Run-time data area structure

The interaction between heap, stack, and method

1. Introduction:

The Java Virtual Machine Specification makes it clear that “although all method areas are logically part of the heap, some simple implementations may not choose to garbage collect or compress.” But in the case of HotSpotJVM, the method area is also called non-heap to separate it from the Heap. So, the method area is considered a piece of memory separate from the Java heap.

  • The Method Area, like the Java heap, is an Area of memory shared by individual threads.

  • The method area is created at JVM startup, and its actual physical memory space can be as discontinuous as the Java heap area.

  • The size of the method area, like the heap space, can be fixed or scalable.

  • The size of the method area determines how many classes the system can hold. If the system defines too many classes and causes the method area to overflow, the VIRTUAL machine will also throw an overflow error: Java. Lang. OutofMemoryError: PermGen space before (8) or Java. Lang. OutofMemoryError: Metaspace (8 and later)

    • Loading too many third-party JAR packages; Too many Tomcat deployment projects; Lots of dynamically generated reflection classes
  • Shutting down the JVM frees up memory in this area.

Nicknames: JDK7 and before (permanent generation), JDK8 and after (meta space)

The evolution of

Similar in nature to permanent generations, meta-spaces are implementations of method areas in the JVM specification. However, the biggest difference between the meta-space and the permanent generation is that the meta-space is not in the memory set by the VM, but uses local memory.

It’s not just the names of the permanent generation and the metacolor that have changed.

2. Set the method area memory size

  • Metadata area size can use parameters-XX:MetaspaceSizeand-XX:MaxMetaspaceSizeSpecifies to replace the previous two parameters.
  • The default values are platform dependent. On Windows, the value of -xx :MetaspaceSize is 21M, and the value of -xx :MaxMetaspaceSize is -1, indicating that there is no limit.
  • Unlike the permanent generation, if the size is not specified, the virtual machine uses up all available system memory by default. If the metadata area overflow, virtual machine will throw an exception OutOfMemoryError: Metaspace
  • -xx :MetaspaceSize: sets the initial MetaspaceSize size. For a 64-bit server-side JVM, the default XX:MetaspaceSize value is 21MB. This is the initial high watermark, and once it is reached, the Full GC will be triggered to unload useless classes (i.e. their corresponding classloaders are no longer alive) and the high watermark will reset. The value of the new high water level depends on how much space is freed after GC. If the free space is insufficient, increase this value appropriately until MaxMetaspaceSize is exceeded. If too much space is freed, lower this value appropriately.
  • If the initial high water mark is set too low, the above high water mark adjustment can occur many times. Multiple Fu11 GC calls can be observed from the garbage collector logs. To avoid frequent GC, it is recommended to set -xx :MetaspaceSize to a relatively high value.

How to solve these OOM?

In order to resolve OOM or Heap space exceptions, a common method is to first analyze heap dump snapshots through a Memory image analysis tool (such as Eclipse Memory Analyzer). The focus is to determine whether the objects in Memory are necessary. In other words, it is important to distinguish between Memory leak and Memory Overflow.

2. If there is a memory leak, you can further check the leak object’s reference chain to GC Roots by using the tool. You can then find out how the leak objects are associated with GC Roots and cause the garbage collector to fail to reclaim them automatically. With the information of the type of the leaking object and the GC Roots reference chain, the location of the leaking code can be more accurately located.

3, if there is no memory leaks, in other words, an in-memory object does also have to live with, it shall check the pile of parameters of the virtual machine (-xmx and – Xms), compared with the machine physical memory to see if can also big, check whether there is a certain object lifecycle from the code is too long, the state holding time is too long, Try to reduce the memory consumption of the program’s runtime

3. Method area memory structure

3.1 Contents stored in method area:

1. Type information

For each loaded type (class, interface, enum, annotation), the JVM stores the following type information in the method area: ① The full valid name of the type (full name = package name). Class name) ② The full valid name of the type’s immediate parent (there is no parent for interface or Java.lang. object) ③ the type’s modifiers (some subset of public,abstract,final) ④ An ordered list of the type’s immediate interfaces

2. Domain information

The JVM must keep information about all fields of the type and the order in which the fields are declared in the method area.

Domain information including: domain name, domain type, domain modifier (public, private, protected, static, final, volatile, a subset of the transient)

3. Method information

The JVM must hold the following information about all methods, including the declaration order, as well as domain information:

  1. Method names
  2. Method return type (or void)
  3. Number and type of method parameters (in order)
  4. Method of the modifier (public, private, protected, static, final, synchronized, native, a subset of the abstract)
  5. Bytecodes, operand stack, local variable table and size of methods (except abstract and native methods)
  6. Exception table (except for abstract and native methods) : the start and end location of each exception handler, the offset address of the code handler in the program counter, and the constant pool index of the caught exception class

To view the cli, enter javap -v -p (including the private permission) xxx.class > xxx.txt

Example:

public class Test extends HashMap implements Serializable {
    private String name = "";
    private int x = 1;
    public Test(String name) {
        this.name = name;
    }

    public static void main(String[] args) {
        Test haha = new Test(null);
        int nameLength = haha.getNameLength();
        System.out.println(nameLength);
    }

    public int getNameLength(a) {
        int y = 0;
        try {
            y = name.length();
        } catch (NullPointerException e) {
            System.out.println("Null pointer exception");
            e.printStackTrace();
        }
        returny; }}Copy the code
Classfile /D:/ideaFiles/Algorithm/out/production/Algorithm/com/lx/mySort/Test.class
  Last modified 2020-7-29; size 1145 bytes
  MD5 checksum 8f9825153f3fa6f2042785c0df59703b
  Compiled from "Test.java"
/ / class information
public class com.lx.mySort.Test extends java.util.HashMap implements java.io.Serializable
  minor version: 0
  major version: 52
  flags: ACC_PUBLIC.ACC_SUPER
Constant pool# 1:= Methodref          #15.#44        // java/util/HashMap."<init>":()V
   #2 = String             #45            //. {/ / domain information
  private java.lang.String name;
    descriptor: Ljava/lang/String;
    flags: ACC_PRIVATE

  private int x;
    descriptor: I
    flags: ACC_PRIVATE

// Method information.public int getNameLength(a);
    descriptor: ()I
    flags: ACC_PUBLIC
    Code:
      stack=2, locals=3, args_size=1
         0: iconst_0
         1: istore_1
         2: aload_0
         3: getfield      #3                  // Field name:Ljava/lang/String;
         6: invokevirtual #10                 // Method java/lang/String.length:()I
         9: istore_1
        10: goto          26
        13: astore_2
        14: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream;
        17: ldc           #12                 // String null pointer exception
        19: invokevirtual #13                 // Method java/io/PrintStream.println:(Ljava/lang/String;) V
        22: aload_2
        23: invokevirtual #14                 // Method java/lang/NullPointerException.printStackTrace:()V
        26: iload_1
        27: ireturn
/ / table
      Exception table:
         from    to  target type
             2    10    13   Class java/lang/NullPointerException
      LineNumberTable:
        line 26: 0
        line 28: 2
        line 32: 10
        line 29: 13
        line 30: 14
        line 31: 22
        line 33: 26
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
           14      12     2     e   Ljava/lang/NullPointerException;
            0      28     0  this   Lcom/lx/mySort/Test;
            2      26     1     y   I
      StackMapTable: number_of_entries = 2
        frame_type = 255 /* full_frame */
          offset_delta = 13
          locals = [ class com/lx/mySort/Test.int ]
          stack = [ class java/lang/NullPointerException ]
        frame_type = 12 /* same */
}
SourceFile: "Test.java"
Copy the code
4. Static variables
  • Non-final class variable

    Static Static variables: Load preparation (default value), initialization (given value)

  • Global constants

Static final: Assigns a given value at compile time (preparation stage)

5. Runtime constant pool
Constant pool

Constant pool location

A valid bytecode file contains not only the version information, fields, methods, and interfaces of the class, but also the Constant Pool Table, which contains various literals and symbolic references to types, fields, and methods.

Constant pool functions:

A Java source file of classes, interfaces, compiled to produce a bytecode file. Bytecodes in Java require data support, usually too large to be stored directly in bytecodes, or, alternatively, in a constant pool, which contains references to the constant pool. Runtime constant pools are used for dynamic linking, as described earlier.

Data stored in a constant pool

  1. Number of values
  2. A string value
  3. Class reference
  4. Field reference
  5. Method references
Run-time constant pool
  • The Runtime Constant Pool is part of the method area.

  • The Constant Pool Table is part of the class file.

  • Runtime constant pool, which is created after classes and interfaces are loaded into the VIRTUAL machine.

  • The JVM maintains a constant pool for each loaded type (class or interface).

  • The runtime constant pool contains a variety of constants, from numeric literals that are explicit at compile time to method or field references that are not available until they are parsed at run time. So instead of having a symbolic address in the constant pool, we have a real address.

    • Another important feature of run-time constant pools as opposed to class file constant pools is that they are dynamic.
  • When creating a runtime constant pool for a class or interface, the JVM throws an OutOfMemoryError if the amount of memory required to construct the runtime constant pool exceeds the maximum that can be provided by the method area.

4. Evolution

What would be replaced by a meta-space for permanent proxies

  • It is difficult to determine the size of the permanent generation space, too small is prone to GC/OOM exceptions, too much memory (the meta-space is not in the VIRTUAL machine, but uses local memory, the size is limited only by local memory)
  • Permanent generation is difficult to tune
  • Garbage collection frequency is low

Where do WE put our static variables?

Permanent generations in heap space (7 and later are heap)

5, method area garbage recycling

Main recycling:

Deprecated constants in the constant pool: literal and symbolic references… (If it is not referenced, it can be recycled)

2. Classes that are no longer in use (classes that meet the following three criteria are allowed to be recycled) :

1) All instances of the class are recycled, that is, there are no instances of the class or any of its derived subclasses in the Java heap

2) Class loaders for this class are already recycled (difficult to implement unless carefully designed, such as OSGI, JSP reloading, etc.)

3) The java.lang.Class object corresponding to this Class has no reference anywhere, and no method of this Class can be accessed anywhere through reflection

The HotSpot virtual machine provides the -xnoClassGC parameter to control whether or not to reclaim the type, You can also use -verbose:class and -xx :+ traceclassloading or -xx :+ traceclassclass to view class Loading and unloading information

5, summary

6. Object instantiation

Initialization:

  1. Default initialization
  2. Display initialization/code block initialization/constructor initialization

7, Object memory layout:

Example:

8. Object access location

8.1 Method of accessing objects

  1. Handle access

    Reference stores the stable handle address. When the object is moved (common in garbage collection), only the pointer to the sample data of the object in the handle pool will be changed. Reference does not need to be modified

  1. Direct Pointers (adopted by HotSpot)

    Memory is relatively small

9. Direct memory

  • It is not part of the virtual machine run-time data area, nor is it an area of memory as defined in the Java Virtual Machine Specification.

  • Direct memory is an area of memory outside the Java heap that is requested directly from the system.

  • Derived from NIO, Native memory is operated by DirectByteBuffer that exists in the heap

  • In general, access to direct memory is faster than the Java heap. That is, the read and write performance is high.

    • Therefore, for performance reasons, direct memory may be considered in situations where read and write are frequent.
    • Java’s NIO library allows Java programs to use direct memory for data buffers

Welcome to pay attention to the public number: Java treasure to receive more tutorial welfare