【发布时间】:2016-02-23 20:36:29
【问题描述】:
在 java 中,我们可以使用双重检查锁定和 volatile 编写安全的单例:
public class Singleton {
private static volatile Singleton instance;
public static Singleton getInstance(String arg) {
Singleton localInstance = instance;
if (localInstance == null) {
synchronized (Singleton.class) {
localInstance = instance;
if (localInstance == null) {
instance = localInstance = new Singleton(arg);
}
}
}
return localInstance;
}
}
我们如何在 kotlin 中编写它?
关于对象
object A {
object B {}
object C {}
init {
C.hashCode()
}
}
我使用 kotlin 反编译器来得到它
public final class A {
public static final A INSTANCE;
private A() {
INSTANCE = (A)this;
A.C.INSTANCE.hashCode();
}
static {
new A();
}
public static final class B {
public static final A.B INSTANCE;
private B() {
INSTANCE = (A.B)this;
}
static {
new A.B();
}
}
public static final class C {
public static final A.C INSTANCE;
private C() {
INSTANCE = (A.C)this;
}
static {
new A.C();
}
}
}
所有对象在static 块中都有构造函数调用。基于它,我们可以认为它并不偷懒。
С失去正确答案。
class Singleton {
companion object {
val instance: Singleton by lazy(LazyThreadSafetyMode.PUBLICATION) { Singleton() }
}
}
反编译:
public static final class Companion {
// $FF: synthetic field
private static final KProperty[] $$delegatedProperties = new KProperty[]{(KProperty)Reflection.property1(new PropertyReference1Impl(Reflection.getOrCreateKotlinClass(Singleton.Companion.class), "instance", "getInstance()Lru/example/project/tech/Singleton;"))};
@NotNull
public final Singleton getInstance() {
Lazy var1 = Singleton.instance$delegate;
KProperty var3 = $$delegatedProperties[0];
return (Singleton)var1.getValue();
}
private Companion() {
}
// $FF: synthetic method
public Companion(DefaultConstructorMarker $constructor_marker) {
this();
}
}
我希望 Kotlin 开发者在未来做出非反射实现...
【问题讨论】:
-
Java 中的首选方式应该是:stackoverflow.com/a/17800038/3679676,而不是使用 volatile 进行双重检查锁定。另请参阅:en.wikipedia.org/wiki/…
-
双重锁检查的复杂性和更新版本:en.wikipedia.org/wiki/Double-checked_locking
-
这不是 Java 中单例的正确方法!
-
@Zordid 你能解释一下吗?
-
只要谷歌你的双重检查锁定,你会发现它被打破了。例如。这里cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
标签: multithreading singleton kotlin