Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Singleton pattern - volatile doubt  RSS feed

 
ankur rathi
Ranch Hand
Posts: 3830
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please consider the following code from HFDP book:



I don't understand the need of volatile keyword here?

Can anyone explain?

Thanks.
[ April 20, 2007: Message edited by: ankur rathi ]
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This isn't easy to explain. In fact, it seems that this solution might in fact not work as expected.

The problem is in subtle side effects of multi-threading - for optimization reasons, the processor is allowed to reorder operations, as long as the effect is the same *for the current thread*. Another effect is the use of memory that is local to a thread (for example processor registers), so that changes aren't immediately visible to all other threads.

The consequence is that other threads can see inconsistent states, for example a reference to an inclompletely initialized object. Synchronization and the volatile keyword are tools to control those effects.

See http://www-128.ibm.com/developerworks/library/j-dcl.html

Does that help?

(I will move this to our Threads forum, where the experts will be able to correct me... )
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Ilja]: In fact, it seems that this solution might in fact not work as expected.

Indeed, it doesn't work reliably on JDK's prior to JDK 5; this is acknowledged in a "Watch It!" blurb at the bottom of the page in HFDP (p. 182). Note that the Developerworks article linked above is from 2002. The revised Java memory model that came out with JDK 5 did strengthen the semantics of volatile, such that the double-checked locking code above should work for JDK 5 and later. See the JSR-133 FAQ for more info.

I'm perplexed as to why HFDP omitted the Initialization On Demand Holder idiom, as it's easier to understand and code, and works for earlier JDK's as well.


I'm also a bit irritated that p. 180 has them repeating the "I heard synchronization is expensive" myth without pointing out that it's much faster now than it was in the earliest days of Java, and it's really pretty rare that synchronization would cause a perceptible performance problem in a short method like getInstance(). Too much bad, convoluted code has been written by people bending over backwards to avoid synchronization. (Especially prior to JDK 5 and the java.util.concurrent packages.) Grumble, grumble.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!