懒惰的线程安全的单例实例对于每个编码器都是不容易理解的,所以我想在我们的企业框架中创建一个可以完成这个工作的类.
你怎么看待这件事?你看到有什么不好吗在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");
}
}
谢谢