aspose file tools
The moose likes Threads and Synchronization and the fly likes Is the Volatile modifier required here? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Is the Volatile modifier required here?" Watch "Is the Volatile modifier required here?" New topic
Author

Is the Volatile modifier required here?

Nikhil Sun
Ranch Hand

Joined: Nov 13, 2005
Posts: 108
I know that global variables are shared between threads.

Consider the below code:

The volatile keyword is used so that inter thread communication is facilitated without the local memories of the threads involved coming into the picture.Only the main memory is used to access/store the variable's data.
But if global variables are already shared between threads then is the volatile keyword absolutely necessary or is it an implementation dependent usage?


[HENRY: Added code tags]
[ October 25, 2006: Message edited by: Henry Wong ]
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
Looking briefly at your code, it looks like the use of "volatile" is appropriate here. A valid alternative would be to protect all accesses of "finished" by synchronisation. But "volatile", in this case, is neater.

If access to "finished" were neither protected by "volatile" nor by synchronisation, then the code might or might not work, depending on the particular JVM and sheer luck.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P
venkatesh pendharkar
Ranch Hand

Joined: Apr 29, 2006
Posts: 104
hi,
I would like to know whether volatile keyword is really important or not.Because i really do not know whether under any particualr situation the compiler starts optimizing values for a variable.I guess if we know exactly in which situations ,optimization of a vaiable is going to happen then we can use volatile keyword under these situations as unnecessorily using volatile keyword can waste CPU time.
 
I agree. Here's the link: jrebel
 
subject: Is the Volatile modifier required here?
 
Similar Threads
Insights into synchronization
notify() question from Nikos
Thread priorities and Daemon threads
Confused about Thread synchronization
thread doubt