Rajat Saxena
Rajat Saxena

Reputation: 3925

JVM byte code output

In JVM specs, The following example

void createThreadArray() {
    Thread threads[];
    int count = 10;
    threads = new Thread[count];
    threads[0] = new Thread();
}

produces

Method void createThreadArray()
0   bipush 10           // Push int constant 10
2   istore_2            // Initialize count to that
3   iload_2             // Push count, used by anewarray
4   anewarray class #1  // Create new array of class Thread
7   astore_1            // Store new array in threads
8   aload_1             // Push value of threads
9   iconst_0            // Push int constant 0
10  new #1              // Create instance of class Thread
13  dup                 // Make duplicate reference...
14  invokespecial #5    // ...for Thread's constructor
                        // Method java.lang.Thread.<init>()V
17  aastore             // Store new Thread in array at 0
18  return

My question is, why are we doing istore_2 then iload_2 in this method in the start? Can't we just use the value pushed by bipush 10 onto the stack for creating new array of objects? What's the design consideration behind this?

Upvotes: 2

Views: 199

Answers (2)

apangin
apangin

Reputation: 98495

As it was already told, Javac does not optimize this pattern.
However, not because it could not do so, but because it must not do so.

For every local variable in source code Javac reserves a slot in local variable array in the class file (JVMS §2.6.1). The liveness range of this variable along with its local variable index is stored in LocalVariableTable attribute (JVMS §4.7.13).

This information is necessary for debugging purposes. Local variable array provides mapping from variables in source code to variables in bytecode. E.g. you may set a breakpoint in your code at the line

threads = new Thread[count];

and query the value of count variable that is mapped to locals[2] in the bytecode.

Upvotes: 3

wero
wero

Reputation: 33000

javac is not an optimizing compiler. Optimization like removal of the unnecessesary local variable count is done in the JVM runtime when the runtime detects that it is a hotspot.

By using literal translation it is very easy to construct the bytecode compiler. Any optimization analysis is hard, and is already implemented in the runtime, so javac simply does not do it.

Upvotes: 5

Related Questions