Why are Java objects pointers to pointers?

流过昼夜 提交于 2020-03-18 06:56:11

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/57725764/why-are-java-objects-pointers-to-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!