0% found this document useful (0 votes)
35 views

10 Interview Question On Singleton Pattern in Java

This document discusses 10 common interview questions about the Singleton design pattern in Java. It begins by defining the Singleton pattern and providing an example of how it is used in the Java SDK. It then lists and provides details on 10 frequently asked interview questions about Singleton topics like when to use Singleton, how to implement the getInstance() method, lazy vs eager loading, preventing multiple instances via cloning and reflection, and examples of Singletons in Java code. The questions cover concepts like thread-safety, performance tradeoffs, and how Singletons can fail to be Singletons in certain cases.

Uploaded by

Sunitha M
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

10 Interview Question On Singleton Pattern in Java

This document discusses 10 common interview questions about the Singleton design pattern in Java. It begins by defining the Singleton pattern and providing an example of how it is used in the Java SDK. It then lists and provides details on 10 frequently asked interview questions about Singleton topics like when to use Singleton, how to implement the getInstance() method, lazy vs eager loading, preventing multiple instances via cloning and reflection, and examples of Singletons in Java code. The questions cover concepts like thread-safety, performance tradeoffs, and how Singletons can fail to be Singletons in certain cases.

Uploaded by

Sunitha M
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Design Patterns Questions

10 Singleton Pattern Interview questions in Java - Answered


Singleton pattern in Java is one of the most common patterns available and it's also used heavily in core Java
libraries. Questions from Singleton pattern is very common in Java interviews and good knowledge of how to
implement Singleton pattern certainly help.This is also one of my favorite Design pattern Interview question
and HAS lots of interesting Follow-up to dig into details, this not only check the Knowledge of Design pattern but
ALSO check coding, multithreading Aspect Which IS very Important while working for a real Life Application. In this
post have listed some of the most common question asked on Singleton pattern during a Java Interview. I have not
provided the answers of these questions as they are easily available via google search but if you guys need I can try
to modify this tutorial to include answers as well. As promised earlier and having received lot of request for providing
answers of these question, I have decided to update this post along with answers. By the way if you are preparing
for interview on Java technology than you can check my collection on Java Interview questions and multi-Threading
Interview questions . There Are lot of Resources in Javarevisited Which CAN help you in your Interview Preparation.
On the Other hand if you Are more interested on Design pattern tutorials than you CAN check My post on Builder
Design pattern and Decorator pattern .

10 interview question on Singleton Pattern in Java

Question starts with

What is Singleton class? Have you used Singleton before?

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.

5) Example of Singleton in standard Java Development Kit?

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:

● Java.lang.Runtime with getRuntime () method


● Java.awt.Toolkit with getDefaultToolkit ()
● Java.awt.Desktop with getDesktop ()

6) What is double checked locking in Singleton?


One of the MOST hyped question on Singleton pattern and really Demands Complete Understanding to Get it right
BECAUSE of Java Memory model CAVEAT PRIOR to Java 5. If a guy Comes up with a solution of USING volatile
keyword with Singleton instance and Explains it then it really shows it has in depth knowledge of Java memory model
and he is constantly updating his Java knowledge.

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.

public static Singleton getInstance () {

if (_INSTANCE == null) {

synchronized (Singleton. class) {

// Double checked locking - because second check of Singleton instance with lock

if (_INSTANCE == null) {

_INSTANCE = New Singleton ();

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?

Open to all. In my opinion throwing exception from constructor is an option.

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.

10) When is Singleton not a Singleton in Java?

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?

Answer: I know at least 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

13) How to write thread-safe Singleton in Java?


Answer: Thread Safe Singleton Usually REFERS to write thread Safe code . Which Creates one and only one
instance of Singleton if called by multiple thread at same time There Are many Ways to Achieve this by USING like
double checked locking Technique as shown Above and by USING enum or initialized by Singleton class Loader.

At last few more questions for your practice, contributed by Mansi:

14) Singleton vs Static Class?

15) When to choose Singleton over Static Class?

16) Can you replace Singleton with Static Class in Java?

17) Difference between Singleton and Static Class in java?

18) Advantage of Singleton over Static Class?

You might also like