> What would be the result of un-thread safe access at "if 
> (psMap == null) psMap = new HashMap();" ? The Map would be 
> instantiated twice and one of the instantiations would 'win', 
> right? Possibly the Map could be holding one 
> PreparedStatement, and be replaced by the new empty map... 
> resulting in the re-compilation of one PreparedStatement at 
> some future point?
> 
> Could something worse happen?

Unfortunately, yes.  Java's Memory Model is funky and can result in some 
counter-intuitive behavior.  This is an excellent example.

The JVM is allowed to assign to "psMap" *before* completing its construction.  This 
means that one thread can see a non-null "psMap" yet find it unusable because its 
construction hasn't executed.  At best, you'll see an NPE, at worst you'll see 
abnormal behavior.

You can read about it in detail here: 
http://java.sun.com/docs/books/vmspec/2nd-edition/html/VMSpecTOC.doc.html(Section 8, 
Threads and Locks, has most of the meat on this issue).  If you'd rather something 
lighter, pickup a copy of "Effective Java" - its an excellent read and addresses all 
kinds of stuff (and suggests a very creative workaround).  If you read the VM spec and 
are intrigued, check out Doug Lea's util.concurrent code (he deals with the memory 
model idiosyncrasies head on).  

> Same question of unsynchronized access to the HashMap. What 
> should I be concerned about happening? Seems like maybe two 
> threads would try
> Map.get(key) and both get null back, then both create the 
> same PS and place it into the Map, where one would 'win', right?

Your assuming that the get and put are atomic operations.  In a thread unsafe class 
this is not the case.  Consider an implementation that updates 4 internal data members 
on a put() operation and you did a get() after only 2 have completed.  What will the 
result be?  It might mean you see an NPE (or other exception) in the get() operation, 
it might mean you get null or it might mean you successfully get the entry being 
processed.  Its indeterminate.  Of course, the latter two are tolerable a 
RuntimeException isn't.

--rob

_______________________________________________
Juglist mailing list
[EMAIL PROTECTED]
http://trijug.org/mailman/listinfo/juglist_trijug.org

Reply via email to