Is a synchronized static method legal in Java?
2 answers
Yes, and it simplifies static factory methods like this:
class Foo {
private Foo() {}
public static synchronized Foo getInstance() {
if (instance == null) {
instance = new Foo();
}
return instance;
}
private static Foo instance = null;
}
This is what it would look like if the methods static
couldn't be 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();
}
Not that big a deal, it just saves 2 lines of code.
0
source to share