I have two unsynchronized threads in a tight loop, incrementing a global variable X times (x=100000).
The correct final value of the global should be 2*X, but since they are unsynchronized it will be less, empirically it is typically just a bit over X
However, in all the test runs the value of global was never under X .
Is it possible for the final result to be less than x ( less than 100000 )?
public class TestClass {
static int global;
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread( () -> { for(int i=0; i < 100000; ++i) { TestClass.global++; } });
Thread t2 = new Thread( () -> { for(int i=0; i < 100000; ++i) { TestClass.global++; } });
t.start(); t2.start();
t.join(); t2.join();
System.out.println("global = " + global);
}
}