Java Singleton Design Pattern Best Practices with Examples

This week blog post is about Java Singleton design pattern. The reasons for Singleton pattern are to restricts the instantiation of a class and ensures that only one instance of the class exists. This article explains and show examples of the many different approaches of Singleton pattern implementation, the problems with the approach.

The approaches of Singleton pattern implementation:

  1. Eager initialization – pros: easiest way to create a singleton class | cons: instance variable is created even though it might not be used.
  2. Static block initialization – Similar to eager initialization but provides option for exception handling.
  3. Lazy initialization – This is the approach that was we used in class and it’s a completely fine for a single threaded environment, but potential can cause problems for a multi-threaded environment.
  4. Thread Safe Singleton – resolutions for Lazy initialization but reduces performance. Requires synchronization.
  5. Bill Pugh Singleton implementation – Best method for singleton implementation. Contains a inner static helper class by doing so the instance is not created unless someone calls on the getInstance() method. Doesn’t require synchronization.
  6. Using Reflection to destroy Singleton Pattern – This approach destroyed the singleton pattern.
  7. Enum Singleton – resolution for reflection method. Not flexible. Any enum value is instantiated only once.
  8. Serialization and Singleton – Use to store it in file system to retrieve it later. Cons: when deserialize it creates a new instance of the class.

I found this article very helpful with understanding Singleton design. This article explains to me when to use and the consequences that comes with each different implementation. The content of this blog was the best. The example code of this article was very clear and made easier to understand the materials. This change my way of using this method because I now know which method to choose in certain situation. The lazy initialization will be used more while I’m in school, but I think Bill Pugh method will be used more in the future because it’s very popular and it’s easy to understand. I agree with all the contents, but I read the comments of the other readers and they had some issue with some of the content which I have to read more about the subject to find out what’s right and wrong.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s