Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Double Checked Locking

 
Kalyan Anand
Ranch Hand
Posts: 194
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Initialize-On-Demand
 
Rob Spoor
Sheriff
Pie
Posts: 20510
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sam Yim
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4181
21
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sam Yim
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic