Singleton and Double-Checked Locking
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Vic_Bancroft
Posted On:   Friday, October 28, 2005 09:23 AM

I had noticed what appears to be an inefficiency in the Singleton design pattern as often discussed and was not comfortable with the "Double-Checked Locking" version. Someone recently pointed out the page of Bill Pugh, (signed by John Mitchell, among others), which details nicely the flaws in that implementation of the Singleton pattern. I had done a variation of the original code as follows, class Foo { private Helper helper = null; public Helper getHelper() { if (helper != null) { return helper; } return constructHelper(); } public synchronized Helper constructHelper() { if (helper == null) { helper = new Helper();    More>>


I had noticed what appears to be an inefficiency in the Singleton design pattern as often discussed and was not comfortable with the "Double-Checked Locking" version.
Someone recently pointed out the page of Bill Pugh, (signed by John Mitchell, among others), which details nicely the flaws in that implementation of the Singleton pattern. I had done a variation of the original code as follows,



			
class Foo {
private Helper helper = null;

public Helper getHelper() {
if (helper != null) {
return helper;
}
return constructHelper();
}

public synchronized Helper constructHelper() {
if (helper == null) {
helper = new Helper();
}
return helper;
}
// other functions and members...
}



Does this have the same problem ?



I will rework the test program and see if it breaks on the machines I have available, though such experiments do not show that this modified version will not break on some other platform and compiler.



more,



l8r,



v

   <<Less

Re: Singleton and Double-Checked Locking

Posted By:   Vic_Bancroft  
Posted On:   Friday, October 28, 2005 09:37 AM


Actually there is a missing static on the member variable . . . perhaps it should read,




class Foo {
private static Foo instance = null;

public Foo getInstance() {
if (instance != null) {
return instance;
}
return constructInstance();
}

public synchronized Foo constructInstance() {
if (instance == null) {
instance = new Foo();
}
return instance;
}
// other functions and members...
}

About | Sitemap | Contact