Context
I am reading a tech document which basically tells me the difference between using int vs long in fori loop: Scenario A(int fori loop)
public class SafePoint {
public static AtomicInteger num = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
Runnable runnable=()->{
for (int i = 0; i < 1000000000; i++) {
num.getAndAdd(1);
}
System.out.println(Thread.currentThread().getName()+"end!");
};
Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);
t1.start();
t2.start();
Thread.sleep(1000);
System.out.println("num = " + num);
}
}
Expected Result:
Thread-1end!
Thread-0end!
num = 2000000000
Scenario B(long fori loop)
public class SafePoint {
public static AtomicInteger num = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
Runnable runnable=()->{
for (long i = 0; i < 1000000000; i++) {
num.getAndAdd(1);
}
System.out.println(Thread.currentThread().getName()+"end!");
};
Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);
t1.start();
t2.start();
Thread.sleep(1000);
System.out.println("num = " + num);
}
}
Expected Result:
num = 55406251 (or some random number less than 2000000000)
Thread-1end!
Thread-0end!
The most important concept he gives is the safepoint: We have safepoint in long fori loop due to uncounted loop but not int fori loop. Therefore in int fori loop, the sleep needs to wait for the two threads to finish and then do GC cause there is no safepoint when the threads are still in int fori loop.
Issue:
I take his idea and try to reproduce them on my local machine then it failed: Basically no matter whether I use int or long, it is always the result similar to the second one. The num get printed first.
Then after carefully thinking, it can only be due to the JVM I use: java 11 corretto.
Based on tech doc's idea, it basicaly means in Java 11 safepints exist both in counted and uncounted loop
Question:
Can anyone test on java 8 and tell me whether that is the reason?
I actually already tested: in java 8 we can observe the expected results of both A and B
Does java 11 change the way how we put Safe Points and why?
Related links:
The tech doc trying to explain on and How to do GC in fori loop: Why Thread.sleep(0) can prevent gc in rocketmq?