Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to parse an example of JVM memory structure partition

2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

How to analyze the JVM memory structure partition example, I believe that many inexperienced people do not know what to do, so this paper summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

This article mainly introduces the example analysis of JVM memory structure partition, which is introduced in great detail through the sample code, which has a certain reference and learning value for everyone's study or work. Friends who need it can refer to it.

Data region division

Runtime memory area partition: program counter, virtual machine stack, local method stack, heap, method area

Program counter

There is no run overflow when the thread is private through registers.

The line number indicator executed by the current thread, which remembers the execution address of the next JVM instruction

Virtual machine stack

Garbage collection does not involve stack memory, stack memory is thread private, it can be understood that the memory space needed by a thread to run is composed of stack frames, and each stack frame represents the memory needed for method execution (parameters, local variables, return address) each thread can only have one active stack frame, corresponding to the method currently being executed

Excessive stack memory allocation can only support certain recursive calls, does not affect the running speed, and may reduce the number of threads (because physical memory is certain).

Local method stack

Memory allocated for running local methods (HotSpot combines the virtual machine stack and the local method stack into one)

There is a garbage collection mechanism for thread sharing in the heap. Thread safety issues need to be considered to store instances of objects (objects created by the new keyword). From the perspective of memory allocation: the heap can be divided into private allocation buffers (TLAB) of multiple threads to improve the efficiency of object allocation. Java heap can be in physically discontiguous memory space. But logically, it should be considered continuous (but for large objects such as arrays, continuous memory space may be required)

Method area

The thread sharing area stores type information that has been loaded by the virtual machine, constants, static variables, and the code cache compiled by the instant compiler is created when the virtual machine starts, logically part of the heap (different JVM implementations vary) JDK1.6 uses permanent generation (PerGen) as the method area implementation JDK1.8 uses meta-space (Metaspace) to implement the other method area (including three parts of Class ClassLoader constant pool) Put in direct memory) StringTable is placed in the heap (helps garbage collection management)

Use scenarios: such as dynamic loading used by Spring Mybatis

Running constant pool

The run-time pool is part of the method area

Binary bytecode content: class basic information\ constant pool table\ class method definition, including virtual machine instructions

Among them, the constant pool table stores various literals (such as various basic data types) and symbolic references (such as class name\ method name\ parameter type) generated during compilation. This part of the content will be stored in the runtime constant pool in the method area after the class is loaded, and the symbol address will be changed to the real address.

StringTable

Similar to hashTable structure, it cannot be expanded automatically

A string in a constant pool is just a symbol and becomes an object the first time it is used

Using string pooling mechanism to avoid repeated creation of character objects

Case

The principle of string concatenation is to optimize string splicing at compile time. StringBuilder (JDK1.8) uses the intern () method to actively put string objects that are not already in the string pool into the string pool.

/ / StringTable ["a", "b", "ab"] hashtable structure. The information in the public class Demo1_22 {/ / constant pool cannot be expanded. All the information in the constant pool will be loaded into the running constant pool. In this case, ab ab is the symbol in the constant pool. Not yet java string object / / ldc # 2 will turn a symbol into "a" string object / / ldc # 3 will turn b symbol into "b" string object / / ldc # 4 will turn ab symbol into "ab" string object public static void main (String [] args) {String S1 = "a" / / lazy String S2 = "b"; String S3 = "ab"; String S4 = S1 + S2; / / new StringBuilder (). Append ("a"). Append ("b"). ToString () new String ("ab") String S5 = "a" + "b"; / / javac optimization during compilation, the result has been determined to be ab System.out.println (S3 = S5);}}

After JDK1.7, using the intern () method, you will try to put the string object into the string pool, if there is any, it will not, if not, the object in the string pool will be returned, while JDK1.6 calls the intern () method to copy a copy of the object into the string pool, and the reference to the object in the heap does not change.

Public class Demo1_23 {/ / ["ab", "a", "b"] public static void main (String [] args) {demo1 (); demo2 ();} static void demo1 () {/ / there is no "ab" in the string pool beforehand. After intern (), s returns the object String s = new String ("a") + new String ("b"); String S1 = s.intern (); System.out.println (s = "ab") / / true System.out.println (S1 = = "ab"); / / true} static void demo2 () {/ / there is already "ab" in the string pool, and s still returns the object in the heap String x = "ab"; String s = new String ("a") + new String ("b"); / / heap new String ("a") new String ("b") new String ("ab") String S2 = s.intern () / / try to put this string object into the string pool. If there is one, it will not. If not, the string pool will return the object in the string pool to System.out.println (S2 = = x); / / true System.out.println (s = = x); / / false}}

Position

In the case of JDK1.6, StringTable is placed in metaspace, which belongs to the position of permanent generation, but it takes a long time to trigger full gc when StringTable occupies memory, and when JDK1.7 puts StringTable in heap memory, minor gc is triggered first with the increase of memory footprint, which takes less time.

Direct memory

Use the Native function to allocate out-of-heap memory directly, and then use the DirectByteBuffer object in the Java heap as a reference to this memory. Description of the principle:

Use the Unsafe object to allocate and reclaim direct memory, and the freeMemory method needs to be called actively when reclaiming.

Cleaner (virtual reference) is used inside the implementation class of ByteBuffer to monitor the ByteBuffer (BB) object. Once the BB object is garbage collected, the referenceHandler thread will free memory by calling freeMemory through the Cleaner method.

Create a new object description

The process of HotSpot virtual machine assigning, laying out, and accessing objects in the Java heap

Creation of object

New bytecode instruction

When the virtual opportunity comes to the new bytecode instruction, first check whether the symbol reference of a class can be located in the constant pool, and check whether the symbol reference has been loaded, parsed, and initialized. If not, the corresponding class loading process is performed. After the class load check, the virtual machine allocates memory to the new object

Memory allocation

The amount of memory required for an object can be determined during class loading. There are two ways to partition memory for objects in the Java virtual machine: pointer collisions, free list pointer collisions: using a pointer as an indicator of the demarcation point between used and unused memory, memory allocation is just pointer movement. The advantage is that it does not cause memory fragmentation, but it is slow.

Free list: the virtual machine maintains a memory usage record table, which, when used, directly allocates a large enough space from the free memory area to the object instance.

Thread safety issues in memory allocation

After dividing the available space, it is still necessary to consider the use of memory in the case of concurrency. There are two ways to solve the problem of memory conflict: CAS with failed retry, TLAB local thread allocation buffer TLAB: the memory allocation is divided into different spaces according to threads, that is, each thread pre-allocates a small piece of memory space in the Java heap.

Memory layout of the object

The layout of objects in heap memory can be divided into three parts: object header, instance data, and alignment padding.

Object head

The object header contains two types of information: Mark Word and type pointer

Mark Word

Storing the runtime data of the object itself, taking into account the space efficiency of the virtual machine, is designed as a dynamically defined data structure. that is, reuse your own storage space according to the state of the object (32 bits and 64 bits on 32-bit and 64-bit virtual machines, respectively).

Type pointer

Object to its type metadata, which is used by the Java virtual machine to determine which class the object is (not all virtual machines must keep type pointers on the object data). In addition, if the object is an array, the object header must also have a piece of data that records the length of the data

Instance data

That is, the various types of field content defined in the program code, including fields inherited from the parent class or defined in the subclass. The types of data are stored in a certain order (long/double, ints...), and fields of the same width are always assigned to be stored together, so variables defined in the parent class may appear before the subclass.

Align fill

Placeholder, no special meaning

The automatic memory management system of the HotSpot virtual machine requires that the starting address of the object must be an integral multiple of 8 bytes. If the object header and sample data memory design of some objects are not multiples of 8, they need to be filled with placeholders.

Access location of object

Java programs operate on specific objects through reference data. There are two main ways to access them: handle and direct pointer.

Handle

A block of memory may be allocated in the Java heap as a handle pool. The handle address of the object is stored in reference, and the handle contains the specific address information of the object's instance data and type data.

Direct pointer

The layout of objects in the Java heap needs to consider how to place information about the type data (such as access information). The address of the object is directly stored in the reference. If you only access the object itself, you don't need to spend one more indirect access.

Advantages and disadvantages

Using handle access, reference data only needs to be related to the handle address, and when the object is reclaimed or moved, you only need to change the instance data pointer in the handle. Reference itself does not need to modify the use of direct pointer, which saves the time overhead of pointer positioning and is faster. Because the access to objects in Java is quite frequent, the effect is considerable. HotSpot uses direct pointers

After reading the above, have you mastered how to parse the JVM memory structure partition instance? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report