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?

11 Answers
11

Leave a Comment