I have a piece of code that looks something like this,
import java.util.concurrent.ThreadLocalRandom;
public class CompilerBehaviour {
public static void main(String[] args) throws Exception {
new CompilerBehaviour().test();
}
Integer test() {
long startTime = System.currentTimeMillis();
try {
return methodCall();
} finally {
long timeTaken = System.currentTimeMillis() - startTime;
System.out.println("Time taken" + timeTaken);
}
}
Integer methodCall() {
return ThreadLocalRandom.current().nextInt();
}
}
When I compile this and de-compile it using FernFlower decompiler, I get the below
import java.util.concurrent.ThreadLocalRandom;
public class CompilerBehaviour {
public CompilerBehaviour() {
}
public static void main(String[] args) throws Exception {
(new CompilerBehaviour()).test();
}
Integer test() {
long startTime = System.currentTimeMillis();
boolean var10 = false;
Integer var3;
try {
var10 = true;
var3 = methodCall();
var10 = false;
} finally {
if (var10) {
long timeTaken = System.currentTimeMillis() - startTime;
System.out.println("Time taken" + timeTaken);
}
}
long timeTaken = System.currentTimeMillis() - startTime;
System.out.println("Time taken" + timeTaken);
return var3;
}
Integer methodCall() {
return ThreadLocalRandom.current().nextInt();
}
}
I am unable to understand why does the compiler need to modify the logic to duplicate what was happening in finally block and also use a boolean variable var10 to keep track if an exception is being thrown or not.
Why can't it leave the logic exactly as it was written ? Is this some performance optimization?
I am using coretto-11.0.14