Given the complete source code below, please explain why every execution of this program in Eclipse results in time
in do1()
greater than time
in do2()
by 2~3 milliseconds.
Does the JVM need to "warm up"?
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
public class Question {
public static void main(String[] args) {
do1();
do2();
}
public static void do1() {
O obj = new O();
Thread t = new Thread(() -> IntStream.range(0, 100000)
.forEach(e -> obj.incrementN()));
long start = System.currentTimeMillis();
t.start();
try {
t.join();
} catch (InterruptedException e1) {
}
float time = (System.currentTimeMillis()-start)/1000F;
System.out.println(time);
System.out.println(obj);
System.out.println();
}
public static void do2() {
O obj = new O();
Thread t = new Thread(() -> IntStream.range(0, 100000)
.forEach(e -> obj.incrementN()));
long start = System.currentTimeMillis();
t.start();
try {
t.join();
} catch (InterruptedException e1) {
}
float time = (System.currentTimeMillis()-start)/1000F;
System.out.println(time);
System.out.println(obj);
}
}
class O {
private AtomicInteger n = new AtomicInteger(0);
public void incrementN() {
n.getAndIncrement();
}
@Override
public String toString() {
return ""+n.get();
}
}
Sample output:
0.003
100000
0.001
100000