File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Test question - need help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Test question - need help" Watch "Test question - need help" New topic

Test question - need help

david andrew

Joined: Sep 20, 2005
Posts: 2
Consider the following class:

public class Foo{
private static Foo mInstance;
public static Foo getInstance(){
if(mInstance == null){
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

Joined: Jul 08, 2003
Posts: 24195


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:

[Jess in Action][AskingGoodQuestions]
david andrew

Joined: Sep 20, 2005
Posts: 2
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.
I agree. Here's the link:
subject: Test question - need help
jQuery in Action, 3rd edition