JVM Knowledge Point Grooming

Source: Internet
Author: User

Why 1.JVM can cross-platform

The JVM can execute Java bytecode (the JVM bytecode instruction set) across the computer architecture (operating system), masking the differences between the software or hardware that can be associated with each machine platform , making the platform-related coupling unified by the JVM provider.

Instruction set: A collection of commands that computers can recognize for machine languages.

Each running Java program is a JVM instance.

2. Describe the JVM architecture

(1) class loader : When the JVM starts or the class runs, the required classes are loaded into the JVM. The type of each loaded class corresponds to a class instance, which uniquely represents the class and is stored in the heap.

(2) execution Engine : The bytecode instruction (CPU) responsible for executing the JVM. The execution engine is the core part of the JVM, the function is to parse the bytecode instruction, get the execution result (Implementation mode: Direct execution, JIT (just in time) to the local code execution, the Register chip mode execution, based on the stack execution). is essentially a way to string up the process. Each Java thread is an instance of an execution engine, with multiple execution engines working in a JVM instance, some executing the user program, and some executing the JVM internal program (GC).

(3) Memory Area : A function module, such as a register or a PC pointer recorder, that simulates the storage, recording, and scheduling of physical machines. Stores the data that the execution engine needs to store when it executes.

(4) Local Method Interface : Invokes the operating system local method to return the result.

3. Describe the JVM's working mechanism

How the machine executes the code: source code-preprocessor-compiler-assembler-target code-linker-executable program.

The Java compiler compiles the high-level language into the virtual machine target language.

The JVM Execution bytecode instruction is a stack-based architecture , and all operands must first be put into the stack, and then the result is pressed into the stack based on the selection of the code from the top of the Stack, which pops up several elements.

The source code is compiled into the virtual machine target language through the Java compiler and then executed by the JVM execution engine.

4. Why JVM bytecode directives select a stack-based structure

The JVM is designed to be platform agnostic , and it is difficult to design uniform register-based directives.

For The purpose of compact instruction , the compiled class file is more compact, which improves the efficiency of byte-code transmission on the network.

5. Describe the architecture design of the execution engine

When a new thread is created, the JVM creates a stack for the thread and assigns a PC register (pointing to the first line of executable code). A new stack frame data structure is created on this stack when the new method is called. The stack frame of the method after execution is gone, the PC register is destroyed, all values in the local variable area are freed, and the JVM is recycled.

6. Describe the basic structure of the Javac compiler

The purpose of the Javac compiler is to convert the source code that conforms to the Java language specification into the Java bytecode of the JVM specification.

(1) Lexical analyzer component : Finding a normalized token stream

(2) Parser component : Generate an abstract syntax tree that conforms to the Java language Specification

(3) Semantic parser components : Translating complex syntax into the simplest syntax, annotated syntax tree

(4) Code generator component : Converting a syntax tree data structure into a byte-code data structure

7. Description of JVM compilation optimizations

Early (compiler): very little; at compile time, to save the constant pool space, the same constant can be determined with only one reference address.

Late (operating period):

Method Inline: Removes the cost of the method call, builds a good foundation for other optimizations, and facilitates continuous optimization on a larger scale.

Redundant access elimination: Common sub-expression elimination

Replication propagation: Completely equal variables can be substituted

Useless code elimination: Clear code that will never be executed

(1) Common subexpression elimination (language-independent): If the public subexpression has been computed, and there is no change, there is no need to calculate again, the results can be replaced.

(2) Array boundary Check elimination (language related): Limit the loop variable between the range of values, can save multiple conditions to judge.

(3) Method inline (most important): Remove the cost of the method call, establish a good basis for other optimizations, and facilitate the adoption of continuous optimization in a wider range of means.

(4) Escape analysis (Forefront): The dynamic scope of the analysis object; variables are passed to other methods as invocation parameters-method escapes; accessed by external threads-thread escapes.

Stack allocation-Reduce the collection pressure of the garbage system

Sync elimination-If you can't escape the thread, you can eliminate the sync

Scalar substitution-Restores the variable to the original type to access

Small copy: Final modified local variables and parameters, there is no symbolic reference in the constant pool, there is no access to the identity, there is no effect on the runtime, only to ensure that its compilation during the invariance.

What are the 8.ClassLoader (class loaders)

(1) Bootstrap ClassLoader (startup ClassLoader): Fully controlled by the JVM, loading classes (Java_home/lib) required by the JVM's own work

(2) Extension ClassLoader (Extension class loader): Part of the JVM itself, not implemented by the JVM itself (Java_home/lib/ext)

(3) Appclication ClassLoader (Application class loader): The parent class is extension ClassLoader, which loads the class library on the classpath (user-Classpath)

9. Describe the role of ClassLoader (what is the ClassLoader) and the loading process

Load the class file into the JVM, examine who loads each class (the parent-first level loading mechanism), and re-parse the class bytecode into the JVM's uniform requirements object (class object) format.

. Class->findclass->liking:class specification validation, preparation, parsing, class property initialization assignment (execution of static block)->class object (This is why the static block executes only once)

10. Describe the JVM class loading mechanism

ClassLoader first does not try to load the class itself, but instead delegates the request to the parent ClassLoader to complete, each level is. The child loader will attempt to load (level loading mechanism, parent precedence, parental delegation) only if the parent loader feedback cannot complete the request (the desired class is not found within the search scope).

Benefit: The class has a hierarchical relationship with precedence along with its loader, guaranteeing that the same class can only be loaded by one loader.

11.JVM load class files into memory in two ways

(1) Implicit Loading: Inherited or referenced classes are not in-memory

(2) Explicit loading: Loading in code by calling ClassLoader

12. Load class error analysis and its solution

(1) ClassNotFoundException: No corresponding byte code (. Class) file was found; check classpath for any corresponding files

(2) Noclassdeffounderror: Implicit loading is not found, ClassNotFoundException throws noclassdeffounderror; Ensure that classes referenced by each class are under Classpath

(3) Unsatisfiedlinkerror (link error not met): the corresponding local library file could not be found when a Lib file for the JVM was deleted or the method for resolving the native identity was removed

(4) ClassCastException: This error occurs when casting a type, the container type is best displayed indicating the type of object it contains, the instanceof check is not the target type, and the type conversion

(5) Exceptioninitializererror: When assigning a value to a static property of a class

13:java should not load classes dynamically (JVM can dynamically load classes)

There is only one copy of the object in the JVM, which cannot be replaced, the object's reference relationship is only held and used by the creator of the object, and the JVM cannot intervene in the reference relationship of the object because the JVM does not know how the object is being used, the JVM does not know the object's run-time type, only the compile-time type.

However, you can not save the state of the object, object creation and use is freed, the next time after the modification, the object is new (JSP).

Which components in 14.Java need to use memory

(1) Java heap: Storing Java objects

(2) Thread: The entity of the Java Runtime Program

(3) class and ClassLoader: stored in the heap, this part of the area is called the Permanent generation (PermGen area)

(4) NIO: A new way to perform I/O based on channels and buffers.

(5) JNI: Native code can call Java methods, Java methods can also invoke native code

15. Describes the JVM memory structure and memory overflow.

The JVM divides the memory structure according to the storage structure of the run-time data.

PC Register data: Strictly speaking, a data structure that holds the memory address of the currently executing program. The thread is private in order to recover to the correct execution location after the thread switch.

No memory overflow.

(1) Java stack: The memory model that the method executes, which stores the data that the thread needs to execute. Thread Private.
Unable to request sufficient space when--OUTOFMEMORYERROR:JVM the expansion stack. A method that constantly calls itself and does not terminate.

--stackoverflowerror: The requested stack depth is greater than the stack depth allowed by the JVM. Create a sufficient number of threads.

(2) Heap: storage objects, each of the Java objects in the heap is a copy of the object's class, and replication includes all non-static attributes that inherit from his parent class. Thread sharing.

--OutOfMemoryError: The number of objects reaches the heap capacity limit. You can add object implementations to the ArrayList by constantly adding them.

(3) Method area: Store class structure information. This includes Chang (a variety of literal and symbolic references produced during the compilation period) and a run-time-constant pool. Thread sharing.

--OutOfMemoryError: the same running constant pool.

(4) Local method stack: similar to the Java stack, the space prepared for the JVM to run the native method. Thread Private. (c stack) OutOfMemoryError and stackoverflowerror with JVM stacks.

(5) Run a constant-rate pool: Represents the Constants table in each class file at run time. New constants generated during the run are placed in the run-time constant pool.

--outofmemoryerror: Continuously adds a string to the list<string> and then String.inern (), PermGen Space (the run-time constant pool belongs to the method area).

(6) Local Direct memory: NIO.

--outofmemoryerror: Allocates memory by applying directly to the operating system.

16. Describe the JVM memory allocation policy

(1) Priority allocation of objects in Eden

(2) Large objects go straight into the old age

(3) long-term survival of the object will enter the old age

(4) The surviving area of the same age object occupies more than half of the surviving space, and will enter the old age

(5) Space guarantee allocation (more than half the remaining space in the old age, otherwise full GC)

17. Describe how the JVM detects garbage

Through the accessibility analysis algorithm, through some of the columns called GC roots as the starting point, from these starting points to search down, the path of the search is called the reference chain, when an object to the GC roots no reference chain connected (GC roots to this object unreachable), it proves that this object is not available.

Use the accessibility analysis algorithm instead of the reference counting algorithm. Because the reference counting algorithm is difficult to solve the problem of circular references between objects.

18. What elements are available as GC Roots

(1) reference in JVM stack (local variable table in stack frame)

(2) Class static property reference in the method area

(3) Constant reference in the method area

(4) Jni (General native method) reference in the local method stack

19. Describe the idea of generational garbage collection algorithm:

The object according to the length of life to group, divided into the young generation and the old age, the newly created in the old age, after several recovery still survive the object into the old age, the old age of garbage frequency is not as frequent as the younger generation, reduce each collection to scan all the number of objects, improve the efficiency of garbage collection.

20. Describe the heap structure and its proportions based on generational.

(1) Young Generation ( -1/4): Eden+survior (1/8, this ratio guarantees that only 10% of the space is wasted to ensure that only a few more than 10% of the objects are alive) =from+to, storing the newly created object.

(2) older (old): objects that are kept alive after several garbage collections

(3) Permanent zone (Perm area): Class object for storing classes

21. Describe garbage collection algorithms

(1) Mark-sweep algorithm: First mark the object to be recycled, and then clear the mark after completion. Cons: Low mark efficiency and low efficiency, resulting in a large amount of discontinuous memory fragmentation at the end of the recovery (there is not enough contiguous space to allocate memory, triggering another garbage collection in advance). Suitable for the old age of high object survival.

(2) The copy algorithm (the From and to areas of the survivor, the From and to Will interchange roles):

Divide the memory capacity by two blocks of equal size, using only one piece at a time. Once you're done, copy the surviving object to another piece and clear the used piece once. Regardless of memory fragmentation, each time you move the top pointer, the memory is allocated sequentially, enabling simple and efficient operation. Suitable for the new generation.

Disadvantage: Memory is reduced to the original general, high cost. Waste 50% of space.

(3) Marker-Collation algorithm:
When the tag is complete, move the surviving object to one end, and then clear the memory outside the boundary. Suitable for the old age of high object survival.

22. Describe the recovery strategy for the new generation and the old age

When the Eden Zone is full, the minor GC is triggered, all the surviving objects are copied to a survivor area, and another object that survives in the survivor area is copied to the survivor area, always guaranteeing that a survivor is empty.

Toung area survivor after triggering minor GC, the object that still survives is stored in the old area, if the object in the Survivor area is not placed in the Eden area, or if the Survivor area object is older enough, it is placed directly into the OID area, and the full GC is triggered if it does not fit.

Perm Zone full will trigger major GC.

22. Describe the CMS garbage collector

CMS collector: Concurrent Mark Sweep concurrent tag-clear. Pay attention to the response speed, applicable to the Internet and B/s system on the service side. The initial tag still requires stop the world but is fast. Disadvantage: CPU resource is sensitive, can not float garbage disposal, there will be a lot of space debris.


1.Java should not dynamically record class

Java's advantage is based on the mechanism of shared objects, to achieve a high degree of information sharing, that is, eliminates duplication of class information creation and recycling by saving and holding the state of an object . Once an object is created, it can be held and used by people. Dynamic loading theoretically can replace this object directly, and then update all references to the original object in the Java stack, but it is still not feasible, because it violates the design principle of the JVM, the object's reference is only owned and used by the creator of the object . The JVM does not interfere with the reference relationship of an object, because the JVM does not know what to do with the object, and the JVM does not know the object's run-time type but only the compile-time type.

If the property structure of an object is modified, the property may still be referenced by other objects at run time.

but you can a workaround to take a state that does not save the object , the object is freed after it is created and the object is new after the next modification. This is true for JSP and other interpreted languages.

JVM Knowledge Point Grooming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.