Vladimir
Vladimir

Reputation: 13153

Java synchronized methods question

I have class with 2 synchronized methods:

class Service {

 public synchronized void calc1();

 public synchronized void calc2();

}

Both takes considerable time to execute. The question is would execution of these methods blocks each other. I.e. can both methods be executed in parallel in different threads?

Upvotes: 3

Views: 1432

Answers (3)

Andrzej Doyle
Andrzej Doyle

Reputation: 103777

No they can't be executed in parallel on the same service - both methods share the same monitor (i.e. this), and so if thread A is executing calc1, thread B won't be able to obtain the monitor and so won't be able to run calc2. (Note that thread B could call either method on a different instance of Service though, as it will be trying to acquire a different, unheld monitor, since the this in question would be different.)

The simplest solution (assuming you want them to run independently) would be to do something like the following using explicit monitors:

class Service {
   private final Object calc1Lock = new Object();
   private final Object calc2Lock = new Object();

   public void calc1() {
       synchronized(calc1Lock) {
           // ... method body
       }
   }

   public void calc2() {
       synchronized(calc2Lock) {
           // ... method body
       }
   }

}

The "locks" in question don't need to have any special abilities other than being Objects, and thus having a specific monitor. If you have more complex requirements that might involve trying to lock and falling back immediately, or querying who holds a lock, you can use the actual Lock objects, but for the basic case these simple Object locks are fine.

Upvotes: 10

fastcodejava
fastcodejava

Reputation: 41077

No, they cannot be. In this case you might use a synchronized block instead of synchronizing the whole method. Don't forget to synchronize on different objects.

Upvotes: 0

Matthias
Matthias

Reputation: 12259

Yes, you can execute them in two different threads without messing up your class internals but no they won't run in parallel - only one of them will be executed at each time.

Upvotes: 1

Related Questions