Java中的同步静态方法是否合法?
答案 0 :(得分:14)
是。它获取对象的锁定,该对象表示定义方法的类(例如,MyClass.class)
答案 1 :(得分:0)
是的,它简化了这样的静态工厂方法:
class Foo {
private Foo() {}
public static synchronized Foo getInstance() {
if (instance == null) {
instance = new Foo();
}
return instance;
}
private static Foo instance = null;
}
如果static
方法无法synchronized
,可能会出现以下情况:
class Foo {
private Foo() {}
public static Foo getInstance() {
synchronized (LOCK) {
if (instance == null) {
instance = new Foo();
}
}
return instance;
}
private static Foo instance = null;
private static final Object LOCK = Foo.class;
// alternative: private static final Object LOCK = new Object();
}
没什么大不了的,它只保存了2行代码。