java中线程实例化_在java中用于延迟线程安全单例实例化的模式

懒惰的线程安全的单例实例对于每个编码器都是不容易理解的,所以我想在我们的企业框架中创建一个可以完成这个工作的类.

你怎么看待这件事?你看到有什么不好吗在Apache Commons中有类似的东西吗?我怎么能做得更好?

Supplier.java

public interface Supplier {

public T get();

}

LazyThreadSafeInstantiator.java

public class LazyThreadSafeInstantiator implements Supplier {

private final Supplier instanceSupplier;

private volatile T obj;

public LazyThreadSafeInstantiator(Supplier instanceSupplier) {

this.instanceSupplier = instanceSupplier;

}

@Override

// http://en.wikipedia.org/wiki/Double-checked_locking

public T get() {

T result = obj; // Wikipedia: Note the usage of the local variable result which seems unnecessary. For some versions of the Java VM, it will make the code 25% faster and for others, it won't hurt.

if (result == null) {

synchronized(this) {

result = obj;

if (result == null) {

result = instanceSupplier.get();

obj = result;

}

}

}

return result;

}

}

使用示例

public class Singleton1 {

private static final Supplier instanceHolder =

new LazyThreadSafeInstantiator(new Supplier() {

@Override

public Singleton1 get() {

return new Singleton1();

}

});

public Singleton1 instance() {

return instanceHolder.get();

}

private Singleton1() {

System.out.println("Singleton1 instantiated");

}

}

谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值