java多线程单例模式
2012-03-21 22:30
295 查看
java多线程单例模式:
另一个改进:
一些讨论:
Probably the first design pattern that every software developer learns is Singleton and lazy loading of Singleton classes.
The usual example, goes something like this:
The problem with this solution is that synchronized method
Today, thanks to Bob Lee, I found out that there is a solution to this problem that is both simple and fast: Initialization on Demand Holder (IODH) idiom. The appropriate example follows:
Basicaly, Java Language Specification (JLS) guarantees that
public static Singleton getInstance(){ if (instance == null) synchronized(instance){ if(instance == null) instance = new Singleton(); } return instance; }
另一个改进:
public class Singleton{ private Singleton(){ … } private static class SingletonContainer{ private static Singleton instance = new Singleton(); } public static Singleton getInstance(){ return SingletonContainer.instance; } }
一些讨论:
Probably the first design pattern that every software developer learns is Singleton and lazy loading of Singleton classes.
The usual example, goes something like this:
public class Singleton { static Singleton instance; public static synchronized Singleton getInstance() { if (instance == null) instance = new Singleton(); return instance; } }
The problem with this solution is that synchronized method
getInstance()is called every time, while synchronization is actually needed only for the first call of the method (which introduces performance overhead in your application). There were attempts to tackle this problem by using Double-checked locking pattern, which although great in theory didn’t work in practice.
Today, thanks to Bob Lee, I found out that there is a solution to this problem that is both simple and fast: Initialization on Demand Holder (IODH) idiom. The appropriate example follows:
public class Singleton { static class SingletonHolder { static Singleton instance = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.instance; } }
Basicaly, Java Language Specification (JLS) guarantees that
instancewould not be initialized until someone calls
getInstance()method (more information could be found in articles that I’ve linked to before). Elegant and fast, just as it should be.
相关文章推荐
- Java多线程模式之流水线模式
- Java Note: 多线程的同步(互斥锁)的方法对比,信号量锁,读写锁的实现,生产者-消费者模式的实现
- Java多线程编程简明教程(2) - ForkJoin模式
- JAVA 单例模式与多线程
- Java基础之多线程(一)--概述、同步、死锁、单例模式
- Java中的模式 --单态-多线程下的处理方式(部分翻译 double-checked locking break)
- java多线程之消费者生产者模式(一)
- java多线程Thread-per-Message模式详解
- java——多线程——单例模式的static方法和非static方法是否是线程安全的?
- JAVA多线程的设计模式
- (10)Java多线程之再看生产者/消费者模式
- Java多线程之线程间通信--生产者/消费者模式
- java多线程中的设计模式
- java中结合单例模式,控制单例类的某方法在被多线程调用时,只被1个线程调用执行,执行完毕后才被另一线程调用
- 3-2-Java多线程-案例-单例设计模式出现的问题
- Java多线程编程模式实战指南之Promise模式
- Java多线程编程模式实战指南(三):Two-phase Termination模式
- JAVA学习第二十五课(多线程(四))- 单例设计模式涉及的多线程问题
- Java知识(多线程模式和线程安全)
- Java Note: 多线程的同步(互斥锁)的方法对比,信号量锁,读写锁的实现,生产者-消费者模式的实现