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();
    }
Jon Skeet
people
quotationmark

(From comments...)

My point is that I want to run this class and get the same instance every time.

It sounds like you have a misconception about what singletons are. If you're running your app twice, i.e.

$ java MyApp
[output]

$ java MyApp
[output]

then those are entirely separate invocations of the JVM. When the first run has finished, there is no instance any more - all the memory allocated by the JVM will have been released.

If you need a persistent object (i.e. one which still exists somewhere even when Java isn't running) then that's a very different scenario, and you should look into serialization - although you still shouldn't expect two applications running on separate instances of the JVM to see the same object in memory.

EDIT: Now that we know you're running under Soot, it's possible that that's creating a separate classloader every time, so you'd get a different instance that way instead. Fundamentally, you need to understand the context in which your code is running, and provide that information (and exactly what you're observing) in the question.

people

See more on this question at Stackoverflow