简体   繁体   中英

No deadlock while incrementing synchronized Integer objects

I am tried to implement deadlock in my program and all was ok except one issue which I can't explain.

public class Test {
    public static void main(String[] args) throws InterruptedException {
        Integer balanceA = 10000;
        Integer balanceB = 10000;

        Thread t1 = new Thread(() -> {
            while (true) {
                Processor.run(balanceA, balanceB);
            }
        });

        Thread t2 = new Thread(() -> {
            while (true) {
                Processor.run(balanceB, balanceA);
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }
}

class Processor {
    public static void run(Integer balanceA, Integer balanceB) {
        synchronized (balanceA) {
            synchronized (balanceB) {
                System.out.println(balanceA++ + "; " + balanceB--);
            }
        }
    }
}

Why it always show me the same result as if I did't modify Integer values:

10000; 10000

10000; 10000

...

balanceA++ is equivalent to balanceA = balance + 1 . It doesn't modify the Integer (it can't, because Integer is immutable). It just changes the value of the balanceA parameter to refer to a different object.

If you use AtomicInteger and call either incrementAndGet or getAndIncrement , then you'll see the values changing. You also won't need any synchronization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM