【翻译】10 Interview questions on Singleton Pattern in Java

原文地址: http://www.dzone.com/links/r/top_10_interview_questions_on_singleton_pattern_i.html

Singleton pattern is one of the most common patterns available and it’s also used heavily in Java. This is also one of my favorite interview question and has lots of interesting follow-up to digg 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 short java interview tutorial I 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.

So question starts with what is Singleton? Have you used Singleton before?
Singleton is a class which has only one instance thought out the application and provides a getInstance() method to access the singleton instance.

[b]1) Which classes are candidates of Singleton? Which kind of class do you make Singleton in Java?[/b]
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.

[b]2) Can you write code for getInstance() method of a Singleton class in Java?[/b]
Most of the guys fail here if they have mugged up the singleton code because you can ask lots of follow-up question based upon the code written by candidate. In my experience I have seen mostly java interviewee right Singleton getInstance() method with double checking but they are not really familiar with the caveat associated with double checking of singleton prior to Java 5.

[b]3) Is it better to make whole getInstance() method synchronized or just critical section is enough? Which one you will prefer?[/b]
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.

[b]4) What is lazy and early loading of Singleton and how will you implement it?[/b]
This is again great 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.

[b]5) Example of Singleton in standard JAVA Development Kit?[/b]
This is open question to all, please share which classes are Singleton in JDK.

[b]6) What is double checked locking in Singleton?[/b]
One of the most hyped question on Singleton 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 instance of Singleton then it really shows it has in depth knowledge of Java memory model and he is constantly updating his Java knowledge.

[b]7) How do you prevent for creating another instance of Singleton using clone() method?[/b]
This type of questions generally comes some time by asking how to break singleton or when Singleton is not Singleton in Java.

[b]8) How do you prevent for creating another instance of Singleton using reflection?[/b]
Open to all. In my opinion throwing exception from constructor is an option.

[b]9) How do you prevent for creating another instance of Singleton during serialization?[/b]
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.

[b]10) When is Singleton not a Singleton in Java?[/b]
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/

If you like to read more Java interview questions you can have a look on some of my favorites below:

[url=http://www.bukisa.com/articles/458805_why-string-is-immutable-in-java-]How to identify and fix deadlock in java[/url]
[url=http://www.bukisa.com/articles/458805_why-string-is-immutable-in-java-]Difference between HashMap and HashTable? Can we make hashmap synchronized[/url]
[url=http://www.bukisa.com/articles/458805_why-string-is-immutable-in-java-]How to check if a thread holds lock on a particular object in Java [/url]

以下是评论:

11 comments:

Anonymous said...

Nice collection. It's better you provide the answers also.
March 4, 2011 8:00 AM
Anonymous said...

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.
March 7, 2011 11:00 AM
Eurekin said...

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?
March 7, 2011 11:04 AM
Anonymous said...

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
March 7, 2011 12:16 PM
Anonymous said...

11. Why you should avoid the singleton anti-pattern at all and replace it with DI?

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 (i.e. once).
March 7, 2011 1:57 PM
Gavin said...

I blogged about the Singleton as an interview question a while back - got some interesting comments: http://fishdujour.typepad.com/blog/2007/11/the-blissful-in.html
March 7, 2011 2:58 PM
Javin said...

@ 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.
March 7, 2011 9:12 PM
buddy said...

@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 .
March 7, 2011 9:14 PM
Jeune said...

Really great and informative post! I have heard of interviews where these questions were asked.
March 7, 2011 10:12 PM
Robert Kovačević said...

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
March 8, 2011 12:44 AM
Anonymous said...

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.
March 8, 2011 4:51 AM
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值