Thank you folks.
+13
A:
Yes. It gets the lock on the object representing the class the method is defined in (eg MyClass.class)
idrosid
2009-09-11 17:08:34
A:
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;
}
Here's what it might look like if static
methods could not 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.
finnw
2009-09-12 00:01:31
Actually, both of those versions are horrible. just initialize the instance field directly in its declaration. It will then be initialized when the class is first accessed and synchronized implicitly once, allowing subsequence calls to getInstance() to be unsynchronized.
Michael Borgwardt
2009-09-12 00:15:03
and we all know that static factories like this are evil. Sometimes you have to go evil to just get the job done, but that doesn't make it right. Better to inject resources.
Kevin Day
2009-09-12 03:59:04