File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/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
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: 19718
    
  20

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: 4181
    
  21

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Double Checked Locking