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?
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 executingcalc1, thread B won’t be able to obtain the monitor and so won’t be able to runcalc2. (Note that thread B could call either method on a different instance ofServicethough, as it will be trying to acquire a different, unheld monitor, since thethisin 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:
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
Objectlocks are fine.