javajvmjava-memory-model

Where JVM keeps information about reference and object types


I am trying to deepen my knowledge in Java Memory Model and JVM.

The basic concept is easy, but I cannot understand where JVM keeps information about types for primitives, objects and references.

For example

  1. we have variable int i = 0. This value is stored in thread's stack. This is just a 4 bytes that contains value 0x0000 in RAM or/and CPU cache. But it doesn't contain any information about its type. Imagine that you can get access to these bytes in memory directly. You cannot be sure that it is a integer. As far as i understand you won't be able to say nothing about its type. This is just 4 bytes information.

Thus, JVM has to keep some information about its type in other place, but where and how JVM keeps it?

  1. Reference object
class A {}
class B extends A {}

A obj = new B();

In this case we have something like this:

| stack |        |HEAP|         |PermGen|

 "reference" ----> "Object"          "A", "B".

Reference is located in stack and has type "A", but reference contains only information where "Object" is stored. It has 8bytes (can be compressed to 4byte if JVM uses less then 32GB). It doesn't have any information about its type in these 8 bytes.

"Object" is located in heap and has type "B". I don't know if it has there any information about its type...

  1. References with generics.
List<String> list = new ArrayList<>();

Where and how JVM keeps information about each type for objects and references?


Solution

  • I cannot understand where JVM keeps information about types for primitives, objects and references.

    The JVM has a space (Perm Gen or Metaspace) where records all type information and code.

    This is just 4 bytes information.

    Yes, it could be an boolean, an int or a 32-bit reference.Most likely it is in a register which means it doesn't even use any memory.

    JVM has to keep some information about its type in other place, but where and how JVM keeps it?

    Actually it doesn't. If it way to look up such information on every access it would be extremely slow. Instead it has machine code which puts a 4 byte value into a register and then just assumes it is the type it expect it to be.

    The only thing it needs to keep track of is which registers hold references and which hold primitives. It needs this to perform a GC.

    The code which is being run can have meta information about which registers and which stack locations have references. Registers are not allocated dynamically except when the code is recompiled.

    References with generics. List list = new ArrayList<>(); Where and how JVM keeps information about each type for objects and references?

    It doesn't. Generics are a compile time feature.

    There is some information you can obtain at runtime, however this is not available on objects, only on classes.