I found this example code for Joshua Bloch's book, Effective Java. It's meant to demonstrate why you should avoid unnecessarily creating objects:
public class Sum {
private static long sum() {
Long sum = 0L;
for (long i = 0; i <= Integer.MAX_VALUE; i++)
sum += i;
return sum;
}
public static void main(String[] args) {
int numSets = Integer.parseInt(args[0]);
long x = 0;
for (int i = 0; i < numSets; i++) {
long start = System.nanoTime();
x += sum();
long end = System.nanoTime();
System.out.println((end - start) / 1_000_000. + " ms.");
}
// Prevents VM from optimizing away everything.
if (x == 42)
System.out.println();
}
}
What do the last two lines of the main method accomplish here?
That final comparison is the only usage of that variable. Without it, who would care about the value in that variable?
Nobody!
So, the compiler might assume: that value is never used, and the code that writes to it has node side effects. Things that don't get used, why waste time writing to them.
Thus: that final first "read" usages prevents over eager compilerd from "optimizing out" the call to the method you intend to measure!