Singleton is one of the Gangs of Four (GoF) Design patterns and comes in the Creational Design Pattern. From the definition, it seems to be a very simple design pattern but when it comes to implementation, it comes with a lot of implementation concerns. The implementation of Singleton pattern has always been a controversial topic. We will discuss a...

Read More

In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton class. For Runtime class Java uses these approach. Here is the implementation of static initialization singleton class. package java.lang; import java.io.*; import java.util.StringTokenizer; import sun.r...

Read More

The easier way to create a thread-safe singleton class is to make the global access getInstance() method synchronized, so that only one thread can execute this method at a time. General implementation of this approach is like the below class. public class Singleton {          private static Singleton instance;          /* Private constructor ...

Read More

Reflection can be used to destroy all the above singleton implementation approaches.  Let’s  see  this  with  an  example  class. import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class SingletonTest { @SuppressWarnings("rawtypes") public static void main(String[] args) { S...

Read More

The following implementation of Singleton design pattern will handle most of the flaws we made till now. /** * Hard-to-get-it-right implementation of a Singleton supporting lazy * instantiation. */ public class Singleton implements Cloneable { private static final long serialVersionUID = 6462568326558031828L; /* * Marking volatile is necessa...

Read More

To overcome this situation with Reflection, Joshua Bloch suggests the use of Enum to implement Singleton design pattern as Java ensures that any enum value is instantiated only once in a Java program. Since Java Enum values are globally accessible, so is the singleton. The drawback is that the enum type is somewhat inflexible;  for example, it does...

Read More

In this post we will see some more ways to implement Sigleton pattern. This post is contributed by Huba Albu First Solution: Using ReentrantReadWriteLock public final class Singleton { private static final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock(); private static Singleton instance; /* Private constructor to prevent i...

Read More

FOLLOW US ON LinkedIn



Explore Tutu'rself