shreyasva
shreyasva

Reputation: 13446

Threading and synchronisation in Java

If there is a synchronized method in a class and 1 thread enters it, can another thread call the same method on a different object.

Upvotes: 3

Views: 681

Answers (3)

Farrell
Farrell

Reputation: 508

If the method is marked as synchronized, then the lock is held on the object. This means that a call to the same method on a different object will not be locked.
However, if the method is a static one, then it is held by the entire class and it will not be possible for a second call to run it at the same time [and will be blocked]

Upvotes: 3

Eugene Burtsev
Eugene Burtsev

Reputation: 1475

Yes, another thread can call this method from instance of this class

Upvotes: 0

Joachim Sauer
Joachim Sauer

Reputation: 308001

Yes, if the method is not static.

A synchronized non-static method synchronizes on this. So this method:

public synchronized void foo() {
  // do stuff
}

is effectively equivalent to this one:

public void foo() {
  synchronized(this) {
    // do stuff
  }
}

A staticsynchronized method synchronizes on the current class. So a method like this:

public static synchronized void bar() {
  // do stuff
}

is effectively equivalent to this one:

public static void bar() {
  synchronized(ThisClass.class) {
    // do stuff
  }
}

Upvotes: 7

Related Questions