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
You can have both static synchronized method and nonstatic synchronized method and synchronized blocks in Java but we can not have synchronized variable in java. Using synchronized keyword with a variable is illegal and will result in compilation error.
First drawback is that threads that are blocked waiting to execute synchronize code can't be interrupted. Once they're blocked their stuck there, until they get the lock for the object the code is synchronizing on.
Java provides a way of creating threads and synchronizing their tasks using synchronized blocks. Synchronized blocks in Java are marked with the synchronized keyword. A synchronized block in Java is synchronized on some object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With