If I have 2 synchronized methods in the same class, but each accessing different variables, can 2 threads access those 2 methods at the same time? Does the lock occur on the object, or does it get as specific as the variables inside the synchronized method?
Example:
class X {
private int a;
private int b;
public synchronized void addA(){
a++;
}
public synchronized void addB(){
b++;
}
}
Can 2 threads access the same instance of class X performing x.addA(
) and x.addB()
at the same time?
Best Answer
If you declare the method as synchronized (as you're doing by typing
public synchronized void addA()
) you synchronize on the whole object, so two thread accessing a different variable from this same object would block each other anyway.If you want to synchronize only on one variable at a time, so two threads won't block each other while accessing different variables, you have synchronize on them separately in
synchronized ()
blocks. Ifa
andb
were object references you would use:But since they're primitives you can't do this.
I would suggest you to use AtomicInteger instead: