javasingletonjava-ws

Persistent Singleton Object for Java Web Service


Good morning.

I am currently working on a Java Web Service project, that is deployed on an Apache Tomcat 7 server. For the needs of the project, I need to maintain a global (among WS threads, created by every request) object in memory. Thus, I tried to implement a Singleton design pattern as follows:

public class SingletonDesign {
    private static boolean _instanceFlag = false;
    private static final SingletonDesign _instance = new SingletonDesign();
    private static GlobalObject _myGlobalObject;

    private SingletonDesign() {
        if(_instanceFlag == false) {
            _myGlobalObject = new GlobalObject();
            _instanceFlag = true;
        }
    }

    public static GlobalObject getModel() {
        if(_instanceFlag == false) {
            _myGlobalObject = new GlobalObject();
            _instanceFlag = true;
        }
        return _myGlobalObject;
    }

    public static int parseModel() {
        if(_instanceFlag == false) {
            _myGlobalObject = new ItemSimilarityModel();
            _instanceFlag = true;
        }
        int val = _myGlobalObject.parseFromFile();
        return val;
    }
}

I am aware of the fact that every time a request is done, a new thread would be created on my Web – service class (object). My goal, is to have a global SingletonDesign object among all threads, which stays alive in memory, and is created only once. Despite the fact that the above design seems to be working according to my expectations, I am not really sure if it is correct. So these are my questions:

1) Why do the methods of the SingletonDesign object need to be static? (I have attempted to define them as non-static, but my Singleton object is not initialized properly).

2) The above design is seen from the Wikipedia page on the Singleton Design Pattern. The part that confuses me is the initialization of the _instance field, which I have seen in other Singleton implementations too. Why do we need that object?

3) Does my object stay alive until the server stops? I have made some tests and It seems that it stays alive, but I have to be 100% sure.

Thank you for your time and interest.


Solution

  • The _instance field contains your singleton. You need a static getInstance() method, and your other methods would be instance methods. I don;t think you need the _instanceFlag field at all.

    Then you would call it as follows:

    SingletonDesign.getInstance().getGlobalObject();

    Still, keep in mind that a lot of people (including myself) thing of Singleton as a code-smell. Also, this design is not considered the best way to implement a Singleton in Java, cfr: What is an efficient way to implement a singleton pattern in Java?

    The object will stay alive as long as its classloader stays alive.