Singleton returning multiple instances

我怕爱的太早我们不能终老 提交于 2021-01-28 07:12:50

问题


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?


回答1:


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.




回答2:


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,



来源:https://stackoverflow.com/questions/26699511/singleton-returning-multiple-instances

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!