If I have a method like this
public synchronized static foo()
{
}
this compiles fine.
So this leads me to two questions
- What is is syncrhonizing on? The Class, or something else?
- Can you synchronize on a class, does that lock all object of that class as well.
for instance could you do this
synchronized(Foo) // where Foo is a class
{
}
Synchronized static method in
MyClassis essentially the same assynchronized(MyClass.class)block. Your second example should be rewritten asto be correct.
If you would like to be defensive about your class synchronization, you should synchronize on a private static object not visible outside your class. This prevents malicious code from blocking your static methods by executing
synchronizedon their class object, thus blocking the legitimate method.As far as “locking all objects” goes, non-static methods marked
synchronizedwill not be locked by execution of a staticsynchronizedmethod, because regularsynchronizedmethods lock on an instance of the object, not on its class.