原文地址: 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.
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.
2) Can you write code for getInstance() method of a Singleton class in Java?
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.
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.
4) What is lazy and early loading of Singleton and how will you implement it?
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.
5) Example of Singleton in standard JAVA Development Kit?
This is open question to all, please share which classes are Singleton in JDK.
6) What is double checked locking in Singleton?
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.
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.
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.
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.
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 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:
How to identify and fix deadlock in java
Difference between HashMap and HashTable? Can we make hashmap synchronized
How to check if a thread holds lock on a particular object in Java
以下是评论:
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
分享到:
相关推荐
singleton pattern 的定义 主要应用方法 优缺点 通过代码 具体分析解释
### Singleton Pattern 单例模式应用详解 #### 一、单例模式概述 单例模式(Singleton Pattern)是一种常用的软件设计模式,在系统中确保某个类只有一个实例,并提供一个全局访问点。这种模式通常用于控制资源的...
1. **单例模式(Singleton Pattern)**: - 定义:确保一个类只有一个实例,并提供一个全局访问点。 - 应用场景:适用于配置管理、线程池等需要全局唯一对象的场合。 2. **工厂模式(Factory Pattern)**: - ...
在Java中,Singleton模式的实现有多种方式,每种方式都有其优缺点,我们将详细探讨这些实现方法并进行对比。 ### 1. 饿汉式(Static Final Field) 这是最简单的Singleton实现方式,通过静态初始化器在类加载时就...
单例模式(Singleton Pattern)是软件设计模式中的一种,它保证一个类只有一个实例,并提供一个全局访问点。这种模式在很多场景下非常有用,比如控制资源的唯一性、全局配置对象或者缓存服务等。本篇文章将深入探讨...
《Design Pattern In Java》这本书是关于Java设计模式的指南,由James W. Cooper撰写。设计模式是软件开发中的一种最佳实践,它总结了在特定情境下解决常见问题的经验和方法,为面向对象编程提供了可复用的设计解决...
### 单例模式 Singleton Pattern #### 概述 单例模式是一种常见的设计模式,属于创建型模式之一。这种模式的核心在于确保某个类只有一个实例存在,并且提供一个全局访问点来获取该实例。单例模式在Java开发中尤其...
Java据说有23种设计模式,Android的设计模式肯定是由Java来引申出来的。这里不讨论有多少人全会,有多少种设计模式会使用到,我们来讲下其中用得最多的也就是人人都知道的...这里是一个简单的SingletonPatternDemo。
**单例模式(Singleton Pattern)**是软件设计模式中的一种基础模式,它的核心思想是确保一个类只有一个实例,并提供一个全局访问点。这种模式在很多场景下非常有用,比如配置管理、线程池、数据库连接池等,这些都...
这里我们将深入探讨三种常见的Java设计模式:单例(Singleton)、工厂方法(Factory Method)和抽象工厂(Abstract Factory)。 **单例模式(Singleton)** 单例模式确保一个类只有一个实例,并提供一个全局访问点...
Singleton Pattern单例模式详解 Singleton Pattern单例模式是一种创建型设计模式,提供了一种创建对象的最佳方式。该模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建在应用程序运行...
在Go语言中,实现单例模式(Singleton Pattern)通常涉及确保一个类只有一个实例,并提供一个全局访问点来获取该实例。由于Go语言没有传统的类和对象概念,但具有结构体(struct)和函数,我们可以通过使用包级变量...
Singleton模式包含的角色只有一个,就是Singleton。Singleton拥有一个私有构造函数,确保用户无法通过new直接实例化它。除此之外,该模式中包含一个静态私有成员变量instance与静态公有方法Instance()。Instance()...
简单的单例模式举例Singleton 分为恶汉式 懒汉式
private static final Singleton INSTANCE = new Singleton(); private Singleton() {} public static Singleton getInstance() { return INSTANCE; } } ``` 2. 懒汉式(Lazy Initialization):在第一次需要时...
在Laravel框架中,设计模式的应用是提升代码质量和可维护性的重要手段之一,而Singleton(单例模式)是其中一种常见的模式。Singleton确保一个类只有一个实例,并提供一个全局访问点,这样可以避免创建多个对象导致...
单件模式(Singleton pattern)是设计模式中的一种结构型模式,它的主要目的是确保一个类只有一个实例,并提供一个全局访问点。这种模式常用于系统中需要频繁创建和销毁的对象,如日志服务、线程池或者数据库连接等...
工厂三兄弟之抽象工厂模式(二) 工厂三兄弟之抽象工厂模式(三) 工厂三兄弟之抽象工厂模式(四) 工厂三兄弟之抽象工厂模式(五) 单例模式-Singleton Pattern 确保对象的唯一性——单例模式 (一) 确保对象的...
单例模式(Singleton Pattern)是一种创建型设计模式,确保一个类只有一个实例,并提供一个全局访问点。这种模式常用于需要全局共享资源的场景,比如配置管理、日志记录等。 单例模式的组成 私有构造函数:防止外部...
### Java的Singleton模式详解 #### 一、Singleton模式概述 Singleton模式是一种常用的设计模式,在Java中主要用于确保一个类只有一个实例,并提供一个全局访问点。这种模式对于管理共享资源(如数据库连接池、...