5

I have problem with following java code, this program always give "KKBB" as the output (so it seems like synchronization works ), So i am unable to understand since i is a local variable why synchronization is working here?

class Test implements Runnable {
    public void run() {
        Integer i=10;
        synchronized(i)
        {
            try {
                System.out.print(Thread.currentThread().getName());
                Thread.sleep(1200);
                System.out.print(Thread.currentThread().getName());
            } catch (InterruptedException e) {
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new Test(), "K").start();
        new Thread(new Test(), "B").start();
    }
}

I heard that since local variables have different copies for each methods, so synchronization won't work, please help me to understand, thanks

1
  • Re, "since i is a local variable..." The synchronized(i) statement does not operate on the variable, it operates on the object to which the variable refers. As @chrylis pointed out, Integer.valueOf(10) always refers to the same cached Integer object. Commented Aug 15, 2014 at 13:50

1 Answer 1

8

The wrapper classes have special behavior for small values. If you use Integer.valueOf() (or Short, Char, or Byte) for a value between -128 and 127, you'll get a shared cached instance.

The autoboxing treats

Integer i = 10;

as

Integer i = Integer.valueOf(10);

so the different i variables are actually referring to the same instance of Integer and thus share a monitor.

Sign up to request clarification or add additional context in comments.

1 Comment

Right -- you don't synchronize on the variable, you synchronize on the object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.