Forum

Thread safety in Singleton

1 Replies Posted since 26/05/2010

  • matt's profile image

    Member
    matt

    8 Posts

    Thread safety in Singleton

    I understand that double locking in Java is broken, so what are the best ways to make Singletons Thread Safe in Java? The first thing that springs to my mind is:

    class Singleton{
    private static Singleton instance;

    private Singleton(){}

    public static synchronized Singleton getInstance(){
    if(instance == null) instance = new Singleton();
    return instance;
    }
    }

    Does this work? if so, is it the best way (I guess that depends on circumstances, so stating when a particular technique is best, would be useful)

  • Matt2k's profile image

    Member
    Matt2k

    9 Posts

    Replied at 14:15 - 26/05/2010

    Re: Thread safety in Singleton

    You should use Strategies, possibly implemented within an enum, e.g.:

    enum UserType {
    ADMIN() {
    public void doStuff() {
    // do stuff the Admin way
    }
    },
    STUDENT {
    public void doStuff() {
    // do stuff the Student way
    }
    };

    public abstract void doStuff();
    }

    As the code structure within each outermost if branch in your code looks pretty much the same, you might want to factor out that duplication into separate template methods in the next step. Alternatively, you might turn Location into an enum strategy as well.

    Update: in Java4, you can implement a typesafe enum by hand, and use plain old subclassing to implement the different strategies.

  •  

    You must be logged in to post replies

  • Page 1 of 1

Back to top

Sunderland Software City, Evolve Business Centre,
Cygnet Way, Rainton Bridge South Business Park,
Houghton Le Spring, DH4 5QY

Site by SUMO