且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java 单例和同步

更新时间:2023-12-03 13:37:10

是的,有必要.您可以使用多种方法通过延迟初始化实现线程安全:

Yes, it is necessary. There are several methods you can use to achieve thread safety with lazy initialization:

严酷的同步:

private static YourObject instance;

public static synchronized YourObject getInstance() {
    if (instance == null) {
        instance = new YourObject();
    }
    return instance;
}

这个解决方案要求每个线程同步,而实际上只有前几个需要同步.

This solution requires that every thread be synchronized when in reality only the first few need to be.

双重检查同步:

private static final Object lock = new Object();
private static volatile YourObject instance;

public static YourObject getInstance() {
    YourObject r = instance;
    if (r == null) {
        synchronized (lock) {    // While we were waiting for the lock, another 
            r = instance;        // thread may have instantiated the object.
            if (r == null) {  
                r = new YourObject();
                instance = r;
            }
        }
    }
    return r;
}

此解决方案确保只有前几个尝试获取单例的线程必须经历获取锁的过程.

This solution ensures that only the first few threads that try to acquire your singleton have to go through the process of acquiring the lock.

按需初始化:

private static class InstanceHolder {
    private static final YourObject instance = new YourObject();
}

public static YourObject getInstance() {
    return InstanceHolder.instance;
}

该解决方案利用 Java 内存模型对类初始化的保证来确保线程安全.每个类只能加载一次,只有在需要的时候才会加载.这意味着第一次调用 getInstance 时,将加载 InstanceHolder 并创建 instance,因为这是由 控制的ClassLoaders,不需要额外的同步.

This solution takes advantage of the Java memory model's guarantees about class initialization to ensure thread safety. Each class can only be loaded once, and it will only be loaded when it is needed. That means that the first time getInstance is called, InstanceHolder will be loaded and instance will be created, and since this is controlled by ClassLoaders, no additional synchronization is necessary.