Search code examples
javaobjectjvmvm-implementation

With the Java VM, how are object references treated


During the execution of a Java application, are object references used by the runtime or are they stripped away at compile time?

I guess I could decompile class files and see how they are used as local variables and member variables.

Is it wasteful to create an object reference when you don't need to or will the compiler strip away unneeded references?

E.g.

final String abc = "abc"; method(abc);

as opposed to:

method("abc");


Solution

  • Methods are stored in the object data area (as laid out by the class definition), but block local references are stored in a special area of the JVM stack frame. When the frame pops off of the frame stack of the executing thread, all the block local references are lost as they are not actually stored in the object's data structures.

    Note that if you are unfamiliar with JVM stack frames, a new stack frame is obtained for the entry into every method, and is popped off the Thread's stack when returning from a method. Stack frames contain a number of elements, including a pointer to the current instruction (which is located in the Class's instruction pages) a pointer to the "this" object, and a small stack to hold intermediates in the current method calculation. Sometimes a variable reference doesn't incur any need for storage, and many optimizing compilers will then compile out the code to use the local stack instead of the "object reference storage" meaning that reversing of the code will result in not discovering that the person used a variable at all.

    The "this" pointer always occupies the first entry in the object reference storage area, and all of these concepts are conceptual. The actual implementation only needs to conform to the operational standard, it doesn't need to conform to a particular memory layout.