javamultithreadingthread-safetylockingsynchronized

Java synchronized method lock on object, or method?


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?


Solution

  • 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 threads accessing a different variable from the 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. If a and b were object references you would use:

    public void addA() {
        synchronized( a ) {
            a++;
        }
    }
    
    public void addB() {
        synchronized( b ) {
            b++;
        }
    }
    

    But since they're primitives you can't do this.

    I would suggest you to use AtomicInteger instead:

    import java.util.concurrent.atomic.AtomicInteger;
    
    class X {
    
        AtomicInteger a;
        AtomicInteger b;
    
        public void addA(){
            a.incrementAndGet();
        }
    
        public void addB(){ 
            b.incrementAndGet();
        }
    }