From J2EE Bloger http://j2eeblogger.blogspot.com/2007/10/singleton-vs-multiton-synchronization.html

1. Classic Java singleton synchronization problem

public class Singleton {
private static Singleton instance; /** Prevents instantiating by other classes. */
private Singleton(){} public static synchronized Singleton getInstance() {
if (instance == null){
instance = new Singleton();
} return instance;
}
}

The synchronized keyword on the getInstance() method is the evil. In a multi-thread environment, every thread will be blocked by each other when trying to grab the singleton instance. This is the classic java singleton synchronization problem.

2. The traditional solution using a static variable.

public class Singleton {
/** Prevents instantiating by other classes. */
private Singleton() {} private final static Singleton instance = new Singleton(); public static Singleton getInstance() {
return instance;
}
}

The singleton instance is initialized during the class loading time. No synchronization is necessary on the getInstance level.

3. The classic synchronized multiton.

public class Multiton {
private static final HashMap<Object, Multiton> instances = new HashMap<Object, Multiton>(); private Multiton(){} public static Multiton getInstance(Object key){
synchronized (instances) {
// Our "per key" singleton
Multiton instance;
if ((instance = instances.get(key)) == null) {
// Lazily create instance and add it to the map
instance = new Multiton();
instances.put(key, instance);
} return instance;
}
}
}

The Multiton pattern begins with the concept of the Singleton pattern and expands it into an object pool of keys to objects. Instead of having a single instance per runtime, the Multiton pattern ensures a single instance per key. It simplifies retrieval of shared objects in an application.

As we noticed from the above scriptlet, the access to the getInstance() method is synchronized to ensure the uniqueness of instance per key. This, again, is a performance bottleneck in multi-thread environment. The traditional 'static' solution for Singleton pattern can't be used here since the keys are passed into the Multiton on-the-fly. We have no way to predict how many keys will be passed into the Multiton during the runtime.
 
 
4. The double-check locing solution
public class Multiton {
private static final HashMap<Object, Multiton> instances = new HashMap<Object, Multiton>(); public static Multiton getInstance(Object key) {
// Our "per key" singleton
Multiton instance; if ((instance = instances.get(key)) == null) {
synchronized(instances) {
if ((instance = instances.get(key)) == null) {
instance = new Multiton();
instances.put(key, instance);
}
}
} return instance;
}
}

Yes the double-checked locking does not work for Singleton (http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html), but it does work for our Multiton pattern. Reason? We have our intermediate HashMap object sits in between. Actually we can use the HashMap to solve the Singleton double-checked locking problem as well, if we don't already have the more elegant solution using a static variable.

5. An alternative solution: Using the Java 5 ConcurrentMap

public class Multiton {
private static final ConcurrentMap<Object, Multiton> instances = new ConcurrentHashMap<Object, Multiton>(); public static Multiton getInstance(Object key) {
// Our "per key" singleton
if (instances.get(key) == null) {
// Lazily create instance and try to add it to the map
Multiton instance = new Multiton();
instances.putIfAbsent(key, instance);
} return instances.get(key);
}
}

The Java 5 ConcurrentMap.putIfAbsent(), being an atomic operation, returns the previous value associated with the key instead of the new suggested value. This ensures the uniqueness of the Multiton instance inside the ConcurrentMap.

In this solution, before a key object has been associated with a Multiton object, if two or more threads are trying to retrieve the instance with the same key object, it's possible that multiple Multiton instance will be created inside the if() block. However, the ConcurrentMap ensures that a same Multiton instance is  to be returned to the caller. Extra instances are eligible for Garbage Collection as soon as the method returns. You may not want to use this solution if the creation of the Multiton instance is an expensive operation, as in certain situation.
 
 

Multiton & Singleton的更多相关文章

  1. 23种设计模式--单例模式-Singleton

    一.单例模式的介绍 单例模式简单说就是掌握系统的至高点,在程序中只实例化一次,这样就是单例模式,在系统比如说你是该系统的登录的第多少人,还有数据库的连接池等地方会使用,单例模式是最简单,最常用的模式之 ...

  2. 设计模式之单例模式(Singleton)

    设计模式之单例模式(Singleton) 设计模式是前辈的一些经验总结之后的精髓,学习设计模式可以针对不同的问题给出更加优雅的解答 单例模式可分为俩种:懒汉模式和饿汉模式.俩种模式分别有不同的优势和缺 ...

  3. PHP设计模式(四)单例模式(Singleton For PHP)

    今天讲单例设计模式,这种设计模式和工厂模式一样,用的非常非常多,同时单例模式比较容易的一种设计模式. 一.什么是单例设计模式 单例模式,也叫单子模式,是一种常用的软件设计模式.在应用这个模式时,单例对 ...

  4. The Java Enum: A Singleton Pattern [reproduced]

    The singleton pattern restricts the instantiation of a class to one object. In Java, to enforce this ...

  5. 最适合作为Java基础面试题之Singleton模式

    看似只是最简单的一种设计模式,可细细挖掘,static.synchronized.volatile关键字.内部类.对象克隆.序列化.枚举类型.反射和类加载机制等基础却又不易理解透彻的Java知识纷纷呼 ...

  6. 每天一个设计模式-4 单例模式(Singleton)

    每天一个设计模式-4 单例模式(Singleton) 1.实际生活的例子 有一天,你的自行车的某个螺丝钉松了,修车铺离你家比较远,而附近的五金店有卖扳手:因此,你决定去五金店买一个扳手,自己把螺丝钉固 ...

  7. Qt 中使用Singleton模式需小心

    在qt中,使用Singleton模式时一定要小心.因为Singleton模式中使用的是静态对象,静态对象是直到程序结束才被释放的,然而,一旦把该静态对象纳入了Qt的父子对象体系,就会导致不明确的行为. ...

  8. 设计模式之单例模式——Singleton

                        设计模式之单例模式--Singleton 设计意图: 保证类仅有一个实例,并且可以供应用程序全局使用.为了保证这一点,就需要这个类自己创建自己的对象,并且对外有 ...

  9. C#面向对象设计模式纵横谈——2.Singleton 单件(创建型模式)

    一:模式分类 从目的来看: 创建型(Creational)模式:负责对象创建. 结构型(Structural)模式:处理类与对象间的组合. 行为型(Behavioral)模式:类与对象交互中的职责分配 ...

随机推荐

  1. git 笔记

    查看某个提交的修改:git show commitID 查看某个提交修改涉及的文件:git show commitID --oneline --name-status 清理掉没有入库的文件,并把修改了 ...

  2. SQL Server 全文索引创建

    在安装数据库管理系统SQL Server 后,默认情况下全文索引的服务是没有开启的 ,所以首先需要先开启服务,在sql server配置管理器中 (sql server configuration M ...

  3. 算法入门笔记------------Day1

    1.C语言使用%d显示float值,不会把float值转换为近似的int值,而是显示垃圾值,使用%f显示int值,也不会把该int值转换为浮点值 2.三位数反转:输入一个三位数,分离它的百位,十位和个 ...

  4. response.sendRedirect的细节

    今天敲书上的例子的时候无意间发现,response中的sendRedirect()重定向到另一个servlet时,调用的是doget方法,不明所以,百度得知,原来还牵扯到http协议的细节问题,原文如 ...

  5. WebBench源码分析与心得

    源码:https://github.com/EZLippi/WebBench   关键全局变量: speed 成功次数 failed 失败次数 bytes 接收字节数 benchtime 执行时长(秒 ...

  6. Software Testing hw2

    Fault的定义:可能导致系统或功能失效的异常条件(Abnormal condition that can cause an element or an item tofail.),可译为“故障”. ...

  7. web

    1.linux下交换文件 .index.php.swp 有时可查看源码2.当php后缀被过滤的时候可以直接对ph开头的后缀进行一个fuzz测试可以上传的文件后缀名3.curl -x 123.45.67 ...

  8. 一个demo让你彻底理解Android触摸事件的并发

    注:本文涉及的demo的地址:https://github.com/absfree/TouchDispatch 1. 触摸动作及事件序列 (1)触摸事件的动作 触摸动作一共有三种:ACTION_DOW ...

  9. (原创) 巩固理解I2C协议(MCU,经验)

        题外话:这几天天气突然转冷了.今天已是11月23日了,查查黄历,昨天(11月22日)刚好是小雪,一夜温度骤降,果然老祖先的经验有灵验!冬天来了,还是多加加衣服,注意保暖! 1.Abstract ...

  10. 拾遗——java多线程

    由于sleep()方法是Thread类的方法,因此它不能改变对象的机锁.所以当在一个Synchronized方法中调用sleep()时,线程虽然休眠了,但是对象的机锁没有被释放,其他线程仍然无法访问这 ...