PearsonArtPhoto
PearsonArtPhoto

Reputation: 39698

Singleton returning multiple instances

I have a singleton class that is returning multiple instances, and I can't figure out how. It is likely that there are multiple threads calling on the singleton class, but if that is the case, I'm not sure how I can make it work properly. Here's some of the code.

public class SomeClass{
    private static final String TAG="someClass";

    private volatile static SomeClass instance = new SomeClass();

    public static synchronized SomeClass getInstance() {
        Log.v(TAG,"Returning instance "+instance);
        return instance;
    }

    private SomeClass() {
        //Some initialization here
    }
    @Override
    public String toString() {
        StringBuilder sb=new StringBuilder();
        sb.append("this="+System.identityHashCode(this));
        return sb.toString();
    }
}

And my logs look like this:

11-02 12:50:04.494: V/someClass(12882): Returning instance this=1386326216
11-02 12:50:04.518: V/someClass(12900): Returning instance this=1384153464

I don't understand how I can have 2 instances, given how I'm setting this up. Any ideas?

Upvotes: 1

Views: 132

Answers (2)

PearsonArtPhoto
PearsonArtPhoto

Reputation: 39698

The problem, as @CommonsWare guessed, is that I have two processes running, causing two class loaders in effect, which is a known boundary to the singleton process. The solution is to remove the android:process tag from the service I use in my class, to make sure that there is only a single instance.

Upvotes: 1

Hobbyist
Hobbyist

Reputation: 16192

The original code never actually made use of a Singleton, instead you created a new instance of the class and set it to a static variable, thus changing the static instance. The code below checks to see if the Singleton is already set, and if it is, it will return the instance of the original class.

public class SomeClass{

    private volatile static SomeClass singleton = new SomeClass();

    public static synchronized SomeClass getSingleton() {
        Log.v(TAG,"Returning instance "+singleton);
        return singleton;
    }

    private SomeClass() {
        if(singleton == null) {
            singleton = this;
        } else {
            singleton = getSingleton();
        }
    }
    @Override
    public String toString() {
        StringBuilder sb=new StringBuilder();
        sb.append("this="+System.identityHashCode(this));
        return sb.toString();
    }
}

You're never initiating a Singleton,

Upvotes: 0

Related Questions