简体   繁体   中英

Singleton methods thread safe

I have a question Singleton pattern and threads. Implementation is like this.

public class Singleton {
    private static final Singleton instance = new Singleton();

    private SomeClass someField;
    // and  another private fields

    private Singleton() {
        someField = new SomeClass(some args);
        // init another private fields
    }

    public Singleton getInstance() {
        return instance;
    }

    public void operation() {
        //some operations
        someField.method();
    }
}

(Sorry I can not provide real example.) The question is next: is method operation() thread safe?

We have no idea whether it's safe or not - we don't know what someField.method() does.

I would strongly encourage you to make someField a final field, as if the singleton needs to mutate state then it's definitely not thread-safe without extra synchronization. If SomeClass itself is immutable and thread-safe, then you shouldn't need any other synchronization - but otherwise, you will.

Basically, there's nothing "magically thread-safe" about a singleton. It's just a single instance which multiple threads will have access to via the static getInstance() method. If the class is thread-safe, it's thread-safe regardless of whether it's a singleton - and if it's not thread-safe, then making it a singleton won't do anything to help that.

The thread-safety of someField.method(); depends on what it's actually doing. If it's modifying state that is shared among multiple threads then it's not thread-safe. If not, it might be thread-safe. But in general it should not be assumed to be thread-safe. I can't say more without the code.

the answer is not thread safe as answered above. This can be test as the code below !


public class TestSingleton {
public static void main(String[] args) throws Exception {
    ExecutorService pool = Executors.newFixedThreadPool(10);
    for (int j = 0; j < 100000; j++) {
        pool.submit(new Thread() {
            public void run() {

                Singleton.get().add();
            }
        });
    }
    pool.shutdownNow();
    System.out.println(Singleton.get().getcnt());
}

}

class Singleton {
private static Singleton singleton = new Singleton();

int cnt = 0;

private Singleton() {}

public static Singleton get() {
    return singleton;
}

public void add() {
    cnt++;
}

public int getcnt() {
    return cnt;
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM