我很困惑应该使用哪一个来创建同步单例类对象。我知道以下两种实现它的方法。
static volatile PaymentSettings paymentSettings = null;
public static PaymentSettings getInstance() {
if (paymentSettings == null) {
synchronized (PaymentSettings.class) {
if (paymentSettings == null)
paymentSettings = new PaymentSettings();
}
}
return paymentSettings;
}
还有
private static class PaymentSettingsInstanceHolder {
private static PaymentSettings instance = new PaymentSettings();
}
public static PaymentSettings getInstance() {
return PaymentSettingsInstanceHolder.instance;
}
请建议我应该使用哪种方法以及为什么?
最佳答案
这两种机制是实现 Singleton 的常见尝试。 .
第一个名为 Double-checked locking尽管您对类进行锁定的技术可能是一种可接受的解决方法,但通常认为它已损坏。
您的第二个解决方案是一个整洁的解决方案,但可能会在不需要时创建对象。
当今被认为最好的解决方案是使用enum
。这确保该对象仅在需要时而不是之前创建。请参阅here关于为什么这很好的精彩论述。
final class Singleton {
private Singleton() {
// Make sure only I can create one.
}
private enum Single {
INSTANCE;
// The only instance - ever.
final Singleton s = new Singleton();
}
public static Singleton getInstance() {
// Will force the construction here only.
return Single.INSTANCE.s;
}
}
关于java - 如何使Java对象同步?哪种方法更好,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33075585/