Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Test question - need help

 
david andrew
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following class:

public class Foo{
private static Foo mInstance;
public static Foo getInstance(){
if(mInstance == null){
synchronized(Foo.class){
if(mInstance == null){
mInstance = new Foo();
}
}
}
return mInstance;
}
}
a. What design pattern(s) are used in class Foo?

b. Will this work in all environments? If not, under what condition will this fail?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

Foo is using the "Singleton" design pattern, which wants to insure that only one instance of class Foo will ever be created.

However, it uses an idiom called "double-checked locking," which famously can fail to work properly. The reasons are reasonably complicated, but it boils down to this: creating and initializing an object is a two step process: first memory is allocated, and then the constructor is called. It's possible, when using this idiom, that getInstance() will return the Foo object when it's been allocated, but before it's been constructed, so that its member data won't have been initialized yet. Only some JVMs are prone to this, but since you never know about where your code will run, this isn't safe to do, ever.

Instead, just do this:

 
david andrew
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot, that makes sense. I have been reading and studying threads, class constructors and design patterns all morning, but couldn't formulate a decent answer. Thanks again.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic