Search code examples
javareferencehandle

What is the concept of handle in Java?


I read on a site ( http://www.rajeshpatkar.com/articles/javarefpnt/ ) that when we instantiate a class i.e

Emp e = new Emp();

A handle is stored in the variable e, which is not a pointer i.e it does not store the address of object in memory.

The explanation gives an example of array of pointers. The memory address is stored at a[1] position and when the object is moved this position is updated with new address.

So why this array is used instead of directly storing the address (it states that it helps GC, but i didn't understand it ) and updating it (the address stored in e) when the object is moved?

I've spent quite a lot of time in understanding this, but still haven't found an answer that satisfies me. So if you can explain me what actually is stored in the variable 'e' (with an example) it would be quiet helpful.

Thanks :)


Solution

  • The usual term is "object reference" (or just "reference"), rather than "handle."

    An object reference is an opaque value that uniquely identifies a certain object to the JVM. The form of that value is not defined by the specification other than. I suspect it's typically the size of an int or long, but I don't think even that is covered by either the JLS or the JVM spec. (To give you an idea, the JVM spec expressly points out that even the exact value of null [the special value meaning "no reference"] isn't mandated.)

    References are not pointers, although of course since the form of a reference isn't specified, it would be possible for a JVM to be implemented by using pointers as references, so long as that fact couldn't be exploited in a way that violated the spec.

    Because references are not pointers, Java doesn't have "pointer arithmetic" like C and its related languages do.

    So if you can explain me what actually is stored in the variable 'e' (with an example) it would be quiet helpful.

    It's not defined by the spec. It's just a value that uniquely identifies an object (and we can never see that value; the myth that the hex value you see when you use System.out to print an object that doesn't implement toString is the object's reference is just that: a myth). How that value identifies that object is up to the implementation of the JVM. It could be a pointer. It could be an index into an array of pointers. It could be more complex, using different bits from the reference value for different things.