• Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread may not access the most recent version of a variable without sync?  RSS feed

 
Henry Zheng
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys,

I read the "Effective Java" the other day and got quite confused with the threading section.

The author wrote that without synchronization, change on a variable made by one thread is not guaranteed to be visible to other threads, even they made their accesses after the change had token place.

How come this could happen? The threads access a variable might not get the most recent version of it without synchronization?

Really hope someone could shed some light.

Thanks!
 
David Weitzman
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The value of a field will be stored off in the heap somewhere. Suppose that a certain field is an integer, and one of your methods does some math with it, changing it a few times in the process. Since register access is much faster than digging in the heap, the JIT would like to load the value from the heap into a register, do some processing on it, and push it back into the heap once the sequence of changes is done. Or perhaps the value doesn't change, but it's accessed a lot of times in a short period and keeping it in a register would save a lot of work fetching data from the heap. The Java memory model allows threads to cache field values to allow optimizations in these circumstances.

Fields declared with the "volatile" modifier won't be cached, which can sometimes save you from needing to synchronize a block (for example, in the double-checked locking idiom). If you synchronize, though, you can be sure that all the values you use will be loaded fresh from the heap the first time you use them and will be flushed back to the heap when the block finishes executing.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!