Search code examples
javareferencejava-ee-6

Java reference variable management?


I want to understand the exact management of reference variables in Java. How memory is management for them? How much memory itself a reference variable takes say of 32 bit or 64 bit operating system.

What about two of following code? Which would be better based on above questions

Creating reference variable one and assigning it to new objects (Flyweight pattern I guess ??).

    StringBuilder strReference = null; 
    for(int i = 0;i < 1000000; i ++) {
        strReference = // assiging some object from somewhere say from DB list
        // doing some operation on object with strReference
    }

NowCreating the Reference variable everytime in the

        for(int i = 0;i < 1000000; i ++) {
            StringBuilder strReference = // assiging some object from somewhere say from DB list
            // doing some operation on object with strReference
        }

Can I see the exact effect of above two code statements by profiler ?


Solution

  • The exact size of a reference is not mandated by the Java Specifications (you can see what is mandated here). This size is completely dependent on the Java Virtual Machine implementation, and so in some system it can be of 32bits, in other 64bits.

    About you sample code, both are exactly the same for the JVM (see footnote #1 nonetheless). Remember that space for variables created inside functions is kept in the Stack and so before entering the function the JVM will make room for that variable (strReference). Source: here.

    So it is not about where/how you create your references but about where/how you create the data that will be inside your references.

    If you want to see more, try compiling your code and then using javap to see the generated bytecode. That way you can see if the implementation really changes.


    Footnote #1: The first 4 variables/parameters/this in each method have special management inside the bytecode, so there can be a difference in that case if you declare your reference early in the code. This difference is about the size and speed of the bytecode as those 4 first variables have special "opcodes" for them.