Why are Java objects pointers to pointers?

Stefan :

The JVMS says that:

In some of Oracle’s implementations of the Java Virtual Machine, a reference to a class instance is a pointer to a handle that is itself a pair of pointers: one to a table containing the methods of the object and a pointer to the Class object that represents the type of the object, and the other to the memory allocated from the heap for the object data.

I don't understand why references would be implemented this way rather than making them a pointer to the method table pointer directly followed by the object's data. This would avoid an extra memory allocation on object creation and an extra pointer dereference on field access.

What's the reason Oracle implemented them like that instead?

Holger :

Such a strategy would allow moving objects in memory without the need to adapt all existing references, as only the one direct pointer needs to be adapted. Moving objects in memory will be done by copying or compacting garbage collectors.

However, for all recent JVM implementations the costs of this indirection were considered not worth the saving, so “some of Oracle’s implementations” actually means “some very old JVMs from Sun which Oracle got when buying Sun”. Today’s real world JVMs do adapt all references when moving objects in memory.

In other words, that’s rather an outdated statement regarding JVMs still in use, but was kept in the specification as an example of an alternative implementation strategy.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=140106&siteId=1