Sync java local variable

I have a problem with the following java code, this program always gives "KKBB" as the output (so it looks like synchronization works). Therefore, I cannot understand, since I am a local variable, why does synchronization work 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 method, so the synchronization will not work, please help me understand, thanks

+5
source share
1 answer

Shell classes have special behavior for small values. If you use Integer.valueOf() (or Short , Char or Byte ) for a value from -128 to 127, you will get a shared cached instance.

Autoboxing heals

 Integer i = 10; 

a

 Integer i = Integer.valueOf(10); 

therefore, the different i variables actually refer to the same Integer instance and thus share the monitor.

+7
source

Source: https://habr.com/ru/post/1200373/


All Articles