Search code examples
javaeclipsesingletonsoot

Java Singleton doesn't work


I'm setting a class via SOOT-ECLIPSE plugin as the main class and want it to operate like a singleton. But my implementation seems to not work, as I get different instances one every run.

I tried to use a wrapper and call the singleton class from there in order to avoid the case in which this class is garbage collected by the classloader of soot. But I get different instances, as well.

I confirmed that it runs on one JVM, as the PID that I get on every run is the same in contrast to the instance of the class that changes on every run.

I would really appreciate any insight into this one.

public class MyMain{

    private static boolean isFirstInstance = true;

    private static class MyMainHolder {
        private static final MyMain INSTANCE = new MyMain();
    }

    public static synchronized MyMain getInstance() {
        return MyMainHolder.INSTANCE;
    }

    private MyMain() {
        if (MyMainHolder.INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");
        }
    }


    public static void main(String[] args) {
    System.out.println("PID: " + ManagementFactory.getRuntimeMXBean().getName());

    MyMain tmp = getInstance();
    }

Solution

  • It appears that to OP actually want to be able to discrimiate between the first run of the program, and subsequent ones. This will do that:

    public static void main(String[] args) {
        File file = new File("has_been_run");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // first time
        } else {
            // subsequent times
        }
    }
    

    Obviously, is the file is deleted somehow, then that counts as a "first run" again.

    So could do something similar with any persistent data store that you have available.