top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Give example program for Java Singleton - Thread Safe Singleton using Static field Initialization?

+1 vote
357 views
Give example program for Java Singleton - Thread Safe Singleton using Static field Initialization?
posted Apr 28, 2015 by Joy Nelson

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

You can also create thread safe Singleton in Java by creating Singleton instance during class loading. static fields are initialized during class loading and Classloader will guarantee that instance will not be visible until its fully created. Here is example of creating thread safe singleton in Java using static factory method. Only disadvantage of this implementing Singleton patter using static field is that this is not a lazy initialization and Singleton is initialized even before any clients call there getInstance() method.

public class Singleton{
    private static final Singleton INSTANCE = new Singleton();

    private Singleton(){ }

    public static Singleton getInstance(){
        return INSTANCE;
    }
    public void show(){
        System.out.println("Singleon using static initialization in Java");
    }
}

//Here is how to access this Singleton class
Singleton.getInstance().show();

here we are not creating Singleton instance inside getInstance() method instead it will be created by ClassLoader. Also private constructor makes impossible to create another instance , except one case. You can still access private constructor by reflection and calling setAccessible(true). By the way You can still prevent creating another instance of Singleton by this way by throwing Exception from constructor.

answer Apr 29, 2015 by Karthick.c
...