我想在Java中实现多线程的延迟初始化.
我有一些类似的代码:
class Foo {
private Helper helper = null;
public Helper getHelper() {
if (helper == null) {
Helper h;
synchronized(this) {
h = helper;
if (h == null)
synchronized (this) {
h = new Helper();
} // release inner synchronization lock
helper = h;
}
}
return helper;
}
// other functions and members...
}
Run Code Online (Sandbox Code Playgroud)
而且我得到了"Double-Checked Locking is Broken"声明.
我怎么解决这个问题?
懒惰的线程安全单例实例对每个编码器来说都不容易理解,所以我想在我们的企业框架中创建一个可以完成这项工作的类.
你怎么看待这件事?你觉得它有什么坏处吗?在Apache Commons中有类似的东西吗?我怎样才能让它变得更好?
Supplier.java
public interface Supplier<T> {
public T get();
}
Run Code Online (Sandbox Code Playgroud)
LazyThreadSafeInstantiator.java
public class LazyThreadSafeInstantiator<T> implements Supplier<T> {
private final Supplier<T> instanceSupplier;
private volatile T obj;
public LazyThreadSafeInstantiator(Supplier<T> 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 …Run Code Online (Sandbox Code Playgroud)