10 Interview Question On Singleton Pattern in Java
10 Interview Question On Singleton Pattern in Java
Singleton is a class which has only one instance in whole application and provides a getInstance () method to
access the singleton instance. There are many classes in JDK which is implemented using Singleton pattern like
java.lang.Runtime which provides getRuntime () method to Get access of it and USED to Get Free memory and
Total memory in Java .
1) Which classes are candidates of Singleton? Which kind of class do you make Singleton in Java?
Here they will check whether candidate has enough experience on usage of singleton or not. Does he is familiar of
advantage / disadvantage or alternatives available for singleton in Java or not.
Answer:. Any class which you want to be available to whole application and whole only one instance is viable is
candidate of becoming Singleton One example of this is Runtime class, since on whole java application only one
runtime environment can be possible making Runtime Singleton is right decision. Another example is a utility
classes like Popup in GUI application, if you want to show popup with message you can have one PopUp class on
whole GUI application and anytime just get its instance, and call show () with message.
2) Can you write code for getInstance () method of a Singleton class in Java?
Most of the java programmer fail here if they have mugged up the singleton code because you can ask lots
of follow-up question based upon the code they have written. I have seen many programmer write Singleton
getInstance () method with double checked locking but they are not really familiar with the caveat associated
with double checking of singleton prior to Java 5.
Answer: Until asked do not write code USING double checked locking as it IS more Complex and Chances of errors
Are more but if you Have Deep Knowledge of double checked locking, volatile variable . Lazy Loading and than
this IS your chance to Shine I Have shared code examples of writing singleton classes USING enum, USING Static
Factory and with double checked locking in My recent post Why Enum Singletons Are better in Java , please See
there.
3) Is it better to make whole getInstance () method synchronized or just critical section is enough? Which
one you will prefer?
This is really nice question and I mostly asked to just quickly check whether candidate is aware of performance trade
off of unnecessary locking or not. Since locking only make sense when we need to create instance and rest of the
time its just read only access so locking of critical section IS Always better option. read more About Synchronization
on How Synchronization Works in Java
Answer:. This is again related to double checked locking pattern, well synchronization is costly and when you apply
this on whole method than call to getInstance () will be synchronized and contented Since synchronization is
only needed during initialization on singleton instance, to prevent creating Another instance of Singleton, It's better
to only synchronize critical section and not whole method. Singleton pattern IS ALSO Closely related to Factory
Design pattern where getInstance () Serves as Static Factory method.
4) What is lazy and early loading of Singleton and how will you implement it?
This is another great Singleton interview question in terms of understanding of concept of loading and cost
associated with class loading in Java. Many of which I have interviewed not really familiar with this but its good to
know concept.
Answer: As there Are many Ways to Implement Singleton like USING double checked locking or Singleton class
with Static Final . instance initialized During class Loading Former IS called Lazy Loading BECAUSE Singleton
instance created only WHEN IS client Calls getInstance () method while later IS called early loading because
Singleton instance is created when class is loaded into memory.
This is open question to all, please share which classes are Singleton in JDK. Answer to this question is
java.lang.Runtime
Answer: There are many classes in Java Development Kit which is written using singleton pattern, here are few of
them:
Answer:. Double checked locking is a technique to prevent creating another instance of Singleton when call to
getInstance () method is made in multi-threading environment In Double checked locking pattern as shown in below
example, singleton instance is checked two times before initialization.
if (_INSTANCE == null) {
// Double checked locking - because second check of Singleton instance with lock
if (_INSTANCE == null) {
return _INSTANCE;
Double checked locking SHOULD BE USED WHEN only you Have requirement for Lazy initialization otherwise use
Enum to Implement singleton or simple Static Final variable.
7) How do you prevent for creating another instance of Singleton using clone () method?
This type of questions generally comes some time by asking how to break singleton or when Singleton is not
Singleton in Java.
Answer: Preferred way is not to implement Clonnable interface as why should one wants to create clone () of
Singleton and if you do just throw Exception from clone () method as "Can not create clone of Singleton class".
8) How do you prevent for creating another instance of Singleton using reflection?
Answer:. This IS Similar to previous question Interview Since constructor of Singleton class IS Supposed to
BE Private it Prevents Creating instance of Singleton from outside but Reflection CAN access Private fields and
Methods ., Which Opens a threat of Another instance This CAN BE Avoided by throwing Exception from constructor
as "Singleton already initialized"
9) How do you prevent for creating another instance of Singleton during serialization?
Another great question Which Requires Knowledge of Serialization in Java and How to use it for Persisting Singleton
classes. This IS Open to you all but in My opinion use of readResolve () method CAN sort this out for you.
Answer:. You can prevent this by using readResolve () method, since during serialization readObject () is
used to create instance and it return new instance every time but by using readResolve you can replace it with
original Singleton instance I have shared code on how to do it in post My Enum as Singleton in Java . This IS ALSO
one of the reason I Have SAID That use Enum to create Singleton BECAUSE serialization of enum IS taken care by
JVM and it Provides guaranteed of That.
There IS a very good Article Present in Sun's Java site Which Discusses Various Scenarios WHEN IS a Singleton
not really Remains Singleton and multiple instance of Singleton IS Possible. Here IS the link of That Article Http://
Java.Sun.Com/developer/ technicalArticles / Programming / singletons /
Apart from these questions on Singleton pattern, some of my reader contribute few more questions, which I included
here. Thank you guys for your contribution.
11) Why you should avoid the singleton anti-pattern at all and replace it with DI?
Answer: Singleton Dependency Injection: every class that needs access to a singleton gets the object through its
constructors or with a DI-container.
Singleton Anti-Pattern:. With more and more classes calling getInstance the code gets more and more tightly
coupled, monolithic, not testable and hard to change and hard to reuse because of not configurable, hidden
dependencies Also, there would be no need for this clumsy double checked locking if you call getInstance less often
(ie once).
12) How many ways you can write Singleton Class in Java?
2) Singleton with public static final field initialized during class loading.
3) Singleton generated by static nested class, also referred as Singleton holder pattern.