user492052
user492052

Reputation: 151

synchronized methods can execute simultaneously?

I have created 2 objects and 2 threads. Assume m1() and m2() are synchronized methods.

t1.m1(); t2.m2(); can both threads can execute simultaneously ? is it possible both synchronized methods can execute simultaneously?

Upvotes: 3

Views: 517

Answers (5)

Hardcoded
Hardcoded

Reputation: 6494

Synchronization is always done on a monitor. Only one thread can access a monitor at a time.

When you are synchronizating methods, the monitor is either the object (non-static) or the Class-object (static methods).

You should think of

public synchronized void myMethod(){
  ...
}

as:

public void myMethod(){
  synchronized (this) {
    ...
  }
}

Since you are having two independent object instances with a synchronized method, you have 2 different monitors. Result: Both Threads can work simultaneously.

Upvotes: 0

josefx
josefx

Reputation: 15656

They can execute simultaneously, since synchronized methods lock on the instance.

synchronized void someMethod(){
}

is the same as

void someMethod(){
   synchronized(this){
   }
}

So every instance has its own lock to synchronise on.

Static methods use the class instance instead (SomeClass.class).

Upvotes: 1

Michael Borgwardt
Michael Borgwardt

Reputation: 346260

Synchronization happens on specific instances. Synchronized methods synchronize on the instances the method is called on. Thus, t1.m1() and t2.m2() can execute simultaneously if and only if t1 and t2 refer to different instances.

Upvotes: 2

Adeel Ansari
Adeel Ansari

Reputation: 39887

Yes, if both are non-static and are executed using two different instances.

Explanation added.

Because monitor is actually associated with the instance. So, if one thread acquired the lock on one instance, the thread is free to invoke the method on the other instance.

Upvotes: 1

Bozho
Bozho

Reputation: 597016

Yes, if they are instance methods of different instances, they are synchronization does not happen.

Upvotes: 0

Related Questions