8

I have a singleton class:

public class Singleton {
    private static Singleton istance = null;

    private Singleton() {}

    public synchronized static Singleton getSingleton() {
        if (istance == null)
            istance = new Singleton();
        return istance;
    }

    public void work(){
            for(int i=0; i<10000; i++){
                Log.d("-----------", ""+i);
            }
    }
}

And multiple Threads are calling the work() function:

public class Main {

public static void main(String[] args) {

    new Thread (new Runnable(){
        public void run(){
            Singleton s = Singleton.getSingleton();
            s.work();}
    }).start();

    System.out.println("main thread");

    new Thread(new Runnable() { 
         public void run() {
             Singleton s = Singleton.getSingleton();
                s.work();
         }
    }).start();
}
}

I noticed the two Threads are running concurrently, as if two work functions were instantiated at the same time.

I want the last thread to be run in place of the previous thread, rather then concurrently. Is it possible in java to make the second call override the memory space of the first call?

4

6 回答 6

20

Your getSingleton() method is attempting to lazily initializing the SINGLETON instance, but it has the following problems:

  • Access to the variable is not synchronized
  • The variable is not volatile
  • You are not using double checked locking

so a race condition AMY cause two instances to be created.

The best and simplest was to safely lazily initialize a singleton without synchronization is as follows:

private static class Holder {
    static Singleton instance = new Singleton();
}

public static Singleton getSingleton() { // Note: "synchronized" not needed
    return Holder.instance;
}

This is thread safe because the contract of the java class loader is that all classes have their static initialization complete before they may be used. Also, the class loader does not load a class until it is referenced. If two thread call getSingleton() simultaneously, the Holder class will still only get loaded once, and thus new Singleton() will only be executed once.

This is still lazy because the Holder class is only referenced from getSingleton() method, so the Holder class will only be loaded when the first call to getSingleton() is made.

Synchronization is not needed because this code relies on the class loader's internal synchronization, which is bullet proof.


This code pattern is the only way to fly with singletons. It is:

  • The fastest (no synchronization)
  • The safest (relies on industrial strength class loader safety)
  • The cleanest (least code - double checked locking is ugly and a lot of lines for what it does)


The other similar code pattern (equally safe and fast) is to use an enum with a single instance, but I find this to be clumsy and the intention is less clear.

于 2012-10-14T00:41:33.773 回答
5

As @amit stated in a comment your getSingleton() method should be synchronized. The reason for this is that it is possible for multiple threads to ask for an instance at the same time and the first thread will still be initializing the object and the reference will be null when the next thread checks. This will result in two instances being created.

public static synchronized Singleton getSingleton() {
    if (istance == null)
        istance = new Singleton();
    return istance;
}

Marking your method as synchronized will cause it to block and only allow one thread at a time to call it. This should solve your problem.

于 2012-10-13T23:45:44.147 回答
1

Either use synchronized on the factory method

public class Singleton {
    private static Singleton istance = null;

    private final Singleton() {} // avoid overrides

    public static synchronized Singleton getSingleton() {
        if (istance == null)
            istance = new Singleton();
        return istance;
    }

    public void work() { // not static, otherwise there's no need for the singleton
        // ...
    }
}

or, simply, use a private final initializer (instantiation will happen at class-load time)

public class Singleton {
    private static final Singleton istance = new Singleton(); // class-load initialization

    private final Singleton() {} 

    public static Singleton getSingleton() { // no need for synchronized
        return istance;
    }

    public void work() { 
        // ...
    }
}
于 2012-10-13T23:53:11.827 回答
0

Resource holder given in Java Concurrency In Practice:http://www.javaconcurrencyinpractice.com/ is the best non-blocking singleton pattern available. The singleton is lazily initialized (both SingletonHolder and Singleton class is loaded at Run-Time when the getInstance() method is called the first time) and the access-or method is non-blocking.

public class SingletonFactory {

private static class SingletonHolder {
    static Singleton instance = new Singleton();
}

public static Singleton getInstance() {
    return SingletonFactory.SingletonHolder.instance;
}

static class Singleton{
}

}

于 2012-10-14T04:17:47.833 回答
0

I came up with this code that is doing pretty much what I needed. The orignal question was "Is possible to do the following without using threads? But rather by directly manipulating the memory with the language?" If the answer is no, maybe you can help me improve the following:

public class Main {
private static Thread t;
public static void main(String[] args) {
    work();
    for (int i =0;i<100; i++);
    System.out.println("oooooooooooooooooooooooooooooooooooooooooo");
    for (int i =0;i<100; i++);
    work();
    for (int i =0;i<500; i++);
    System.out.println("oooooooooooooooooooooooooooooooooooooooooo");
}

public static void work(){
    if (t != null) t.interrupt();
    t= new Thread (new Runnable(){
            public void run(){
                // Pause for 4 seconds
                try {
                    Thread.sleep(600);
                } catch (InterruptedException e) {
                    // We've been interrupted: no more messages.
                    return;
                }
                for(int i=0; i<10000; i++){
                    System.out.println(i);
                }
            }
            });
    t.start();
}
}

This code is useful to "debounce" multiple calls to a listener, firing in a burst on user inputs. It has the disadvantages it uses a sleep function. The sleep time should be high enough to prevent events in a burst to start execution of the time consuming task (only the last event should). Unfortunately there is no guarantee that this can always happen even for a large sleep time.

于 2012-10-14T14:11:36.133 回答
0

You can use Locks around the shared resources. Use the Reentrant class. It prevents race conditions for multiple threads.

于 2018-05-01T19:26:41.967 回答