-4

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.

Community
  • 1
  • 1
Harsha
  • 216
  • 1
  • 7

1 Answers1

1

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.

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • No , I ment that static method and instance method. So how both method synchronized block when they access. Specially static method. What is the loked concept when it access. – Harsha Jun 19 '12 at 10:37
  • `static synchronized void theMethod(){}` does the same thing as `static void theMethod(){ synchronized(ThisClass.class){} }` – Thilo Jun 19 '12 at 12:16