4

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?

Stefan
  • 5,052
  • 3
  • 7
  • 12
  • 3
    The main point there is actually the "*The Java Virtual Machine does not mandate any particular internal structure for objects*". Which means what you describing might very well be true for many JVM implementations out there. – M. Prokhorov Aug 30 '19 at 11:38

1 Answers1

9

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.

Holger
  • 285,553
  • 42
  • 434
  • 765
  • 1
    Where "recent" means "for at least the last 20 years." – Brian Goetz Oct 26 '19 at 00:44
  • 1
    @BrianGoetz you’re referring to the point when Sun’s implementation(s) stopped using the pattern, but my statement using the phrase “all recent” is implying the point of time when no JVM of that kind had any relevance anymore, which bears some grain of speculation. Well, I know, if I only got a coin every time I used the term “recent” and thought about whether to add “whereas ‘recent’ means the ‘the last *n* decades’”… – Holger Oct 28 '19 at 12:11