Thread safety in Singleton

后端 未结 5 1898
庸人自扰
庸人自扰 2020-11-29 23:00

I understand that double locking in Java is broken, so what are the best ways to make Singletons Thread Safe in Java? The first thing that springs to my mind is:

         


        
5条回答
  •  有刺的猬
    2020-11-29 23:14

    I see no problem with your implementation (other than the fact that the lock for the singleton-monitor may be used by other methods, for other reasons, and thus, unnecessarily, prevent some other thread from getting the instance). This could be avoided by introducing an extra Object lock to lock on.

    This Wikipedia article suggests another method:

    public class Something {
        private Something() {
        }
    
        private static class LazyHolder {
            private static final Something INSTANCE = new Something();
        }
    
        public static Something getInstance() {
            return LazyHolder.INSTANCE;
        }
    }
    

    From the article:

    This implementation is a well-performing and concurrent implementation valid in all versions of Java.
    ...
    The implementation relies on the well-specified initialization phase of execution within the Java Virtual Machine (JVM); see section 12.4 of Java Language Specification (JLS) for details.

提交回复
热议问题