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

What is Person in java

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

Share

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

This article will explain in detail what the Person in java is, and the content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

Method area

This time it's about the last part of the runtime data area.

From the point of view of thread sharing or not

ThreadLocal: how to ensure the security of multiple threads in a concurrent environment? Typical applications are database connection management and session management

The interaction of one stack, heap and method area

The following involves the access positioning of objects

Person: stored in metaspace, or method area

Person: stored in the local variable table of the Java stack

New Person (): stored in the Java heap

The understanding of the second method area

The Java virtual machine specification makes it clear that "although all method zones are logically part of the heap, some simple implementations may not choose to garbage collect or compress." But for HotSpotJVM, the method zone also has an alias called Non-Heap (non-heap), which is intended to be separated from the heap.

Therefore, the method area is treated as a piece of memory space independent of the Java heap.

The method area mainly stores Class, while the heap mainly stores instantiated objects.

The method Method Area, like the Java heap, is an area of memory shared by each thread.

The method area is created when the JVM starts, and its actual physical memory space can be as discontiguous as the Java heap area.

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

The size of the method area determines how many classes the system can save. If the system defines too many classes, causing the method area to overflow, the virtual machine will also throw a memory overflow error: ava.lang.OutofMemoryError:PermGen space or java.lang.OutOfMemoryError:Metaspace

Load a large number of third-party jar packages

Too many projects deployed in Tomcat (30,50)

A large number of dynamically generated reflection classes

Turning off JVM frees up memory in this area.

The Evolution of Chinese legal District in HotSpot

In jdk7 and before, it is customary to refer to the method area as the permanent generation. Starting with jdk8, metaspace is used instead of permanent generation.

After JDK 1.8, metaspace is stored in out-of-heap memory.

In essence, the method zone and the permanent generation are not equivalent. Only for hotspot. The Java virtual machine specification does not make a unified requirement on how to implement the method area. For example, the concept of permanent generation does not exist in BEAJRockit / IBM J9.

Now, it is not a good idea to use Eternal at that time. Causes Java programs to oom more easily (exceeds the-XX:MaxPermsize upper limit)

When it comes to JDK8, we finally completely abandon the concept of permanent generation and replace it with Metaspace, which is implemented in local memory like JRockit and J9.

The essence of meta-space is similar to that of permanent generation, which is the realization of the legal area in the JVM specification. However, the biggest difference between metaspace and permanent generation is that metaspace is not in the memory set by the virtual machine, but uses local memory.

Permanent generation and metaspace not only have their names changed, but their internal structures have also been adjusted.

According to the Java virtual machine specification, if the method area fails to meet the new memory allocation requirements, an OOM exception will be thrown

3. Setting method area size and OOM

The size of the method area does not have to be fixed, and the JVM can be adjusted dynamically according to the needs of the application.

JKD7 and before

The initial allocation space of the permanent generation is set through-xx:Permsize. The default value is 20.75m

-XX:MaxPermsize to set the maximum allocable space of the permanent generation. The default for a 32-bit machine is 64m, and the 64-bit machine mode is 82m.

When the class information capacity loaded by JVM exceeds this value, an exception OutofMemoryError:PermGen space will be reported.

After JDK8

The size of the metadata area can be specified using the parameters-XX:MetaspaceSize and-XX:MaxMetaspaceSize

The default value depends on the platform. Under windows,-XX:MetaspaceSize is 21m, and the value of MaxMetaspaceSize is-1, that is, there is no limit.

Unlike permanent generations, if you do not specify a size, by default, the virtual machine consumes all available system memory. If the metadata area overflows, the virtual machine will also throw an exception OutOfMemoryError:Metaspace

-XX:MetaspaceSize: sets the initial metaspace size. For a 64-bit server-side JVM, the default-xx: metaspaceSize value is 21MB. This is the initial high water mark, and once it is touched, the Full GC will be triggered and unloaded with useless classes (that is, their corresponding class loaders will no longer survive) and the high water mark will be reset. The value of the new high watermark depends on how much meta-space is freed after the GC. If there is not enough free space, increase the value appropriately when the MaxMetaspaceSize is not exceeded. If you free up too much space, lower the value appropriately.

If the initialized high water mark is set too low, the above high water mark adjustment will occur many times. Multiple calls to FullGC can be observed from the garbage collector's log. To avoid frequent GC, it is recommended that you set-XX:MetaspaceSize to a relatively high value.

How to solve these OOM

To solve the OOM exception or heap space exception, the general method is to first analyze the heap dump snapshot from dump through a memory image analysis tool (such as Eclipse Memory Analyzer). The key point is to confirm whether the objects in memory are necessary, that is, to distinguish whether there is a memory leak (Memory Leak) or a memory overflow (Memory Overflow).

A memory leak means that there are a large number of references to certain objects, but these objects will not be used in the future, but because they are also associated with GC ROOT, these objects will not be recycled in the future. This is the problem of memory leaks.

If it is a memory leak, you can further check the reference chain from the leaked object to GC Roots through the tool. You can then find out how the leaked objects are associated with the GCRoots and cause the garbage collector to fail to collect them automatically. By mastering the type information of the leaked object and the information of the GCRoots reference chain, we can accurately locate the location of the leaked code.

If there is no memory leak, in other words, all objects in memory really must still be alive, then you should check the heap parameters of the virtual machine (- Xmx and-Xms) to see if they can be scaled up compared with the machine's physical memory, check code to see if there are cases where the life cycle of some objects is too long and hold the state for too long, and try to reduce memory consumption during the run time of the program.

The internal structure of the four method areas

The book "in-depth understanding of the Java virtual machine" describes the Method Area storage content as follows: it is used to store type information that has been loaded by the virtual machine, constants, static variables, just-in-time compiler compiled code cache, and so on.

Type information

For each loaded type (class class, interface interface, enumeration enum, annotation annotation), JVM must store the following type information in the method area:

The full valid name of this type (full name = package name. Class name)

The full valid name of the parent class directly for this type (for either interface or java.lang.object, there is no parent class)

Modifiers of this type (a subset of public,abstract,final)

An ordered list of direct interfaces of this type

Domain (Field) information

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

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

Method (Method) information

JVM must save the following information for all methods, including the declaration order like domain information:

Method name

Return type (or void) of the method

Number and type of method parameters (in order)

Method modifier (a subset of public,private,protected,static,final,synchronized,native,abstract)

Bytecode (bytecodes), Operand stack, local variable table and size of the method (except for abstract and native methods)

Exception table (except for abstract and native methods)

The start and end position of each exception handling, the offset address of the code handling in the program counter, and the constant pool index of the caught exception class

Class variables of non-final

Static variables are associated with a class and are loaded as the class is loaded, and they become a logical part of the class data.

The class variable is shared by all instances of the class, and you can access it even when there is no instance of the class

/ * * non-final class variable * * / public class MethodAreaTest {public static void main (String [] args) {Order order = new Order (); order.hello (); System.out.println (order.count);}} class Order {public static int count = 1; public static final int number = 2; public static void hello () {System.out.println ("hello!");}}

As shown in the above code, even if we set order to null, there will be no null pointer exception

Global constants are modified with static final at the same time

Class variables declared as final are handled differently, and each global constant is assigned at compile time.

Running constant pool VS constant pool

Method area, which contains a pool of running constants

Bytecode file, which contains a constant pool

To figure out the method area, you need to understand C1assFile, because the information about the loaded class is in the method area.

To figure out the runtime constant pool in the method area, you need to understand the constant pool in classFile.

Constant pool

In addition to class version information, fields, methods, and interfaces, a valid bytecode file contains information such as constant pool tables (Constant Pool Table), including various literals and symbolic references to types, fields, and methods.

Why do I need a constant pool?

Classes and interfaces in a java source file are compiled to produce a bytecode file. The bytecode in Java requires data support, which is usually too large to be stored directly in the bytecode. On the other hand, it can be saved in the constant pool, which contains a reference to the constant pool. The runtime constant pool is used for dynamic linking, as described earlier.

For example: the following code:

Public class SimpleClass {public void sayHello () {System.out.println ("hello");}}

Although the above code is only 194 bytes, it uses structures such as String, System, PrintStream and Object. The amount of code here is actually very small, if there is more code, there will be more referenced structures, so constant pools are needed here.

What's in the constant pool?

Quantity value

String valu

Class reference

Field reference

Method reference

For example, the following code

Public class MethodAreaTest2 {public static void main (String args []) {Object obj = new Object ();}}

Will be translated into the following bytecode

New # 2 dupinvokespecial Summary

Constant pool can be regarded as a table, according to which the virtual machine instruction finds the class name, method name, parameter type, literal quantity and other types to be executed.

Running constant pool

The runtime constant pool (Runtime Constant Pool) is part of the method area.

The constant pool table (Constant Pool Table) is a part of the Class file that stores various literals and symbolic references generated during compilation. This part of the content will be stored in the runtime pool in the method area after the class is loaded.

The runtime constant pool is created after the classes and interfaces are loaded into the virtual machine.

JVM maintains a constant pool for each loaded type (class or interface). Data items in a pool, like array items, are accessed by index.

The runtime constant pool contains a variety of constants, including numeric literals that are clear at compile time, and methods or field references that are not available until run-time parsing. At this point, it is no longer the symbolic address in the constant pool, but the real address.

Another important feature of the runtime constant pool compared to the Class file constant pool is that it is dynamic.

The runtime constant pool is similar to the symbol table (symboltable) in traditional programming languages, but it contains more data than the symbol table.

When creating a runtime constant pool for a class or interface, JVM throws an outofMemoryError exception if the memory required to construct the runtime constant pool exceeds the maximum value that can be provided by the method area.

Examples of the use of the five method areas

The code is as follows

Public class MethodAreaDemo {public static void main (String args []) {int x = 500; int y = 100; int a = x / y; int b = 50; System.out.println (aqb);}}

Bytecode execution process display

First of all, put the Operand 500 into the Operand stack

And then stored in the local variable table.

Then repeat, put 100 into the local variable scale, and then take out 500 and 100 from the variable scale to operate.

Perform a division operation between 500 and 100, putting the result on the stack

At the end is the output stream, which needs to call the constant of the run time pool

Finally, call invokevirtual (virtual method call) and return

On return

The program counter always calculates the location where the current code is running, in order to facilitate the normal return after recording the method call, or to return to the original code for execution after the CPU switch.

Details of the evolution of the six method areas

First of all, it is clear that only Hotspot has an eternal generation. For BEA JRockit, IBMJ9 and so on, there is no concept of permanent generation. In principle, how to implement the method area belongs to the details of virtual machine implementation, is not subject to the "Java virtual machine specification", and does not require unification.

Changes in the legal area of China in Hotspot:

JDK1.6 and before there is a permanent generation, static variables stored in the permanent generation JDK1.7 has a permanent generation, but has gradually "gone to the permanent generation", string constant pool, static variables removed, stored in the heap JDK1.8 and after no permanent generation, type information, fields, methods, constants are stored in the local memory metaspace, but string constant pools, static variables are still in the heap.

When JDK6

When JDK7

In JDK8, the meta-space size is only affected by physical memory

Why should permanent generation be replaced by metaspace?

JRockit is the result of integration with HotSpot, because JRockit does not have permanent generation, so they do not need to configure permanent generation.

With the advent of Java8, there is no more permanent generation in HotSpot VM. But this does not mean that the metadata information for the class also disappears. This data is moved to a local memory area that is not connected to the heap, which is called Metaspace.

Because the metadata of the class is allocated in local memory, the maximum available memory space for metaspace is the available memory space of the system, which is necessary for the following reasons:

1) it is difficult to determine the size of the space for permanent generations.

In some scenarios, if there are too many classes loaded dynamically, it is easy to generate oom in the Perm area. For example, in an actual Web process, because there are many function points, many classes are loaded dynamically in the process of running, and fatal errors often occur.

"Exception in thread'dubbo client x.x connector'java.lang.OutOfMemoryError:PermGen space"

The biggest difference between metaspace and permanent generation is that metaspace is not in the virtual machine, but uses local memory. Therefore, by default, the size of metaspace is limited only by local memory.

2) it is difficult to tune the permanent generation.

Mainly to reduce Full GC

Some people think that the method zone (such as metaspace or permanent generation in the HotSpot virtual machine) has no garbage collection behavior, but it is not. The constraints of the Java virtual machine specification on the other side of the law zone are very relaxed, and it is mentioned that the virtual machine can not be required to implement garbage collection in the method zone. In fact, there are collectors that do not implement or fully implement method zone type unloading (for example, ZGC collectors in the JDK11 era do not support class unloading). Generally speaking, the recovery effect of this area is difficult to be satisfactory, especially the type of unloading, the conditions are very harsh. But recycling in this area is sometimes necessary. In the past, several serious Bug in sun's Bug list were caused by memory leaks due to the incomplete recycling of this area by low-version HotSpot virtual machines.

The garbage collection in the method area mainly contains two parts: abandoned constants in the constant pool and types that are not in use.

Why does StringTable need to reposition?

StringTable is placed in the heap space in JDK7. Because the recycling efficiency of permanent generation is very low, it will only be triggered when full gc. On the other hand, FULL GC is triggered only when there is a shortage of space and permanent generation in the old days.

This leads to the inefficiency of StringTable recovery. In our development, a large number of strings will be created, and the recycling efficiency is low, resulting in a shortage of permanent memory. If you put it in the heap, you can reclaim the memory in time.

Where are the static variables stored?

There is always heap space for the object entity corresponding to the static reference

You can use jhsdb.exe, which needs to be introduced in jdk9.

Staticobj is stored in the method area with the type information of Test, instanceobj is stored in the Java heap with the object instance of Test, and localobject is stored in the local variable table of the foo () method stack frame.

The test found that the address of the data of the three objects in memory is within the range of the Eden area, so the conclusion: as long as it is an object instance, it is bound to be allocated in the Java heap.

Then, a place that references the staticobj object is found in an instance of java.lang.Class, and the address of the instance is given. Looking at the object instance through Inspector, you can clearly see that this is indeed an object instance of type java.lang.Class, and there is an instance field named staticobj:

From the conceptual model defined by the Java virtual machine specification, all Class related information should be stored in the method area, but how to implement the method area is not stipulated in the Java virtual machine specification, which has become a thing that allows different virtual machines to grasp flexibly. JDK7 and later versions of HotSpot virtual machines choose to store static variables with mapped class objects of type on the side of the Java language and store them in the Java heap, which is clearly verified by our experiments

Garbage collection in six-method area

Some people think that the method zone (such as metaspace or permanent generation in the Hotspot virtual machine) has no garbage collection behavior, but it is not. The constraints of the Java virtual machine specification on the other side of the law zone are very relaxed, and it is mentioned that the virtual machine can not be required to implement garbage collection in the method zone. In fact, there are collectors that do not implement or fully implement method zone type unloading (for example, zGC collectors in the JDK11 era do not support class unloading).

Generally speaking, the recovery effect of this area is difficult to be satisfactory, especially the type of unloading, the conditions are very harsh. But recycling in this area is sometimes necessary. In the past, several serious Bug in sun's Bug list were caused by memory leaks due to the incomplete recycling of this area by low-version HotSpot virtual machines.

There are two main parts of garbage collection in the method area: abandoned constants in the constant pool and types that are no longer used.

First, let's talk about the two main types of constants stored in the constant pool in the method area: literals and symbolic references. Literals are close to constant concepts at the Java language level, such as text strings, constant values declared as final, and so on. On the other hand, symbolic reference belongs to the concept of compilation principle, including the following three types of constants:

Fully qualified names of classes and interfaces

The name and descriptor of the field

The name and descriptor of the method

The HotSpot virtual machine's recycling policy for constant pools is clear, as long as the constants in the constant pool are not referenced anywhere, they can be recycled.

Recycling obsolete constants is very similar to recycling objects in the Java heap. (the recovery of constants is relatively simple, with emphasis on the recovery of classes.)

It is relatively simple to determine whether a constant is "obsolete" or relatively simple, but it is more demanding to determine whether a type belongs to a "class that is no longer used". The following three conditions need to be met at the same time:

All instances of the class have been recycled, that is, there are no instances of the class and any derived subclasses in the Java heap.

The classloader that loads the class has been recycled, and this condition is usually difficult to achieve unless it is a well-designed alternative classloader scenario, such as OSGi, JSP reloading, and so on.

The corresponding java.lang.C1ass object of this class is not referenced anywhere, and its methods cannot be accessed anywhere through reflection. I

The Java virtual machine is allowed to recycle useless classes that meet the above three conditions, which only means "allowed", not like objects, which are bound to be recycled without references. The HotSpot virtual machine provides the-Xnoclassgc parameter to control whether to recycle types, and you can use-verbose:class and-XX:+TraceClass-Loading,-XX:+TraceClassUnLoading to view class loading and unloading information.

In scenarios where bytecode frameworks such as reflection, dynamic proxy and CGLib are widely used to dynamically generate frequent custom class loaders such as JSP and oSGi, the Java virtual machine is usually required to have the ability to unload types to ensure that it does not cause excessive memory pressure on the method area.

Summary

About what Person in java is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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