In the below code total is always 45, but total1 is unpredictable. I feel total should be unpredictable too as threads are not depending whether lock is acquired by tryLock() or not. Please can anybody explain what is the difference in calculation of total and total1.
import java.util.concurrent.locks.*;
import java.util.concurrent.atomic.*;
import java.util.stream.*;
public class HelloWorld{
private Lock vault = new ReentrantLock();
private int total = 0;
private int total1 = 0;
public void deposit(int value) {
try {
vault.tryLock();
total += value;
}
finally {
vault.unlock();
}
}
public void add(int val) {
total1 += val;
}
public static void main(String[] unused) {
HelloWorld bank = new HelloWorld();
IntStream.range(1, 10)
.parallel()
.forEach(s -> bank.deposit(s));
System.out.println(bank.total); // 45
HelloWorld bank1 = new HelloWorld();
AtomicLong value1 = new AtomicLong(0);
final long[] value2 = {0};
IntStream.iterate(1, i -> 1).limit(100)
.parallel()
.forEach(i -> value1.incrementAndGet());
IntStream.iterate(1, i -> 1).limit(100)
.parallel()
.forEach(i -> ++value2[0]);
IntStream.iterate(1, i -> 1).limit(100)
.parallel()
.forEach(i -> bank1.add(i));
System.out.println(value1+" "+value2[0]+" " +bank1.total1); // 100 94(Unpredictable) 96 (Unpredictable)
}
}