Java – is it acceptable to always use ‘this’ as a monitor lock?
•
Java
For example, I have a class with 2 counters (in a multithreaded environment):
public class MyClass { private int counter1; private int counter2; public synchronized void increment1() { counter1++; } public synchronized void increment2() { counter2++; } }
There 2 addition operations are independent of each other But I use the same object to lock (this)
Indeed, if the client calls both increment1 () and increment2 () methods, the increment2 call will be blocked until increment1 () releases the monitor?
If this is true, does it mean that I need to provide different monitor locks for each operation (for performance reasons)?
Solution
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码