singleton implementation
来源:互联网 发布:淘宝买家信用等级v6 编辑:程序博客网 时间:2024/05/21 04:21
原文地址:http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-with-examples
Thread Safe Singleton:
The easier way to create a thread-safe singleton class is to make the global access methodsynchronized,
so that only one thread can execute this method at a time. General implementation of this approach is like the below class
package
com.journaldev.singleton;
public
class
ThreadSafeSingleton {
private
static
ThreadSafeSingleton instance;
private
ThreadSafeSingleton(){}
public
static
synchronized
ThreadSafeSingleton getInstance(){
if
(instance ==
null
){
instance =
new
ThreadSafeSingleton()
return
instance;
}
}
Above implementation works fine and provides thread-safety but it reduces the performance
because
of cost associated with the synchronized method, although we need it only for the first few
threads who might create the separate instances (Read:Java Synchronization). To avoid this extra
overhead everytime, double
checked locking principle is used. In this approach, the synchronized block
is used inside the if condition
with an additional check to ensure that only one instance of singleton
class is created.
Below code snippet provides the double checked locking implementation.
public
static
ThreadSafeSingleton getInstanceUsingDoubleLocking(){
if
(instance ==
null
){
synchronized
(ThreadSafeSingleton.
class
) {
if
(instance ==
null
){
instance =
new
ThreadSafeSingleton();
}
}
}
return
instance;
}
Bill Pugh Singleton Implementation:
Prior to Java 5, java memory model had a lot of issues and above approaches used to fail in
certain scenarios where too many threads try to get the instance of the Singleton class simultaneously.
So Bill Pugh came up with a different approach to create the Singleton class using a
inner static helper class. The Bill Pugh Singleton implementation goes like this;
package
com.journaldev.singleton;
public
class
BillPughSingleton {
private
BillPughSingleton(){}
private
static
class
SingletonHelper{
private
static
final
BillPughSingleton INSTANCE =
new
BillPughSingleton();
}
public
static
BillPughSingleton getInstance(){
return
SingletonHelper.INSTANCE;
}
}
Notice the private inner static class that contains the instance of the singleton class.
When the singleton class is loaded, SingletonHelper
class is not loaded into memory and only when
someone calls the getInstance method, this class gets loaded and creates the Singleton class instance.
This is the most widely used approach for Singleton class as it doesn’t require synchronization.
I am using this approach in many of my projects and it’s easy to understand and implement also.
Using Reflection to destroy Singleton Pattern
Reflection can be used to destroy all the above singleton implementation approaches.
Let’s see this with an example class.
public
class
EagerInitializedSingleton {
private
static
final
EagerInitializedSingleton instance =
new
EagerInitializedSingleton();
//private constructor to avoid client applications to use constructor
private
EagerInitializedSingleton(){}
public
static
EagerInitializedSingleton getInstance(){
return
instance;
}
}
public
class
ReflectionSingletonTest {
public
static
void
main(String[] args) {
EagerInitializedSingleton instanceOne = EagerInitializedSingleton.getInstance();
EagerInitializedSingleton instanceTwo =
null
;
try
{
Constructor[] constructors = EagerInitializedSingleton.
class
.getDeclaredConstructors();
for
(Constructor constructor : constructors) {
//Below code will destroy the singleton pattern
constructor.setAccessible(
true
);
instanceTwo = (EagerInitializedSingleton) constructor.newInstance();
break
;
}
}
catch
(Exception e) {
e.printStackTrace();
}
System.out.println(instanceOne.hashCode());
System.out.println(instanceTwo.hashCode());
}
}
If your singleton class is not using a lot of resources, this is the approach to use.
But in most of the scenarios, Singleton classes are created for resources such as File System,
Database connections etc and we should avoid the instantiation until unless client calls the
getInstance
method. Also this method doesn’t provide any options for exception handling
0 0
- singleton implementation
- Singleton : Implementation in Unity3d C#
- Implementation
- implementation
- Singleton
- Singleton
- singleton
- Singleton
- Singleton
- Singleton
- Singleton
- Singleton
- Singleton
- Singleton
- Singleton
- Singleton
- singleton
- Singleton
- c++开发过程中遇到的线程问题
- phpmyadmin出现“Cannot start session without errors, please check errors given in your PHP and/or webs”
- [Leetcode]Container With Most Water
- 谷歌浏览器javascript调试教程
- 内核阻塞函数中的ERESTARTSYS的定义
- singleton implementation
- Linux下关于TCP的keep alive的实现源码分析
- Java String.split()用法小结
- .NET中原始的ControlPaint类
- Rank() over()的用法
- 使用Netback备份Oracle报ora-27206错误处理
- android PathData生成问题
- 成为高级程序员的10个步骤
- N-Queens II