3

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?

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Uhm, but only if the methods are executed on the same object. Otherwise they can execute at the same time because they are not static. There might be multiple Service objects, the question doesn't make a statement about this.
@musiKk - very good point, and one that's worth making explicitly. I've updated my answer accordingly.
1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.