Class UnsafeStrategy

All Implemented Interfaces:
MemoryMeterStrategy

public final class UnsafeStrategy extends MemoryLayoutBasedStrategy
MemoryMeterStrategy relying on Unsafe to measure object sizes for Java versions ≥ 15.

In Java 15, the way the JVM layout fields across the hierarchy changed. Prior to Java 15 superclass field always came first. Therefore that strategy could only look at the current class to find the greatest offsets. From Java 15 onward it is not the case anymore. The JVM optimizes ensure minimal memory usage by packing the fields in the best possible way across the hierarchy (https://bugs.openjdk.org/browse/JDK-8237767).

Another important change that came in Java 15 is the introduction of hidden classes (https://openjdk.org/jeps/371) and the use of hidden class for lambda. Attempting to use Unsafe.objectFieldOffset on an hidden class field will result in a UnsupportedOperationException preventing the UnsafeStrategy to evaluate correctly the memory used by the class. To avoid that problem UnsafeStrategy will rely on the SpecStrategy to measure hidden classes. This can lead to an overestimation of the object size as the SpecStrategy ignore some optimizations performed by the JVM

  • Constructor Details

  • Method Details

    • measureInstance

      public long measureInstance(Object instance, Class<?> type)
      Description copied from class: MemoryLayoutBasedStrategy
      Measures the shallow memory used by objects of the specified class.
      Specified by:
      measureInstance in class MemoryLayoutBasedStrategy
      Parameters:
      instance - the object to measure
      type - the object type
      Returns:
      the shallow memory used by the object
    • arrayBaseOffset

      protected int arrayBaseOffset()
      Description copied from class: MemoryLayoutBasedStrategy
      Returns the array base offset.

      Array base is aligned based on heap word. It is not visible by default as compressed references are used and the header size is 16 but becomes visible when they are disabled.

      Overrides:
      arrayBaseOffset in class MemoryLayoutBasedStrategy
      Returns:
      the array base offset.