• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

singleton with lazy initialization

 
Max White
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,
I have the following doubt in the singleton pattern.

Kindly ignore the typing errors in the above code.The point at issue is, if we write the code as I did above, it results in double-checked locking.
So, if I change the code as shown below, would it be correct & free from double-checked locking?


Second,how to implement the singleton in a distributed environment(more than one jvm) so that there is only one instance of Singleton class.
Thanks.
 
Junilu Lacar
Bartender
Posts: 7480
50
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
 
Max White
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am sorry Junilu.
I know about the recent changes.My question was out of curiosity.
As you can see in the code , whats the need of having synchronized block after the line which checks for not null instance?
What if we put the not null check within the synchronized block?

Second,how to implement the singleton in a distributed environment(more than one jvm) so that there is only one instance of Singleton class.

Thanks for your time.
 
Junilu Lacar
Bartender
Posts: 7480
50
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think this link: http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html will help explain the first question better than I can.

As for the "true" singleton question, the first thing that pops in my head (which may not necessarily be the best way) involves a web service implementation and a proxy/gateway that you distribute for use by all the JVMs that want to access the singleton.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic