0

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

Adwait Kumar
  • 1,502
  • 10
  • 20
  • 1
    This seems to be an artifact of the decompiler. I don’t know of any compiler generating code with such a `boolean` variable. Most notably, neither javac nor Eclipse do that. – Holger Jun 02 '22 at 09:52

0 Answers0