• Post Reply Bookmark Topic Watch Topic
  • New Topic

Is this program safe with DCL in singleton?  RSS feed

 
xie yufei
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Is this program safe with DCL in singleton?
[ June 12, 2006: Message edited by: xie yufei ]
 
Satish Chilukuri
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I assume you are referring double checked locking as DLC. It doesn't guarantee that only one instance will be created. This article explains how double checked locking can fail. It has something to do with the java memory model. It is supposed to have been be fixed with Java 1.5 but it seems that there is some additional overhead invovled and is not worth using.

Bottom line: avoid using double checked locking. Instead you can do somthing like this:


The createInstance() method will have the logic for creating a new Object adn will return its reference.
[ June 12, 2006: Message edited by: Satish Chilukuri ]
 
xie yufei
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for your instruction, Satish Chilukuri!
I have seen that the double checked locking method not suit for java, but I saw this program in an book of web program instruction,so I am not sure it is right or not.Now I Know it and thanks for giving an explanation.
And can I program this way to realize sinleton?


[ June 12, 2006: Message edited by: xie yufei ]

[ June 12, 2006: Message edited by: xie yufei ]
[ June 12, 2006: Message edited by: xie yufei ]
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
DCL is fundamentally broken, its not a Java issue. Its much worse for other languages. With Java you can look at the spec to see if this is legal or not. With a language like c or c++ you would have to look at your target environment which is basically the CPU specificaiton or the OS, depending on what you are writing for.
 
Kevin Huang
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
YuFei, your java code won't compile. First, method createInstance() should be static; second, local variable STfactory is referenced outside its declaration scope.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!