aspose file tools*
The moose likes Threads and Synchronization and the fly likes Double Checked Locking Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Double Checked Locking" Watch "Double Checked Locking" New topic
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: 19552
    
  16

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 - OCEEJBD 6
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: 3967
    
  17

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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Double Checked Locking
 
Similar Threads
i want the source code of servlet where to get it?
Can not compile filter
Servelet instances created in web.xml
servlet source code
Better way to check user session