Reputation: 51
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
Upvotes: 5
Views: 157
Reputation: 77167
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.
Upvotes: 8