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.