• Post Reply Bookmark Topic Watch Topic
  • New Topic

Does it make sense to use volatile for references only accessed inside synchronized blocks?

 
Yuriy Zilber
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For example, in the following code (of a Singleton), is there any reason the instance variables need to be marked volatile to be safe, or is the synchronization sufficient for Java 1.5 code?



The three instance variables' direct references in this case would not be accessed outside of the synchronized block of someMethod(), with all unsynchronized read-only operations taking place using the method-local refererances. In this case, does making them 'volatile' provide any additional safety measure.

Thanks in advance!
Yuriy
 
Henry Wong
author
Sheriff
Posts: 22529
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If all access to a variable is protected by synchronization, then no, there is no need to make the shared variable volatile. As the process of grabbing and releasing the lock will flush and reload the memory caches as needed.

Henry
 
Yuriy Zilber
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!

Will every single memory cache be flushed/reload by any synchronization, or does it need to relate to the object being synchronized on? In my example I am synchronizing on the Singleton instance, but am worried by instance variables of said Singleton. The Map references at the instance level are protected by the synchronization, but later, method-local references to the same underlying Map objects are used for read-only operation without any synchronization.
 
Adam Smolnik
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey.

Do you think about Map someMap and Map someOtherMap; ?
If yes, they are local for every invoking thread so their visibility is promised in scope of the whole someMethod.
Besides you cannot make method-local variables as volatile.

Adam
 
Yuriy Zilber
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All right, thanks!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!