My env:
- JDK : temurin-1.8.0_332
- System: macOS big sur
- VM: Hot Spot
- GuaranteedSafepointInterval = 1000ms (default)
Q1: The vm param GuaranteedSafepointInterval = 1000ms is really accurately?
public class Test {
public static AtomicInteger count = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 0;i < 1000000000;i++){
count.getAndAdd(1);
}
System.out.println(Thread.currentThread().getName() + " done" );
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
Thread.sleep(1000);
System.out.println("count result = " + count);
}
}
As expect,because of the safepoint, the result is
count result = 2000000000
Thread-1 done
Thread-0 done
But ,if change the main thread sleep time to 800ms...(more you can use <800ms) result
So, the default value GuaranteedSafepointInterval = 1000ms is really accurately?
Q2: Sometimes,if i still set sleep time = 1000ms,but change the loop content count.getAndAdd(1)
to count.getAndAdd(i)
,the "count result" will print after 1s...... as i know,the hot spot vm(jdk=1.8) does some optimizations for 'Counted Loop' when sets savepoint ,(according to the Q1 scence),why it doesnt effective?
Any Can Help Me? More Thanks...