top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How many ways we can write Singleton Class in Java and how to create thread-safe Singleton?

+2 votes
595 views
How many ways we can write Singleton Class in Java and how to create thread-safe Singleton?
posted Oct 19, 2014 by Vikram Luthra

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

1 Answer

0 votes

There are four ways to implement Singleton pattern in Java
1) Singleton by synchronizing getInstance() method
2) Singleton with public static final field initialized during class loading.
3) Singleton generated by static nested class, also referred as Singleton holder pattern.
4) From Java 5 on-wards using Enums

Coming to your second query, I would suggest to go through the article present in Java site which discusses various scenarios when a Singleton is not really remains Singleton and multiple instance of Singleton is possible.

http://java.sun.com/developer/technicalArticles/Programming/singletons/

answer Oct 20, 2014 by Salil Agrawal
...