• Post Reply Bookmark Topic Watch Topic
  • New Topic

Singleton without Synchronized menthod ?  RSS feed

 
Karn Kumar
Ranch Hand
Posts: 153
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Can anyone suggest that is it possible to implement the Singleton Design Pattern without synchronized method .

Say i have a method like this in Test class and below is the way to implement Singleton design Pattern



Can anybody suggest that is there anyway to implement Singleton Design Pattern without the static Synchronized method

Thanks and Regards,

Chetan
 
N Sahni
Ranch Hand
Posts: 55
Java Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

One approach could be:


Or other approach could be using synchronize block inside getTestInstance() method. As method level synchronization will lock the class.
 
john sal
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use Enums

 
Karn Kumar
Ranch Hand
Posts: 153
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi john ,


Can you please explain how can it is used to achieve the Singleton design pattern.


Regards,
Chetan
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The JVM will guarantee that there is only ever one instance of each enum value. So if you use an enum to create a singleton all the hard work is done for you. It's as simple as the example john just gave.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!