Singleton design pattern is one of the most common patterns you will see in Java applications and it’s also used heavily in core Java libraries. Questions from the Singleton pattern are very common in Java interviews and good knowledge of how to implement the Singleton pattern certainly helps. This is also one of my favorite design pattern interview questions and has lots of interesting follow-ups to dig into details, this not only checks the knowledge of design pattern but also checks to code, multithreading aspect which is very important while working for a real-life application.
In this post has listed some of the most common questions asked on Singleton pattern from several Java Interviews I have given.
In this post has listed some of the most common questions asked on Singleton pattern from several Java Interviews I have given.
For many questions I have provided answers but I have not provided all the answers to 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 have received a lot of requests for providing answers to these questions, I have decided to update this post along with answers.
By the way, if you are preparing for an interview on Java technology than you can check my collection on Java interview questions and multi-threading interview questions.
There are also a lot of resources in Javarevisited which can help you in your interview preparation. On the other hand, if you are more interested in design pattern tutorials than you can check my post on builder design pattern
Answer : Any class which you want to be available to whole application and whole only one instance is viable is candidate of becoming Singleton.
Double checked locking should only be used when you have requirement for lazy initialization otherwise use Enum to implement singleton or simple static final variable.
Answer : Preferred way is not to implement Cloneable 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”.
Answer: This is similar to previous interview question.
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.
18) Can you replace Singleton with Static Class in Java?
19) Difference between Singleton and Static Class in java?
20) Advantage of Singleton over Static Class?
I have covered answers of couple of these questions in my post, Singleton vs Static Class in Java - Pros and Cons. If you like to read more Java interview questions you can have a look on some of my favorites below
More questions:
133+ Java Interview Questions from Last 5 years (questions)
50+ Java Multithreading Questions from Last 3 years (questions)
50+ Programmer Phone Interview Questions with answers (more)
There are also a lot of resources in Javarevisited which can help you in your interview preparation. On the other hand, if you are more interested in design pattern tutorials than you can check my post on builder design pattern
10 Interview question on Singleton Pattern in Java
Here is my collection of interview questions based upon Singleton design pattern. They are collected from various Java interviews and highlights key aspects of pattern and where it is broken, if you know how to create thread-safe singletons and different ways to implement this pattern, and pros and cons of each approach. Questions starts with :1. 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.2. Which classes are candidates of Singleton? Which kind of class do you make Singleton in Java?
Here they 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.
3. 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 don’t 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 and lazy loading than this is your chance to shine.
Answer : Until asked don’t 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 and lazy loading 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.
4. 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.
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.
5. 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 is created only when client calls getInstance() method while later is called early loading because Singleton instance is created when class is loaded into memory.
6. Give me some examples of Singleton pattern from 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()
7. 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.
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. See here to learn more about double-checked-locking in Java.
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 only be used when you have requirement for lazy initialization otherwise use Enum to implement singleton or simple static final variable.
8. 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 Cloneable 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”.
9. 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 interview question.
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”
10. 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 my post 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.
11. 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 a Singleton is 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.
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.
12. 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.13. Why Singleton is 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 (i.e. once).
14. How many ways you can write Singleton Class in Java?
Answer : I know at least four ways to implement Singleton pattern in Java- Singleton by synchronizing getInstance() method
- Singleton with public static final field initialized during class loading.
- Singleton generated by static nested class, also referred as Singleton holder pattern.
- From Java 5 on-wards using Enums
15. 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 like by using double checked locking technique as shown above and by using Enum or Singleton initialized by class loader.
At last few more questions for your practice, contributed by Mansi, Thank you Mansi
16. Singleton vs Static Class? What are differences
I have already talked about it here,
17. When to choose Singleton over Static Class?
The choice between a Singleton and a Static Class hinges on the nature of your application's requirements. Opt for a Singleton when you need to ensure a single instance of a class and a centralized point of access.
It's valuable for managing shared resources like configuration settings or connection pools. Singleton also supports lazy initialization, creating the instance only when necessary.
On the other hand, a Static Class is fitting for situations where you have a collection of related utility functions or constants that don't rely on instance-specific state.
These classes encapsulate stateless operations and are accessed through the class itself, making them suitable for grouping related functionalities. The decision ultimately boils down to the specific needs and design principles of your project.
18) Can you replace Singleton with Static Class in Java?
19) Difference between Singleton and Static Class in java?
20) Advantage of Singleton over Static Class?
I have covered answers of couple of these questions in my post, Singleton vs Static Class in Java - Pros and Cons. If you like to read more Java interview questions you can have a look on some of my favorites below
More questions:
133+ Java Interview Questions from Last 5 years (questions)
50+ Java Multithreading Questions from Last 3 years (questions)
50+ Programmer Phone Interview Questions with answers (more)
63 comments :
just don't use singletons ;)
it just makes your code hard to test, use, debug.
let spring instantiate these kind of resources and take care of keeping it singleton... or not.
I am most possibly wrong. Just wanted to clarify.
Is it true, that synchronization is needed only during creation time? AFAIK it's required at all times, when object is mutating. And, as with LinkedHashMap's querying methods, reading alone can be considered as a mutation:
"In access-ordered linked hash maps, merely querying the map with get is a structural modification."
So, are You sure it's correct?
Why all this talk about singletons w/ static methods like 'getInstance'. For some odd reason I cannot understand DZone gets linked singleton related articles way too often per week.
If you ever have to use singleton pattern as discussed here you are way off the grid. Application level sigletons are great, you reference them through an (stateless) interface, you get them from what ever context or DI you run in (servletContext, Spring's ApplicationContext).
BTW your answer to question three is just wrong. If you only lock for the critical section (you say it's the instantiation) you'll first check if the field is null without synchronization THEN apply synchronization and check again, if still null, go ahead and instantiate. This double-checking idiom comes from Java 1.0 when synchronization was expensive and while it might work, it has nothing to do with best practices.
Accessing single field via synchronized method is simply free in any application using singleton with #getInstance() method. You cannot even measure the overhead.
You should read Java Concurrency In Pratice -- and only ask someone about singleton the question 'when should you apply JVM level singletons?', correct answer would be '[implicitly] when using enums or never'.
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
@ First Anonymous , thanks you liked the post.
@ Second Anonymous, Agree Spring has better handling for Singleton but in the absence of Spring , Singleton still is a powerful pattern and it come very handy in many scenario.
@Eurekin ,In General you would like to synchronize any write operation whether its creation or modification to protect integrity of data. in case of Singleton , instance is not modified once it gets created, it only gets read or accessed so no need of any further synchronization, it's just only slows down access to getInstance() method .
Or, just use enums and you don't have to think about any of these issues.
http://rkovacevic.blogspot.com/2011/02/easy-singletons-in-java.html
I think you mean 'guard against' rather than 'prevent for'?
Also, I agree with the poster above, singleton is one of the most abused patterns in existence because it's the first one most junior programmers discover. It makes code horrible to unit test - as does anything holding state with static (global) scope.
Just say no kids. Just say no.
A Nice collection of questions on the Singleton Pattern. Great Job!!!
Some more questions on the other J2EE Design Patterns can be found by Clicking Here
Anand.
For question no. 5 answer is Runtime.
Runtime class is an example of singleton pattern and available in jdk.
Apart from Singleton pattern in java which other pattern is more important on interview point of view ?
This is really an excellent set of interview questions around Singleton design pattern in Java, Why not you cover other design pattern as well e.g. Factory, AbstractFactory and Model View Controller. Singleton is the simplest out of lot but still so many interview questions just amazed.
As per Joshua Bloch's book "Effective Java" singletons can and should be coded using Java Enums.
Javin Paul is trying be intelligent by only putting questions and wants to prove that he is a senior guy. Javin dont show your intelligence in this way... if you know any thing (answers) please share but don't try to show you are smart.
Hi Anonymous, I am not trying to be smart. If you read my blog and other post I share what I know but I never claim that I know everything.Even I write blog to keep thinking and revising mate, Its all continuous process or learning and improving yourself.
Another question I missed is how to write thread-safe Singleton in Java? I guess you already address writing Singleton but this question would be more specific. also you can include How to use Enum to write Singleton in Java? because that's another way to write thread-safe Singleton in Java.
hello sir this is absolutely right... thanks
priya
Singleton pattern is based on "Skeleton" patter. It was used extensively in COBOL development during late 70's.
Do google. Amazing how sun folks copied so much from COBOL. Dont forget the "Skeleton Pattern"
This is my feedback on "interview questions" focus..some of this is very helpful and thanks for that. But most of the so called interview questions doesn't make any sense for a really experienced person. I have been working in Java in investment banking for more than 10 yrs and I can't answer most of these "questions" and I have worked on developing high quality crticial trading and risk systems in various investment banks. I have seen many people such as Javin taking pleasure in asking these sort of questions in interviews and validating themselves. I have seen many people talk the tech talk but never really walk the walk. people focus on such useless details and they loose the focus on actual stuff and don't understand the big picture or business need and there wouldn't be single system they have delivered and if it is delivered it is pretty guaranteed useless but still runs in prod and doesn't serve any business purpose. These questions just shows too much focus on nothing but validating technical egos. In reality analytical skills and ability to learn and understand new things in short period of time on demand or mostly thinking on their feet are needed to do an IT job satisfactorily. Anybody can ask questions and answering or not answering most of these questions doesn't tell you if a person is right for the job. IMO lot more is needed than just answering how a hashmap works or difference between static and non-static sync. With so many good frameworks outthere, there is no need to waste time in knowing such low level things. Where does it end? is JVM inner workings next? or is it how transistors in an integrated chip work when use a hashmap?
Can't agree more with the last person's comments.
But unfortunately sometimes we are asked those questions and we must be prepared. I am currently looking for a new position in a different company.
And I must say this blog is very useful.
Thanks,
Jasmine
useless, you just raise a good question but do not provide answer.
blah
@yoha, Its for practice mate, you need to do some hard work to find the answers, most of the answers are already available, let me know if you didn't find any answer and I can help you with that.
In following code,
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
why we declare `instance` as static?
@Anonymous, 'instance' is declared so that it can be initialized during class loading, that will make the creation of Singleton instance thread-safe, otherwise if you want to load your Singleton lazy than you need to employ double checked locking pattern or simply use Enum as shown in my post Why Enum Singleton are better in Java
Very nice post!
Some others from my side:
1. Can you extend a 1Singleton implementing class? :) Why ?
2. Can you have more then one isntance per JVM? Why?
Here's an in-depth explanation of the design pattern in all situations:
http://centraladvisor.com/programming-2/design-patterns/what-is-singleton-pattern/
I am very much agree with the guy @Anonymous on the Post dated: May 2, 2012 7:18 PM, as it is obvious people are just validating technical ego. And those questions should not be used for evaluating a candidature who is 10+years experiences, this is nothing just Non-sense. Even I can ask some question, those neither who are 99% in SCJP can't answers, nor the guy who are taking interview for 10+ years and ask this type of questions can answers??? These are just the ugly mindset of egoist people in industry and even if you answered all questions they will not select and will give feedback like they need more competent guy??? what hell of more competent ? are they clear on requirement, simply one questions to those buggers how many times they follow these concepts on there implementation ???It is disgusting. I am not saying should not be followed,or should not be used ? To know the concepts is one thing and after appearing 3/4 round of interview in a senior post and finally rejecting on base of these silly question means they are fearing you as they are not more competent with you,feeling in-secure against you.
great article! I have a query, how will you create a singleton class in a clustered environment?
Thanks Lokesh, I agree that Singleton pattern is not easy to implement, Enum is probably easier way to implement Singleton in Java.
I take the reference from this article "Singleton is a class which has only one instance in whole application....". I would like to believe that this would be correct. But unfortunately, it is incorrect. It is actually one instance per JVM. One instance per JVM is not the same as one instance per application. What happens if there are multiple applications deployed in same JVM which uses the same Singleton? In this case, if the singleton instance is with respect to a JVM, then we would see flaky results.
I believe the author was referring at the Singleton Design pattern from Gang of four. This pattern violates Single Responsibility Principle of Object Oriented Analysis & Design.
Frameworks such as Spring and Guice are aware of the above problem, and their versions of Singleton were different. They create only one instance per application.
Even if we don’t use frameworks, we could develop singletons with the notion that we would be creating only instance per application manually.
@Chandra: Singleton concept is per class loader......in fact! That is per application.
GUYS ... NEWS FLASH ... Double check locking is not 100% guranteed to work for singleton
1.Thread 1 enters the synchronized block and is preempted.
2.Subsequently, a Thread 2 enters the if block.
3.When Thread 1 exits the synchronized block,
4.Thread 2 makes a second check to see if the singleton instance is still null.
5.Since Thread 1 set the singleton member variable,
6.Thread 2's second check will fail, and a second singleton will not be created. Or so it seems.
double-checked locking is not guaranteed to work because the compiler is free to assign a value to the singleton member variable before the singleton's constructor is called. If that happens, Thread 1 can be preempted after the singleton reference has been assigned, but before the singleton is initialized, so Thread 2 can return a reference to an uninitialized singleton instance.
Since double-checked locking is not guaranteed to work, you must synchronize the entire getInstance() method.
Static class vs Singleton ?
@Anonymous, Yes It's a good question to ask about Singleton pattern. Recently blogged about it here Singleton vs Static Class, will update post to include this question as well. Thanks
Hi Javin,
I think you missed the "static" modifier for getInstance() in the code of 6) What is double checked locking in Singleton?
Hi,
"How do you prevent for creating another instance of Singleton using clone() method?"
>>As clone() method is protected, how can we call this method unless we override this method publicly in the singleton class or does your Singleton is extending from any other class where the clone() method is already overridden publicly?
Once again on my previous comment regarding cloning a singleton, we can override the clone method publicly and we can return the singleton instance.
New URL for Question 10 is,
http://www.oracle.com/technetwork/articles/java/singleton-1577166.html
@bonnahu, Good Catch. There should be static modifier, In order to access it as Singleton.getInstance(). Thanks
@Anonymous, You are correct, but clone() method doesn't make sense with Singleton. Throwing CloneNotSupportedException seems more logical then returning same instance.
In JP Morgan, I have asked to list down condition when Singleton fails? I mentioned Serialization, Reflection, multiple ClassLoader, multiple JVM, broken doubled checked locking etc. Does this answer that question?
Is single instance at JVM level or single instance per classloader?
Hi All,
I am not very clear about 8th point, Yes we can throw exception when we have instance but what if someone trying to create instance 1st time through reflection?
Thanks,
Lakhan
Shouldnt we use Enum with a single instance in order to prevent it from reflection or the serializable attack.
8. How do you prevent for creating another instance of Singleton using reflection?
In the ans you mentioned : This can be avoided by throwing Exception from constructor as “Singleton already initialized”
But this will lead to the exception even for the only object that should have been created of the singleton class via private constructor from the getInstance method itself. The end user will get the exception in case of he is trying to instantiate using reflection API but will alse get the same while using getInstance method too
what is a singleton and when would you use it / not use it? do you think it's a good question to ask an experienced programmer?
Do we mention that the quoted (non-enum) implementation is the classic naive-but-actually-broken implementation? http://en.wikipedia.org/wiki/Double-checked_locking
@Anonymous should I write you a HOWTO forum?
The singleton object is the only logic coherence to multiplexing by data!
@buddy Synchronization of singleton creation is needed in a multi-threaded environment.
@Mansi You can see how to use Enum for singletons in Effective Java: http://www.informit.com/articles/article.aspx?p=1216151&seqNum=3
@Anonymous You can just declare your Singleton instance variable as 'public static' instead of 'private static'.
How to handle singleton objects in CLUSTERED environment?
Still nobody answered "How to handle singleton objects in CLUSTERED environment?" I heard that we can use Coherence ( in Memory Caching) and all but no clear idea. Can you please explain ?
Hi All,
Is it possible to write System.println() method instead of System.out.println().
Hi,
I have recently asked a question that , we have a parent Class A and a child class B. How can we achieve the singleton in these two class.
Please help to find the answer of this question.
Thanks in Advance.
Hi, Can we extend the singleton class in java, if yes, then how to achieve to creation a only fixed number of objects of these class.
@Himanshu, you cannot extend a Singleton in Java. They are not designed for Inheritance. Singleton has private constructor which means they cannot be called from any class other than Singleton itself. Since sub class constructor automatically calls super class constructor in Java, its not possible unless the child class is nested inside Singleton itself.
Good questions. If you are looking for some more great Java interview questions from last couple of years, see this list of 13o+ Java interview questions wiht answers
Hi..
In one interview I have asked a question and I was not able to answer that. Question was in double check locking we are passing Singleton.class under synchronization. So what is the meaning of Singleton.class? What does this repesent?
Could you please answer that.
Thanks
You said: to prevent from creating another instance of Singleton using reflection,we can throw exception in constructor. Can you tell me throwing which exception will help here ?
By the way, very nice collection of questions.
Hello @Anonymous, you can throw any runtime exception but I suggest to reuse existing one and throw InstantiationException with custom message saying "Cannot create instance of Singleton class".
i think,this singleton will work in all situation.if any problem with this singleton please suggested to me.
public class MySingleton implements Serializable, Cloneable {
private static final long serialVersionUID = 5784724829335973182L;
private static volatile MySingleton instance;
private MySingleton() {
if (instance != null) {
throw new IllegalStateException("Only one instance may be created");
}
}
public static synchronized MySingleton getInstance() throws CloneNotSupportedException {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
public Object readResolve() {
try {
return getInstance();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
@Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Clone is not supported");
}
}
Please update the URL for Question "When is Singleton not a Singleton in Java".
http://www.oracle.com/technetwork/articles/java/singleton-1577166.html
Why clone? You cant clone singlton since there is no clone method ( I mean without clonable interface). Why explicitly wrote clonable ?
Post a Comment