Your first implementation is not thread-safe, so I think you should go with the second. Or I often saw the following:
I think it is a little bit more efficient since you lock only at the first call.
About cathching or propagating the HibernateException I can't say anything, since I don't know too much about Hibernate.
Probably too difficult a question for "beginning Java". Moving.
What is wrong with having a private static final instance of the class, instantiating it at class loading time, and using a private constructor? That avoids what Miklos Szeles quoted, viz double-checked locking. I have been told this does actually work using the new memory model in Java5, but was unreliable on older versions.
Thanks for pointing me to that description Muhammad. I missed the volatile(my fault) but I wasn't aware of that this implementation is not correct on JVM 1.4(or less). So to summarize the answers:
If it is possible, we should create the object in a static initializator.
If we need lazy initialization for some reason and we are developing for JVM 1.5 or higher, we should use dobule-checked locking and under JVM 1.5 we should simply synchronze the getter method.
Is this correct?
Miklos Szeles wrote:If we need lazy initialization for some reason and we are developing for JVM 1.5 or higher, we should use dobule-checked locking and under JVM 1.5 we should simply synchronze the getter method.
Is this correct?
use the lazy initialization holder class idiom as define in Effective Java.
Joined: Oct 21, 2008
Even if it wasn't me who started the thread, thanks guys for the valuable information. I think my next Java book will be Effective Java
Joined: Oct 13, 2005
Miklos Szeles wrote:I think my next Java book will be Effective Java
Excellent book Another book worth reading is "Java Puzzlers" by Bloch and Gafter.