`
nanjingjiangbiao_T
  • 浏览: 2596779 次
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

单例模式的常见面试题

 
阅读更多

1) 哪些类是单例模式的后续类?在Java中哪些类会成为单例?

这里它们将检查面试者是否有对使用单例模式有足够的使用经验。他是否熟悉单例模式的优点和缺点。

2)你能在Java中编写单例里的getInstance()的代码?

很多面试者都在这里失败。然而如果不能编写出这个代码,那么后续的很多问题都不能被提及。

3)在getInstance()方法上同步有优势还是仅同步必要的块更优优势?你更喜欢哪个方式?

这确实是一个非常好的问题,我几乎每次都会提该问题,用于检查面试者是否会考虑由于锁定带来的性能开销。因为锁定仅仅在创建实例时才有意义,然后其他时候实例仅仅是只读访问的,因此只同步必要的块的性能更优,并且是更好的选择。

4)什么是单例模式的延迟加载或早期加载?你如何实现它?

这是和Java中类加载的载入和性能开销的理解的又一个非常好的问题。我面试过的大部分面试者对此并不熟悉,但是最好理解这个概念。

5) Java平台中的单例模式的实例有哪些?

这是个完全开放的问题,如果你了解JDK中的单例类,请共享给我。

6) 单例模式的两次检查锁是什么?

7)你如何阻止使用clone()方法创建单例实例的另一个实例?

该类型问题有时候会通过如何破坏单例或什么时候Java中的单例模式不是单例来被问及。

8)如果阻止通过使用反射来创建单例类的另一个实例?

开放的问题。在我的理解中,从构造方法中抛出异常可能是一个选项。

9)如果阻止通过使用序列化来创建单例类的另一个实例?

又一个非常好的问题,这需要Java中的序列化知识并需要理解如何使用它来序列化单例类。该问题是开放问题。

10) Java中的单例模式什么时候是非单例?

下面是英文:

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

分享到:
评论

相关推荐

    Python经典面试题 Python常见面试考试题目整理总结 Python面试题手册 共15页.pdf

    Python经典面试题 Python常见面试考试题目整理总结 Python面试题手册 1:Python 如何实现单例模式? 2:什么是 lambda 函数? 3:Python 是如何进行类型转换的? 4:Python 如何定义一个函数 5:Python 是如何进行...

    Java初级开发面试题

    Java面试题包括但不限于: Java基础知识:语法、面向对象编程、集合、多线程、异常处理等。 Java高级特性:反射、泛型、枚举、注解、 Lambda表达式等。 Java虚拟机:Java内存模型、垃圾回收、类加载机制等。 ...

    mysql面试题-mysql经典面试题目-数据库的基本概念-SQL语法-事务处理-索引优化-性能调优-mysql-面试题目

    30道经典java面试题 当面试Java开发职位时,以下是另外一些经典的Java面试题供参考: 什么是Java中的面向对象编程(OOP)?列举OOP的原则。 什么是Java中的重载和重写?它们之间有什么区别? 什么是Java中的...

    Java 基础面试题

    该文档主要整理了常见的Java基础面试题,包含以下内容: 1. 抽象类和接口的区别 2. 什么时候使用抽象类,什么时候使用接口 3. 八大基本数据类型,所占字节数 4. List、Set、Map的区别 5. 什么情况下使用List、...

    Java基础语法面试题.docx

    Java基础语法面试题资源通常是指帮助准备...设计模式:介绍常见的设计模式,如单例模式、工厂模式、观察者模式等。 常见算法和数据结构:可能包含一些常见的算法问题,如查找、排序、递归等,以及与之相关的数据结构。

    北京百度java面试题大全

    Java面试题是针对Java编程语言的技术和知识的一系列问题,用于考察面试者在Java开发方面的能力和...设计模式:涉及常见的设计模式,如单例模式、工厂模式、观察者模式等。 Java框架和技术:包括Spring、Hibernate、My

    java面试题库2021.pdf

    目录 一、 JavaSE 部分 1、 Java 基础 ①Java 基础部分(基本语法, Java 特性等) ②关键字 ③面向对象 ...①单例模式 3、 行为型模式 ①策略模式 ②观察者模式 4、 所有模式汇总 十、 场景题 十一、 UML

    2023Java高频面试题

    Java面试题主要涉及Java语言本身、常用的Java框架和技术、面向对象编程、多线程编程、...设计模式:单例模式、工厂模式、代理模式等常见的设计模式。 算法和数据结构:二叉树、排序算法、查找算法等基础知识。 在面试

    【Java学习+面试指南】 一份涵盖大部分Java程序员所需要掌握的核心知识.rar

    JavaGuide 【Java学习+面试指南】 一份涵盖大部分Java程序员所需要掌握的核心知识。...常见面试题总结 面经 工具 Git Docker 资源 书单 Github榜单 Java基础 Java 基础知识回顾 Java 基础知识疑难点/

    Java面试可能问的问题.docx

    单例模式 策略模式 观察者模式 装饰模式 3.Spring的优越性 https://blog.csdn.net/hht006158/article/details/80181207 4.SpringMVC注解 @Controller @RestController @RequestMapping @RequestBody @ResponseBody...

    java面试题

    如何控制两种框架中的单例模式? 74 73. Spring 75 73.1. Spring 简介 75 73.2. 为什么要用Spring? 76 73.3. spring工作机制或工作原理 76 73.4. Spring是什么?根据你的理解详细谈谈你的见解。 76 73.5. 项目中如何...

    JAVA面试题收录

    文章目录一、JavaSE基础二、JavaWeb部分三、...单例设计模式 常见的异常类型 Throws和Throw的区别 Final,Finally,finalize关键字的作用 Hashtable与HashMap的区别 线程和进程的区别 实现多线程程序的2种方式 List、

    java 面试题 总结

    异常表示程序运行过程中可能出现的非正常状态,运行时异常表示虚拟机的通常操作中可能遇到的异常,是一种常见运行错误。java编译器要求方法必须声明抛出可能发生的非运行时异常,但是并不要求必须声明抛出未被捕获的...

    2023年最新java面试大全

    【15期】谈谈这几个常见的多线程面试题 【16期】你能谈谈HashMap怎样解决hash冲突吗 【17期】什么情况用ArrayList or LinkedList呢? 【18期】Java序列化与反序列化三连问:是什么?为什么要?如何做?

    超级有影响力霸气的Java面试题大全文档

    超级有影响力的Java面试题大全文档 1.抽象: 抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面。抽象并不打算了解全部问题,而只是选择其中的一部分,暂时不用部分细节。...

    JAVA开发五年程序员简历模版

    Java面试专题课解决面试过程中的一些常见问题,课程全面覆盖重难点Java面试题。包含了多个模块的面试题讲解,如:Redis、MySQL、框架、微服务、消息中间件、数据结构、Java集合源码分析、多线程、JVM、设计模式、高...

    面试常见题型

    包括JSP九大内置对象、servlet、常用类及包接口、设计模式(单例)、冒泡排序、线程、Ajax、还有常见的一些要说区别的题 好不容易才整合的,希望对大家有所帮助。

    java面试题,180多页,绝对良心制作,欢迎点评,涵盖各种知识点,排版优美,阅读舒心

    180多页面试题,前前后后不间断的更新了两年,准备换工作时,总是拿来看看,有比较好的面试题,也不间断的更新,面试题目录如下: 【基础】面向对象的特征有哪些方面 13 抽象 13 继承 13 封装 13 多态性 13 【基础】...

Global site tag (gtag.js) - Google Analytics