• Post Reply Bookmark Topic Watch Topic
  • New Topic

Is the Volatile modifier required here?

 
Nikhil Sun
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
venkatesh pendharkar
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!