현도연
현도연

Reputation: 65

How to destroy or reset Singleton instance in Java?

Singleton class

public class M_Singleton{
  private volatile static M_Singleton uniqueInstance=null;
  private ArraList<Integer> myArr;

  private M_Signleton{
    this.myArr=new ArrayList<Integer>();
  }

  public static M_Singleton getInstance(){
    if(uniqueInstance==null){
       synchronized (M_Signleton.class){
           if(uniqueInstance==null)
                uniqueInstance=new M_Signleton();
           }
       }
    return uniqueInstance;
  }
  public void deleteInstance(){
     uniqueInstance=null;
  }
}

Main class

M_Singleton ms=M_Singleton getInstance();
//put A-value in "MyArr"
sd.deleteInstance();
//put B-value in "MyArr"

I thought, there would be only B-value in MyArr But there is only A-value.

If I change deleteInstance like this, there is only A-value still.

public void deleteInstance(){
     uniqueInstance=new M_Singleton();
}

How to destroy singleton?

Upvotes: 1

Views: 7091

Answers (2)

shizhen
shizhen

Reputation: 12573

If you really want to stick to Singleton for your case, below is a Java reflection way for resetting your single instance:

public static void setPrivateField(Class clazz, Object inst, String field, Object value) throws Exception {
    java.lang.reflect.Field f = clazz.getDeclaredField(field);
    f.setAccessible(true);
    f.set(inst, value);
    f.setAccessible(false);
}

Just call this method like below wherever you need to reset this singleton:

setPrivateField(M_Singleton.class, null, "uniqueInstance", null);

Upvotes: 0

Sohel S9
Sohel S9

Reputation: 246

make singleton object null for destroy singleton like this

uniqueInstance=null

Upvotes: 2

Related Questions