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 understand the basic principles of HotSpot JVM

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article will explain in detail how to understand the basic principles of HotSpot JVM, 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 a certain understanding of the relevant knowledge after reading this article.

About JAVA

The Java ®programming language is a universal, concurrent, object-oriented language. Its syntax is similar to C and C++, but it omits many of the features that make C and C++ complex, chaotic, and unsafe.

Java is the foundation for almost all types of web applications and a global standard for developing and providing embedded and mobile applications, games, Web-based content, and enterprise software. .

From laptops to data centers, from game consoles to scientific supercomputers, from mobile phones to the Internet, Java is everywhere!

The technical system of Java is mainly composed of JVM virtual machine on various hardware platforms, Java API which provides interface support in various development fields, Java programming language, three-party Java framework (Spring, etc.).

The three parts of Java programming language, Java virtual machine and Java API class library are called JDK (Java Development Kit). JDK is the smallest environment used to support Java program development.

The Java SE API subset and the Java virtual machine in the Java API class library can be called JRE (Java Runtime Environment). JRE is a standard environment that supports the running of Java programs.

The following figure shows the content of the Java technology architecture, as well as the scope of JDK and JRE.

About JVM

Java virtual machine is the cornerstone of Java platform. Responsible for the independence of its hardware and operating system, and provide a runtime environment for the execution of Java bytecode.

The JVM virtual machine is not specified in the Java virtual machine specification, but is implemented by the major manufacturers themselves.

Implementation details that are not part of the Java Virtual Machine's specification would unnecessarily constrain the creativity of implementors. For example, the memory layout of run-time data areas, the garbage-collection algorithm used, and any internal optimization of the Java Virtual Machine instructions (for example, translating them into machine code) are left to the discretion of the implementor.

Classic VM is "the first commercial Java virtual machine in the world". Before JDK 1.2, it was the only virtual machine in Sun JDK.

In JDK 1.2, it coexisted with HotSpot VM, while in JDK 1.3, HotSpot VM became the default virtual machine, and it was not until JDK 1.4 that Classic VM completely retired from the history of commercial virtual machines.

On April 27th, 1999, HotSpot Virtual Machine was released. HotSpot was originally developed by a small company called Longview Technologies, which was acquired by Sun in 1997 because of HotSpot's excellent performance. It later became the default virtual machine for all versions of Sun JDK in JDK 1.3 and later.

In 2008 and 2009, Oracle acquired BEA and Sun respectively, so Oracle has two excellent Java virtual machines: JRockit VM and HotSpot VM.

About HostSpot

The Java HotSpot virtual machine is Sun's VM for the Java platform. It uses many advanced technologies to provide the best performance for Java applications, including the state-of-the-art memory model, garbage collector and adaptive optimizer.

Include two styles of VM in SUN/Orace JDK

Client mode

Server mode

Start with client mode by default.

Start the command with-server and start with server mode.

View the current JVM mode:

The difference between the two mode:

Client mode

Start in a short time and use less memory at run time

C1 lightweight compiler with less optimization

Suitable for lightweight and desktop programs

Server mode

Slow startup, more memory consumption at run time

C2 heavyweight compiler for more thorough optimization

Can provide better performance and is suitable for production deployment

HotSpot JVM Architecture

HotSpot JVM mainly consists of three components:

Class Loader Subsystem

Runtime Data Areas

Execution Engine

Class Loader Subsystem

Class Loader Subsystem is an essential core of JVM for reading / loading .class files and saving bytecode in the JVM method area.

Loading process

The whole process of class loading in the Java virtual machine: loading, verification, preparation, parsing, initialization.

Loading

In the Loading phase, the virtual machine does three things:

Get the binary byte stream that defines this class through the fully qualified name of a class

Convert the static storage structure represented by this byte stream to the run-time data structure of the method area

A java.lang.class object representing this class is generated in memory as an access entry for various data of this class in the method area.

The first step of loading is implemented outside the Java virtual machine, and there is a 'classloader' to complete the loading action.

Most Java programs use the class loaders provided by the following three systems:

Start the classloader (Bootstrap ClassLoader)

Implemented in C++ language, it is a part of the virtual machine itself.

Load the jar recognized by the virtual machine in / lib, such as rt.jar.

Cannot be directly referenced by Java programs

Extended class loader (Extension ClassLoader)

Implemented by sun.misc.Launcher$ExtClassLoader

Load class libraries in / lib/ext

The Java program can be used directly

Application class loader (Application ClassLoader)

Implemented by sun.misc.Launcher$AppClassLoader

Also known as the system class loader, loading the jar under the application classpath

Can be used directly, the default class loader in the program

Linking

Performs a link to a class or interface.

Verification, verify. Ensure that the information contained in the byte stream of the Class file meets the requirements of the current virtual machine and does not compromise the security of the virtual machine.

Preparation, stand by. Allocate memory and set initial values for class variables (variables decorated by static) in the method area.

Resolution, parsing. The virtual machine replaces the symbolic reference of the constant pool with a direct reference.

Initialization

In the final phase of class loading, all static variables are assigned original values, and the static block executes from the parent class to the child class.

Loading principle

Delegation, delegate

Visibility, visibility

Uniqueness, uniqueness

Delegation

Parental delegation model

The parent delegation model was introduced in JDK1.2, requiring all classloaders to have parent class loaders except to start the classloader.

Loading process: when a class loader receives a load request, it is first delegated to the parent class loader to complete, each level of the class loader is the same, and finally the load request is passed to the top-level startup class loader. If the parent class cannot complete the load request, the subclass will try to load.

Destroy the parental delegation model

Parental delegation solves the problem of unifying the basic classes of all kinds of loaders.

What if the underlying class needs to reverse the user code?

The thread asks the class loader (Thread Context ClassLoader), TCCL. Resolve the basic class to reverse the user code. For example, JDBC, JNDI and so on that implement SPI mechanism in JDK.

Visibility

The subclass loader can see the classes loaded by the parent class loader. The parent class loader does not see the classes in the child class loader.

Uniqueness

Classes loaded by the parent class loader are not loaded by the child class loader.

Runtime Data Areas

Runtime Data Areas can be roughly divided into two parts:

Thread private area, which allocates memory when the thread is created. Initialize the thread when it starts and destroy it after the thread finishes

The thread shared area, which is accessible to all threads. JVM is initialized when it starts and destroyed when it is closed.

Program counter

Saves the address of the currently executing JVM instruction. Each thread has its own PC.

Java virtual machine stack

Each Java virtual machine thread has a private Java virtual machine stack created at the same time as the thread.

Local method stack

A stack for native methods implemented in a non-Java language. In other words, it is used to call the Cmax Candle + code called through the JNI (Java Native Interface Java native interface). Depending on the language, a C stack or C++ stack will be created.

Java reactor

The space used to hold the instance or object, and it is the main target of garbage collection. It is often mentioned when discussing issues such as JVM performance. The JVM provider can decide how to configure the heap space and not garbage collect it.

Method area

The method area is shared by all threads and is created when JVM starts. It holds the runtime constant pool, member variables and method information, static variables and method bytecode for all classes and interfaces loaded by JVM. The provider of JVM can implement the method zone in different ways. In Oracle's HotSpot JVM, the method zone is called permanent zone or permanent generation (PermGen). Whether or not to garbage collect the method area is optional for the implementation of JVM.

After JDK1.8, the PermGen is permanently removed, and there is a Metaspace (metaspace) to implement the method area.

The biggest difference between the permanent generation and the permanent generation is that the metaspace is not in the virtual machine, but uses local memory.

Therefore, by default, the size of metaspace is limited by local memory only.

Running constant pool

This area corresponds to the constant_pool in the class file. This area is contained in the method area, but it is a core role for JVM operations. Therefore, its importance is specifically mentioned in the JVM specification. In addition to containing constants for each class and interface, it also contains references to all methods and variables. In short, when a method or variable is referenced, JVM runs the constant area to find the actual address of the method or variable in memory.

Execution Engine

Interpreter

Bytecode instructions are read and executed sequentially.

JIT

JIT (Just In Time) Compiler.

It counteracts the disadvantage of slow execution speed of Interpreter and improves the performance. The JIT compiler compiles similar parts of the bytecode at the same time, reducing the total time required for compilation.

Garbage Collection

Free memory by collecting and deleting unreferenced objects.

Whether the object survives

Almost all the object instances of the Java world are stored in the heap, and the first thing the garbage collector does before collecting the heap is to determine whether the object is alive or not.

Citation counting algorithm

The reference counting algorithm (Reference Counting) is simple to implement and efficient to determine. Add a reference counter to the object, which increases the counter value by 1 whenever a place references it; when the reference expires, the counter value is subtracted by 1; an object with a counter of 0 can no longer be used.

Python language and Squire, which is widely used in the field of game scripts, use reference counting algorithm for memory management. However, it is not useful in the java virtual machine, mainly because it is difficult to solve the problem of circular references between objects.

Accessibility analysis

The basic idea of reachability analysis (Reachability Analysis) is to search down from these nodes through a series of objects called "GC Roots". The distance of the search is called reference chain (Reference Chain). When an object is not connected to GC Roots with any reference chain, it is proved that the object is not available.

In the Java language, objects that can be used as GC Roots include the following:

Objects referenced in the virtual machine stack (the local variable table in the stack frame)

Objects referenced by class static properties in the method area

Objects referenced by constants in the method area

Objects referenced by JNI (Native methods) in the local method stack

Garbage collection algorithm

Common garbage collection algorithms.

Mark-clear algorithm

The algorithm is divided into two stages: 'marking' and 'clearing'.

First of all, all the objects that need to be recycled are marked, and all the marked objects are recycled uniformly after the marking is completed.

Replication algorithm

Copying, dividing the available memory into two equal-sized chunks, using only one of them at a time. When this piece of memory is used up, copy the surviving objects to another block. Clean up the used memory space at once.

The utility model has the advantages of simple implementation, efficient operation and low memory utilization, which is used to recycle the new generation.

IBM research shows that 98% of objects in the new generation are recycled at the first GC, and there is no need to allocate space according to 1:1.

The default Eden-to-Survivor ratio for HotSpot virtual machines is 8:1, and only 10 per cent of memory is wasted.

When there is not enough Survivor space, we need to rely on the old age for distribution guarantee, and the survival objects collected by the new generation directly enter the old age.

Marking-finishing algorithm

The tag-collation (Mark-Compact) algorithm marks all living objects, moves to one end, and then directly cleans up the unexpected memory at the end boundary.

Generation collection algorithm

According to the different survival period of the object, the Java heap is divided into Cenozoic era and old age.

In the new generation, replication algorithm is adopted.

In the old days, the 'mark-clean' or 'mark-organize' algorithm was used.

Garbage collector

If the collection algorithm is the methodology of memory collection, then the garbage collector is the concrete embodiment of memory collection.

The Java virtual machine specification does not specify how to implement the garbage collector. Different vendors and versions of virtual machine implementations may vary greatly.

Next, discuss the collector based on the HotSpot virtual machine after JDK1.7 Update14.

Serial collector

"Serial" is a stop-the-world, copying collector which uses a single GC thread.

ParNew collector

"ParNew" is a stop-the-world, copying collector which uses multiple GC threads.

Parallel Scavenge collector

"Parallel Scavenge" is a stop-the-world, copying collector which uses multiple GC threads.

Serial Old collector

"Serial Old" is a stop-the-world, mark-sweep-compact collector that uses a single GC thread.

Parallel Old collector

"Parallel Old" is a compacting collector that uses multiple GC threads. Using the-XX flags for our collectors for jdk6.

CMS collector

"CMS" (Concurrent Mark Sweep) is a mostly concurrent, low-pause collector.

G1 collector

G1 (Garbage First) straddles the young generation-tenured generation boundary because it is a generational collector only in the logical sense. G1 divides the heap into regions and during a GC can collect a subset of the regions.

JMM

Java memory model (Java Memory Model), JMM, is used to shield memory access differences between various hardware and operating systems, in order to achieve consistent memory access results on various platforms.

The main goal of JMM is to define the access rules for each variable in the program. That is, the variables are stored in and fetched from memory in the virtual machine.

All variables are stored in main memory (Main Memory), and each thread has its own working memory (Working Memory).

Thread's operations such as reading and assigning values to variables must be carried out in working memory.

The transfer of variable values between threads must be done through main memory.

On how to understand the basic principles of HotSpot JVM to share here, I hope that 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

Internet Technology

Wechat

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

12
Report