Possible Duplicate:
Java synchronized methods: lock on object or class
Please Explain How Java synchronized work with static method ? Some one has said that it is done by its Class Object but they don't say how the lock is done with that.
Possible Duplicate:
Java synchronized methods: lock on object or class
Please Explain How Java synchronized work with static method ? Some one has said that it is done by its Class Object but they don't say how the lock is done with that.
You always synchronize on a monitor object. Every Java object can be used here.
With a synchronized block, you can specify that object directly.
synchronized (something){
}
With a synchronized method, it synchronizes on the object instance itself (on this
), so it is identical to:
synchronized (this) {
}
With a synchronized static method, it synchronizes on the class object, just like "some one has said".
synchronized (ThisClass.class){
}
The mechanism is always the same: Only one thread can hold the lock at the same time, others have to wait.