Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java local variable synchronization

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

like image 458
Buddhika Livera Avatar asked Aug 15 '14 01:08

Buddhika Livera


People also ask

Can I synchronize a variable in Java?

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.

What is the disadvantage of synchronization in Java?

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.

Does Java run synchronously?

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.


1 Answers

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.

like image 90
chrylis -cautiouslyoptimistic- Avatar answered Oct 16 '22 08:10

chrylis -cautiouslyoptimistic-