The requirements didn't say about this, but i changed these three variables to volatile: - static DrugController drugController (in Solution class) - static boolean isStopped (in Solution class) - static Map<Drug, Integer> allDrugs (in DrugController class). My solution was accepted with these changes. But, I don't know, were these changes necessary? Maybe the task would have passed by validation without these changes too - I can't know it. But my thought process was that these three variables are used by all the threads, and so it's better to change them to volatile.
Is the 'volatile' keyword necessary in this task or not?
You must be signed in to leave a comment
8 September 2021, 20:20
If you want to hear my crazy opinion... yeah, let's go... hihihi 1. drugController is never changed. It just stores a reference to the DrugController object. So no refreshing of the registers/ caches is needed. 3. allDrugs, here all (relevant) access is done in synchronized blocks. And synchronization includes refreshing registers (volatile functionality). The access to allDrugs in getRandomDrug is not synchronized so you might think to either synchronize it or add volatile but no. The final checks are done inside the buy and sell methods (that are synchronized). 2. So there's just the isStopped boolean left. Now you could argue that this needs register and cache flushing no matter what. But keep in mind that there is a call to the buy method inside the while(!isStopped) loop. The buy method is synchronized and already takes care of updating the registers (all variables are updated). So I don't think (no, I'm sure) the volatile keyword is necessary here either (however I added it nevertheless in my solution). Three times no for you but I still hope I was able to help you... yum yum yum di dum and arghh (cause multithreading drives me crazy - is this even possible? Crazy, crazier - ahhh - I'm lost 😜🤪)