How do I obtain multiple locks in cases like this:
public class DoubleCounter
{
private int valA = 0;
private int valB = 0;
private Object lockA = new Object();
private Object lockB = new Object();
public void incrementA()
{
synchronized (lockA)
{
valA++;
}
}
public void incrementB()
{
synchronized (lockB)
{
valB++;
}
}
public void print()
{
//I have to obtain both lockA & lockB before executing this:
System.out.format("valA: %d\nvalB: %d", valA, valB);
}
}
Keep in mind I don't want the execution of incrementA()
by one thread to block the execution of incrementB()
by another - therefore I don't want to use synchronized methods.
Similar (not exactly the same) question has been asked twice on StackOverflow but I still haven't got the answer I was looking for. The only thing I know is that I shouldn't nest one synchronized()
inside another synchornized()
.