How to create thread safe Singleton in Java - Java Singleton Example
Thread safe Singleton means a Singleton class which returns exactly same instance even if exposed to multiple threads. Singleton in Java has been a classical design pattern like Factory method pattern or Decorator design pattern and has been used a lot even inside JDK like java.lang.Runtime is an example of Singleton class. Singleton pattern ensures that exactly one instance of class will remain in Java program at any time. In our last post 10 Interview questions on Singleton in Java we have discussed many different questions asked on Singleton pattern, One of them was writing Thread safe singleton in Java. Prior to Java 5 double checked locking mechanism is used to create thread-safe singleton in Java which breaks if one Thread doesn't see instance created by other thread at same time and eventually you will end up with more than one instance of Singleton class. From Java 5 onwards volatile variable guarantee can be used to write thread safe singleton by using double checked locking pattern. I personally don't prefer that way as there are many other simpler alternatives to write thread-safe singleton is available available like using static field to initialize Singleton instance or using Enum as Singleton in Java. Let�s see example of both ways to create thread-safe Singleton in Java.
Comments
Post a Comment
-Berkomentarlah yang baik dan rapi.
-Menggunakan link aktif akan dihapus.