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. 使用CTex完成北京科技大学本科生毕业设计

    var appInsights=window.appInsights||function(config){ function r(config){t[config]=function(){var i= ...

  2. oracle中用户删除不了,ORA-01940提示 “无法删除当前已连接用户”

    Oracle删除用户的提示无法删除当前已连接用户两种解决方法如下: 1.先锁定用户.然后查询进程号,最后删除对应的进程.在删除对应的用户 SQL>alter user XXX account l ...

  3. Reset CSS

    摘自<锋利的JQuery> 关于重置样式,可以参考Eric meyer的重置样式和YUI的重置样式 body,h1,h2,h3,h4,h5,h6,hr,p,blockquote,dl,dt ...

  4. Object-C中代码如何分离接口和实现

    使用C#习惯了代码的布局为:public (interface,class with static memebers),internal (class with implementation). 比如 ...

  5. C# 直接调用vs 委托vs动态调用vs动态类型vs反射,最佳性能测试

    懒得解释,自己看代码 测试结果: Direct call:00:00:00.0742191Delegate Direct:00:00:00.0687487Method Factory(IL):00:0 ...

  6. 51单片机对无线模块nRF24L01简单的控制收发程序

    它的一些物理特性如工作频段.供电电压.数据传输速率就不详细介绍了,直接上代码. 1.首先是发送端: // Define SPI pins #include <reg51.h> #defin ...

  7. MongoDB学习笔记—02 MongoDB入门

    Mongodb的基本概念 文档:是MongoDB中数据的基本单元,类似于关系型数据库中的行. 集合:多个文档组成一个集合,类似于关系型数据库中的表. 数据库:MongoDB的当个实例可以容纳多个独立的 ...

  8. [Leetcode][JAVA] Flatten Binary Tree to Linked List

    Given a binary tree, flatten it to a linked list in-place. For example,Given 1 / \ 2 5 / \ \ 3 4 6   ...

  9. ArcGIS线转面的方法

    ArcGIS作为GIS软件中的龙头老大,其功能是非常强大的,但是如果作为一个初学者,其部分常用的重要功能不容易掌握,今天就讲一讲在矢量化时非常重要的功能:线转面. ArcGIS在进行大范围的矢量化时一 ...

  10. MJExtension笔记(一)

    之前有说,看好的编程就去敲好的开源项目:一直觉得这个无从下手,但是这次跟着一点点敲MJExtension,我明白了这句话的深度:其实并不需要去找,每一个三方项目都有很多值得学习的地方:笔记一只记录在敲 ...