| Author |
Double Checked Locking
|
Kalyan Anand
Ranch Hand
Joined: Feb 07, 2007
Posts: 194
|
|
|
I have to implement a singleton in Java 5+ environment. Is there more efficient implementation or some better practice other than DCL ?
|
 |
P. Re
Greenhorn
Joined: Jul 11, 2009
Posts: 1
|
|
|
Initialize-On-Demand
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19230
|
|
1) Use a static holder class:
The SingletonHolder class is only loaded and initialized when first needed, which is on the first call to the getInstance() method. Also, class loading is atomic by itself.
2) Use an enum:
This way the singleton is also automatically safe for serialization.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Sam Yim
Greenhorn
Joined: Jul 25, 2009
Posts: 17
|
|
Rob Prime wrote:1) Use a static holder class:
The SingletonHolder class is only loaded and initialized when first needed, which is on the first call to the getInstance() method. Also, class loading is atomic by itself.
2) Use an enum:
This way the singleton is also automatically safe for serialization.
If the enum singleton contains methods that modify shared member variables, would those methods need to be synchronize?
|
 |
Steve Luke
Bartender
Joined: Jan 28, 2003
Posts: 3087
|
|
Sam Yim wrote:
If the enum singleton contains methods that modify shared member variables, would those methods need to be synchronize?
Yes, no matter what structures you use, if the object is used in multiple threads and the internal data is modified (in ways that will affect other threads' execution) then the code modifying and using the data should be synchronized. Nothing in how an enum works modifies that.
|
Steve
|
 |
Sam Yim
Greenhorn
Joined: Jul 25, 2009
Posts: 17
|
|
Steve Luke wrote:
Yes, no matter what structures you use, if the object is used in multiple threads and the internal data is modified (in ways that will affect other threads' execution) then the code modifying and using the data should be synchronized. Nothing in how an enum works modifies that.
That was my reasoning but wasn't sure. Thanks for the confirm.
|
 |
 |
|
|
subject: Double Checked Locking
|
|
|