A: the preface

  • Interviewer: Well, tell me about your knowledge of JVM, JRE and JDK.

  • I: (think in the mind) small sample, this problem, want to stumped senior CURD engineer, fortunately I have prepared. The JVM stands for JAVA Virtual machine. It can be used to load JAVA bytecode files. It can be regarded as an execution environment for JAVA.

  • Interviewer: Is that all?

  • I: a listen to the interview officer this tone, in the mind straight fire, money is a trifle, face can’t lose, dare to look down on a years of experience of CURD engineer, this interview not to give you back, just want to continue to answer!

  • Interviewer: put a hand, have spirit weak way, ok, today first so, the back of the news of the human resources will inform you.

  • I: a listen to the interviewer this tone, I was more angry, then said, thirty years east, thirty years west, mo bully young poor! Then he stood up and started to walk out of the interview room.

  • Interviewer: a face smoke, laugh at say, you think you are Xiao Yan? I TM or xiao station!

  • I: I listen to him this answer, this tone! Clearly is to take advantage of me, ah, the primordial power of the body can not be directly controlled, brandished the desktop of the water bottle to the interviewer face to greet the past!

  • I: is I hit is cool, is the interviewer again and again to me for mercy of the time, a foot, I suddenly woke up, found himself lying in bed, time is 2 o ‘clock in the morning. It was a dream! Had known to hit a bit harder, MY heart secretly said!

  • Me: at the moment I have no sleep, recall in the dream to see the face of the interviewer, I secretly swear in my heart, I absolutely do not allow the dream scene in reality, before the interviewer installed B, I will be installed before he!

  • I:Got up from bed, opened the computer, in the interface input: JVM, JRE, JDK what difference!

Two: What is JVM

That next I will focus on chat, hope to give you use for reference! If you like it, don’t forget to give it a thumbs up! Code word is not easy to

Poke me at GitHub home page to learn more tips on optimization

What is the JVM

(a) : the JVM

Before we get to know what a JVM is, let’s think about what we need if we want to use an application on a computer.

First, we need to have an environment (the computer is), and second, we need to install the application on the computer, and then we can use the application to do what we want to do.

Similarly, the JVM stands for Java Virtul Machine(Java Virtual Machine). It is a specification for a computing device. It can be understood as a fictional computer, which contains components similar to real computers and is used to simulate various functions of computers and then run on real computers

(2) Why JAVA is called “platform independent programming language”

Because it contains a JAVA virtual machine (JVM), the JVM know instruction length and other relevant properties of the underlying hardware platform, it blocked and specific information on the platform, the JAVA language development program only need a compiler to generate object code to be able to run on the JVM (bytecode file), which can run on different platforms and sometimes don’t need Recompile

(iii): Internal structure of JVM

Note: The JDK we usually use is provided by the Sun JDK and OpenJDK, and this is the most widely used version. This version of the VIRTUAL machine is Hotspot(Hotspot data), so by default, the JAVA virtual machine we are talking about is Hotspot.

The interior of the JVM can be divided into three parts: the classloader, the execution engine, and the runtime data area.

Class Loader (Class Loader)

It is mainly used to load class bytecode files (class files) from disk to memory, and then perform data verification, conversion and parsing, initialization and other operations on class files, and finally convert them into class objects that can be directly used by virtual machines.

Execution Engine

One of the most core components in the JVM is used to execute instructions, interpret or compile bytecode files loaded into the JVM into local machine instructions on the corresponding platform, and in short, act as an intermediary for translating high-level languages into machine languages

The execution engine may execute JAVA code in interpreted execution (interpreter execution), compiled execution (even if the compiler produces native code execution), or both.

Three: What is an Interpreter and what is a JIT compiler?

(I) Interpreter:

Executed in a manner that is responsible for line-by-line interpretation of bytecode loaded into the JVM according to predefined specifications, each bytecode is translated into the local machine instructions of the corresponding platform for execution, and compiled for each invocation.

(2) JIT(Just In Time Compiler) It is a way to improve the efficiency of the program by compiling the source code in the virtual machine directly into the machine language relevant to the local machine platform, and then saving the machine code of the hot code for later execution.

Hotspot virtual machine (hot) the origin of the name, when the virtual machine found a method or blocks of code to run frequently, will identify the code as code “hot spots”, in order to improve the execution efficiency of hot code, at run time, the virtual opportunities associated with local platform to compile the code into machine code, and optimization of various levels The next call simply executes the machine code, which is what the JIT compiler is designed to do.

(III) Features:

1. The interpreter execution steps can be abstracted as:

Bytecode file -> interpreter to interpret execution -> get execution results

2. JIT can be abstractly understood as:

Bytecode file -> compiler compiles -> executes the compiled code -> gets the execution result

The JIT is faster than the interpreter. It does not mean that “compiled” is faster than “interpreted”, but rather that “executed compiled code” is faster than “interpreted”.

For code that executes only once (called only once with no loops), such as a class constructor, using the interpreter is faster than JIT compilation, and only hot code that executes frequently is more efficient with the JIT

Four: Heap (Heap)

Thread sharing, created when the JVM is started, occupies the largest area of THE JVM memory. It is mainly used to store objects. Because it is shared by threads, data stored in this area may have thread safety problems.

1. Division of the internal structure of the heap

The size ratio of Young and Old is 1:2. The Cenozoic era is divided into three regions: Eden region, From Survivor region and To Survivor region. Their size ratio is 8:1:1, and the specific model is as follows:

2. Why divide the heap into this structure

The goal of generational the heap is to improve memory utilization and garbage collection efficiency. Because the heap is an area of the JVM maximum space, all the object instance is this place, at the same time, it is also the most frequent garbage collection area, if not a generational management about it and the newly created object and a long life cycle and unified management, when a program need for recycling, recycling every time to make a judgment for all objects, the judgment Very time consuming and can seriously affect the efficiency of the GC

A generational management mechanism, the newly created object is new generation, after a lot of recovery is still live objects into the old s (default is 15 times), because the object of the new generation is a “ephemerality”, the life cycle is shorter, so the need for frequent GC, and the old s life cycle long, the frequency of the recycling will be lower than the new generation, thus avoiding the recovery at a time “, but also to determine the state of all objects, improve the efficiency of GC.

A very simple example, as we participate in the activities of the normal life of the young and the old, the elderly more loyal to the square dance, a supermarket discounts, young people more loyal to the new science and technology, games, activities, to participate in an activity, is according to different user groups, you can’t have a square dance this activity has also been held young people to take part in it In the same way, you can’t think of old people playing games all day. Generational management can be different for different situations.

3. Young Generation

The newly generated objects are preferentially stored in the new generation, and the objects in the new generation have the characteristics of “life and death”, and the survival rate is very low. Therefore, in the new generation, each GC recovery can recover a large space and high recovery efficiency.

As you can see in the heap diagram above, the Hotspot VIRTUAL machine divides the new generation into three parts: one Eden region occupying the largest space and two Survisor regions occupying the smaller space. The default ratio is 8:1:1.

Could be divided into three areas because the purpose of new generation is used in the Hotspot of garbage object replication algorithm to recycle Cenozoic (specific algorithm of garbage will be explained in the next, interested can continuous attention), use the default rate can be more adequate use of memory space, reduce waste, so the size proportion generally don’t change.

Features: By default, newly created objects are allocated in Eden (except for large objects, which are stored directly in the old age region). If Eden does not have enough space for objects, the JVM triggers a Minor GC to reclaim garbage objects and free space.

4. New generation GC recycling process:

First, before GC, the To Survivor region in the new generation is empty (used To preserve surviving objects), and only the Eden region and From Survivor region exist for objects.

At the start of the GC, the JVM copies all the surviving objects in the GC into the To Survivor zone. Objects in the From Survivor zone go where they want To go depending on the age of survivability, if the age reaches Hotspot The JVM defaults To 15, and the age of the object is increased by 1 for each round of garbage collection that survives, and this value is stored in the object header.) The object is placed in the old age, and if the age threshold is not reached, the object is copied To Survivor.

After the replication, the GC thread empties the Eden and From Survivor zones, and all surviving objects are stored in the To Survivor zone. Next, the From Survivor and To Survivor zones swap Pointers, with To Survivor pointing To the From Survivor zone and From Survivor pointing To the To Survivor zone. After a round of GC,To Survivor is empty and serves only as an intermediary in the GC. If a To Survivor control cannot hold all the surviving objects of the new generation in a single GC, an allocation guarantee is required To store the object in the old generation.

5. The Old Generation

Objects stored in the old age have the following situations:

1. Objects that have gone through multiple GCS in the new generation and have reached a threshold in the JVM (Hotspot defaults to 15) that are still alive

2, the big object refers to both need larger continuous control of JAVA objects, such as a long array object and a string object, concrete can be specified by the JVM – XX: PretenureSizeThreshold parameters to set the size of large object, the unit is byte (byte)

3. If the size of the surviving objects exceeds the size of the To Survivor zone after the Minor GC, the remaining objects are guaranteed To be placed into the old age.

4. If the total size of objects of a certain age in the Survivor zone exceeds 50% of the size of the Survivor zone, all objects greater than or equal to this age will be transferred to the old age.

5. Before each Minor GC, the JVM checks whether the current amount of space left in the old generation is greater than the total size of all objects in the young generation. Minor GC is performed as long as the contiguous space of the old generation is larger than the total size of the young generation object or less than the average age of each successive promotion to the old generation object; otherwise, Full GC is performed.

6. Heap garbage recycling method

1. Minor GC(YGC): It is mainly used for garbage collection of the new generation. It uses a replication algorithm.

2, Major GC (YGC) : It is mainly used for garbage collection of older objects. Older objects have long life cycles, so they don’t die easily. Major GC is not as frequent as Minor GC, and a Full GC is more common than Minor GC GC takes more time and is more expensive, and there is usually one Major GC and usually (but not always) one Minor GC.

3, Full GC () : Full GC is global-scoped GC for the entire new generation, old generation, metaspace (java8 + replaced Perm Gen), but it is not equal to Major + Minor GC, depending on what combination of garbage collectors is used. A Full GC takes more time and consumes more energy, so try to minimize the number of Full GC.

The Minor GC uses the replication algorithm and requires an empty memory space, so it is inefficient, but it does not cause space fragmentation problems. However, Full GC generally adopts mark-clear algorithm, which is easy to generate space debris. If there are any more objects that need to request continuous space but cannot provide it, garbage collection will be triggered in advance. Therefore, it is suitable for the scenario with many living objects, namely garbage collection in the old days.

7. Heap garbage recovery algorithm

Because garbage collection algorithm more details, so special use of an article to explain, interested can continue to pay attention to!

5. Method Area

An area of memory that is shared by threads. It is mainly used to store class-loaded bytecode files, metadata such as class, method, field, static constants, variables, and machine instructions compiled by the JIT compiler. In addition, it also includes “runtime constant pool”.

1. Implementation of Method Area

A method area is a specification that can be understood as an interface in the JAVA language. It can be implemented in different ways. Common implementations include persistent generation and meta-space

Permanent Generation: before JDK1.7, this is the method area implementation, but the concept of Permanent Generation is only available in Hotspot VMS, other virtual machines such as J9 and JRockit virtual machines do not.

Dimension (MetaSpace) : Hotspot virtual machine (that is, the Oracle of the virtual machine) we use in JDK1.8 version removed the permanent generation, replaces it using dimension, yuan is system memory space occupied, another way, as long as the system’s memory space is enough, method of area will be there is enough space, however, doesn’t mean we don’t need the dimension Small limit, because it is the system memory, if infinite, not only will affect the use of other applications of the system, serious may lead to system crash.

Where are string constant pools and static variables stored in JDK1.7

In JDK1.7, some of the persistent generation data has been moved from the Java persistent generation to the heap, such as symbol references and string constant pools

3. Why does Hotspot replace persistent generation with metasspace in JDK1.8

1. Avoid OOM:

The method area is mainly used to store information related to classes (including class bytecode files). Although PerSize and MaxPerSize parameters can be used to set the space size of permanent generation, with the emergence of dynamic bytecode generation technologies such as ASM and Cglib, the size of class information can not be controlled after the object bytecode information is modified. It’s easy to run out of permanent generation memory.

JDK1.8 uses metasapace instead of permanent generation. Because metasapace uses system memory and is controlled by the actual available space of the system, it can avoid OOM to some extent. However, you can also control the size by specifying parameters such as MaxMetaspaceSize.

2. Improve GC performance:

The permanent generation’s garbage collection is tied to the old generation, so whenever either of them is full, the permanent generation and the old generation’s garbage collection will be triggered.

Using meta-space replacement simplifies the Full GC, reduces the GC time (because you don’t need to scan the data in the permanent generation), and improves GC performance. In the metadata space, there are only a few Pointers to Pointers to class objects in the metadata of a heap such as a class.

3. Hotspot and JRockit merge:

This is the official reason, permanent generation is just a concept in Hotspot VIRTUAL machine,JRockit does not have this term,JDK8 needs to integrate Hotspot and JRockit, so it scrapped permanent generation and introduced meta space.

4. Understand meta-space

(I): Characteristics

Ensure that the life cycle of classes and associated metadata is consistent with that of the class loader.

2. Loaders have their own dedicated storage space

Save GC scan and compression time

4. The position of an object in the meta space is fixed

5. No single class is reclaimed; if the GC finds that a class loader is no longer alive, the associated space is reclaimed entirely

(TWO): existing problems

1. The metacarspace is allocated in blocks. The specific block size is determined by the class loader.

2. Metaspace VMS do not support compression operations.

Vi. Program Counter Register

Threads are private, occupying a small memory space that reads the next bytecode instruction to be executed. It is also an area in the JVM specification where outofMemoryErrors do not occur.

It is designed for the purpose of making multi-threaded JAVA procedures each thread can work normally, each thread has its own program counter, used to save the execution of the thread, so when the thread switch can continue to execute on the basis of the last execution.

A simple example: When you are using a mobile phone looked at hidden little video, as exciting, Lao wang give you a ring, suddenly was interrupted, you scold Lao wang after a meal, are you sure you want to then just didn’t look at the schedule looks rather than the beginning, at the moment, it is how to know where you just saw, the program counter will play a role, it is responsible for managing the schedule, can let you After a thread switch, the previous execution location is also known (exciting!).

Seven: the Stack (Stack)

Threads are private, with the same lifecycle as threads, which in the JAVA language is used to describe the execution memory model of a method.

Before a method is executed, a Stack Frame is created to store information about local variables, dynamic links, method exits, etc. The start and end of a method correspond to the process of a stack frame being pushed into and out of the virtual machine.

Native Method Stack

PS: Native Mehtod is an interface provided externally to JAVA language calls, usually implemented in C or C++.

Thread private, similar to the stack, except that the stack executes methods written in the JAVA language, whereas the Native method stack executes methods provided by the Native interface, i.e. JAVA calls non-Java implementations.

Nine: The relationship between JVM and JMM

When you hear about the JVM(JAVA Virtual Machine) and the JMM(JAVA Memory Model) in everyday code development or job interviews, it’s easy to confuse the relationship between the two. Let’s explain the differences in detail.

JMM(JAVA Memory Model) is used to define a consistent, cross-platform JAVA Memory Model in JSR133 The memory model, which is not as real as the JVM’s memory structure, is a cache consistency protocol that blocks access differences between hardware and operating systems and defines rules for data reads and writes.

One: memory visibility

In JMM, we refer to the shared memory where multiple threads communicate as the main memory. In the application of concurrent programming, each thread maintains its own working memory, and the data stored in the working memory is a copy of the data in the main memory. JMM is used to control the data interaction between the local memory and the main memory.

As you can see from the above picture and analysis, the JMM memory model and the JVM are essentially unrelated, but if forced, the main memory actually corresponds to the object instance data portion of the heap in the JVM, and the working memory corresponds to the stack portion of the JVM.

What is the JRE

The JAVA Runtime Environment can be thought of as a container with the JVM as its contents.

JRE = JVM + Java Packages Classes(like Util, Math, lang, AWT, Swing etc)+ Runtime libraries

What is the JDK

The Java Development Kit is used for Development and contains the JRE, compiler, and other tools (such as JavaDoc, Java debugger) that allow developers to develop, compile, and execute Java applications.

Learn to share and encourage each other

“Drunk in the light to see the sword, dream blowing trumpet company camp”, was awakened in the middle of the night by the interviewer, just have this JVM knowledge, want to interview OFFER more, usually little hard work, but do not recommend everyone stay up late, the body is the capital of the revolution. The above only shows the JVM, but also collates some notes, including Java foundation, Spring, MyBatis, multi-threaded concurrency, design patterns, databases, Redis, algorithms and data structures, distributed, etc

Free access to information: Like + like + likePoke me at GitHub homepageFree access to documentation and this JVM learning brain map (full of notes)!!

Three important things, thumbs up, thumbs up, thumbs up!

Advanced Java architecture presentation

There are interview review materials and sorted out the interview high-frequency questions of the video analysis and advanced notes of the master architecture

If you feel that the article is helpful to you, [remember to like oh! Your support is my creation of more high-quality articles of power, do not waste my midnight up to work overtime! Any suggestions or comments in the comments section!