Sergey Sergey - 1 year ago 76
Java Question

Why doesn't the JVM compile the entire program up front, instead of compiling it piece-by-piece?

For this thread Herbert Schildt writes:

It is important to understand that it is not practical to compile an entire Java program into executable code all at once, because Java performs various run-time checks that can be done only at run time.

What run-time checks does he mean?

Please explain the reasons of compiling bytecode piece-by-piece, not the entire program.

Answer Source

What he is saying is that it's impractical to compile all the bytecode to machine language at runtime. You could precompile everything, but that's not the approach that JIT takes.

For one thing, there is no knowing how large the program is. People would get fairly upset at a 30 minute startup as it compiled every library it could find (A given Java program isn't in a single file, it has access to everything in the classpath)

For another, even if you told the system exactly what components your program would use, there is no telling how much of your program could be used for a given run--people would get more upset at a 30 minute startup to run a command line program with parameters consisting of "--help"

Finally it can do some great tricks by compiling while it's running. with a method like this:

public testMeh(int param) {
    if(param == 35) 
        do bunches of crap;
    else if (param > 5)
        do much more crap;

The compiler can call it once or twice and on the fly recognize that values 5 and under just return. If this is called all the time with a value of 2 it can replace the ENTIRE method call with if (param != 2) testMeh(param);

which eliminates the entire method call for that number. Later it can figure out that not calling that method means certain member variables can't change and that can collapse other portions of the code to nothing.

This is just plain hard as hell if you precompile stuff. I mean you could write exception code everywhere as you recognize patterns but your code would quickly become a nightmare.

Now if you are asking why not precompile the entire program when you compile it into bytecode--that's a different question and not what the quote was addressing at all--but you can do that to. It's been done and works pretty well. You trade portability and runtime flexibility for a quicker start time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download