• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

Novice way to implement a Singleton

December 3, 2010 //  by Krishna Srinivasan//  Leave a Comment

I believe everyone starts (and even continues to do so) implementing Singleton pattern in following fashion:

package com.singleton;

public class SimpleSingleton {
 private static SimpleSingleton simpleSingleton;

 private SimpleSingleton() {
 };

 public static SimpleSingleton getInstance() {
  if (simpleSingleton == null)
   simpleSingleton = new SimpleSingleton();
  return simpleSingleton;
 }
}

also read:

  • Java Tutorials
  • Java EE Tutorials
  • Design Patterns Tutorials
  • Java File IO Tutorials

Do you find any problem in it?

Well, I have!!! The contract of Singleton class can be broken.
Let’s discuss Singleton pattern in Simple Threaded environment and then in next post I will discuss this pattern in Multithreaded environment.

In a Single Threaded Environment

Do you remember the double edge sword in Java, “REFLECTION”?
With the help of reflection, one can very easily breach the singleton contract for above class and create as many instance as he wants. Let’s consider following three statements:

//Get Private Constructor
  Constructor pvtConstructor = Class.forName(
    "com.singleton.SimpleSingleton").getDeclaredConstructors()[0];

  //Set its access control
  pvtConstructor.setAccessible(true);

  //Invoke Private Constructor
  SimpleSingleton notSingleton = (SimpleSingleton) pvtConstructor
    .newInstance(null);

Here is a summary what is happening in above statements

  • First statement retrieves the Constructor object for private constructor of SimpleSingleton class.
  • Since the constructor retrieved is a private one, we need to set its accessibility to true.
  • Last statement invokes the private constructor and create a new instance of SimpleSingleton class.

Clearly, we have breached the contract of Singleton class. So, how to overcome this problem?
Well, prior to Java 1.5, there was no way (at least in my knowledge, but Java Universe is so big that I can’t say with 100% surity 🙂 ) to save a singleton class from Reflection mechanism. In Java 1.5, a new kind of classes were introduced, “Enum”.

Unlike Classes, an Enum has fix number of objects and since this restriction is implemented by JVM’s native libraries, hence it is unbreakable. Let’s see an example:

public enum SampleEnum {
 ONLY_INSTANCE();
}

Now let’s try to create an object of SampleEnum using reflection:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class enumTest {
 public static void main(String[] args) throws ClassNotFoundException,
   IllegalArgumentException, SecurityException,
   InstantiationException, IllegalAccessException,
   InvocationTargetException {
  Constructor c1 = Class.forName("SampleEnum").getDeclaredConstructors()[0];
  c1.setAccessible(true);
  SampleEnum e1 = (SampleEnum) c1.newInstance(null);
 }
}

On running this example, it will throw an exception:

Exception in thread "main" java.lang.IllegalArgumentException: Cannot reflectively create enum objects
 at java.lang.reflect.Constructor.newInstance(Constructor.java:511)
 at enumTest.main(enumTest.java:11)

Clearly, you can’t create an object of Enum type.

Hence, we can conclude that best way to implement a Singleton pattern is by using Enum. It is simple, straightforward and unbreakable.

Category: JavaTag: Core Java

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Previous Post: « What is Remote Debugging in Java?
Next Post: What is Immutable Objects in Java? »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact