Java common face questions and answers 11-20 (JVM) __java

Source: Internet
Author: User
Tags exception handling garbage collection
11.JVM memory is divided into which areas, what is the function of each area?

Java virtual machines are mainly divided into the following areas:

Method Area:
1. Sometimes it also becomes a permanent generation , where garbage collection is rare, but it does not mean that GC does not occur, where GC is primarily an uninstall of the Chang and the type in the method area
2. The method area is primarily used to store data such as information about classes that have been loaded by the virtual machine, constants, static variables, and compiled code for the Just-in-time compiler.
3. The zone is shared by threads.
4. There is a run-time pool in the method area that holds the literal and symbolic references generated by static compilation. The constant pool is dynamic, that is, constants are not necessarily determined at compile time, and constants generated by the runtime also exist in this constant pool.

Virtual Machine Stack:
1. Virtual machine stack is what we call the stack memory , it is the Java method service, each method in the execution of the creation of a stack frame, used to store local variables table, operand stack, dynamic link and method of export information.
2. The virtual machine stack is thread-private and has the same lifecycle as the thread.
3. The Local Variables table stores the base data type, the ReturnAddress type (the address that points to a byte-code instruction), and the object reference, which may be a pointer to the starting address of the object, or a handle to the object or a location associated with the object. The memory space required by the local variable is determined between the compilers
4. The function of the stack of operations is mainly used to store the results of operations and operations, it is different from the local variable table through the index to access, but the stack and stack the way
5. Each stack frame contains a reference to the method that the stack frame belongs to in the Run-time pool, which is held to support the dynamic connection during method invocation. Dynamic linking is the conversion of a symbolic reference in a constant pool to a direct reference at run time.

Local method Stack
The local method stack is similar to the virtual machine stack, except that the local method stack serves the native method.

The Java heap is a piece of memory that is shared by all threads, created at the time the virtual machine is started, and almost all object instances are created here, so the zone often has garbage collection operations.

Program counter
The memory space is small, the bytecode interpreter works by changing this count value can select the next need to execute byte code instructions, branch, loop, jump, exception handling and thread recovery functions need to rely on this counter to complete. The memory area is the only area where the Java Virtual Machine specification does not specify any oom conditions. 12. Like and judge whether an object survives? (or GC Object Determination method)

There are two ways to determine whether an object survives:
1. Reference Counting Method
The so-called reference counting method is to set a reference counter for each object, whenever there is a place to refer to the object, the counter plus one, when the reference is invalid, the counter is reduced by one. When an object's reference counter is zero, the object is not referenced, i.e. "dead object", which is garbage collected.
A flaw in reference counting is the inability to solve the circular reference problem, which means that when object a refers to object B and Object B is a reference to object A, then the A,b object's reference counter is Non-zero and the garbage collection cannot be completed, so the mainstream virtual machine does not use this algorithm.

2. Accessibility algorithm (reference chain method)
The idea of the algorithm is to start a downward search from an object called GC Roots , which is not available if an object is not connected to a GC Roots without any reference chain.
The following are some of the objects in Java that can be roots as GC:
Object method area referenced in virtual machine stack class static property Reference object method area constant Pool Reference object local method stack Jni Reference object

Although these algorithms can determine whether an object can be recycled, an object is not necessarily recycled when the above conditions are met. When an object is not up to GC root, this object and
will not be recycled immediately , but out of a reprieve stage, to be truly recycled two times to go through the mark
If the object does not have a reference chain with GC root in the accessibility analysis, it is marked for the first time and filtered once, and the criteria for filtering is whether the Finalize () method is necessary. This is considered unnecessary when the object does not overwrite the Finalize () method or has been called by the virtual machine.
If the object is necessary to execute the Finalize () method, the object will be placed in a pair of queues called F-queue, where the virtual opportunity triggers a finalize () thread to execute, the thread is low-priority, and the virtual machine does not promise to wait for it to run out. This is because if the finalize () execution is slow or a deadlock occurs, it causes the F-queue queue to wait, causing the memory recovery system to crash. The GC is marked for a second time on an object in F-queue, at which point the object will be removed from the collection to be reclaimed. 13. A brief description of the Java garbage collection mechanism?

In Java, programmers do not need to display to release the memory of an object, but rather by the virtual machine itself. In the JVM, there is a garbage collection thread, it is low-priority and is not normally performed, triggers execution only when the virtual machine is idle or if the current heap is out of memory, sweeps those objects that are not referenced by any reference, and adds them to the collection to be reclaimed for recycling.What are the methods of garbage collection in Mark-Clear:
This is the most basic garbage collection algorithm, according to the name can be known, its idea is to mark which to be recycled objects, and then unified collection. This method is very simple, but there are two major problems: 1. Inefficient, marking and removal efficiency are very low; 2. A large number of discrete pieces of memory will result in the subsequent program in the allocation of large objects, because there is not enough contiguous memory to trigger a GC action ahead of time.
Replication algorithm:
To solve the problem of efficiency, the replication algorithm divides the available memory into two equal parts by capacity, then one at a time, when a piece of memory is used up, the surviving object is copied to the second block of memory, then the first block of memory is once clear, and then the object on the second block is copied to the first block. But this way, the cost of memory is too high, each time basically waste the general memory.
Then the algorithm was improved, the memory area is no longer according to 1:1 to divide, but the memory is divided into three parts of 8:1:1, the larger memory to the Eden area, the remaining two small memory area called Survior area. The Eden area is given priority each time, and if Eden is full, the object is copied to the second block of memory, then the Eden area is cleared, and if there are too many surviving objects to be survivor enough, these objects will be copied to the old age through the allocation guarantee mechanism. (Java heap is also divided into Cenozoic and old age)
The algorithm is mainly used to solve the problem of Mark-purge, which produces large amount of memory fragments, and the efficiency of the replication algorithm is solved when the object survival rate is high. The difference is that the recyclable object is moved to one end when the object is cleared, and then objects outside the dropped bounds are cleared, so that no memory fragmentation is generated.
Generational Collection
Today's virtual machine garbage collection is mostly used in this way, according to the object's life cycle, the heap is divided into Cenozoic and old age. In the Cenozoic, because of the short lifetime of the object, a large number of objects will die each time, then useCopyAlgorithm. In the old age, the object survival rate is high, there is no extra space for allocation guarantee, so you can Memory Model

The Java Memory model (JMM) is a control mechanism for communication between threads. JMM defines the abstract relationship between main memory and threads. Shared variables between threads are stored in main memory (main memory), and each thread has a private local memory, local memory, that is stored locally in memory to read/write a copy of the shared variable. Local memory is an abstract concept of JMM and is not real. It covers caching, write buffers, registers, and other hardware and compiler optimizations. The abstract diagram of the Java memory model is as follows:

From the figure above, the following 2 steps must be experienced to communicate between thread A and thread B:
1. First, thread a flushes the shared variables updated in local memory A to main memory.
2. Thread B then goes to main memory to read shared variables that have been updated before thread A.
Well written: The HTTP://WWW.INFOQ.COM/CN/ARTICLES/JAVA-MEMORY-MODEL-1 class loading process?

Java class loading needs to go through 7 processes:
The first procedure to load the class at load time, in this phase, will complete three things:
1. Gets the binary stream of the class through the fully qualified name of a class.
2. Convert the static storage structure in the binary stream into a method to run the data structure.
3. Generates a class object in memory that is used as the data access entry for the class.

The purpose of validation is to ensure that the information in the byte stream of a class file is not compromised to the virtual machine. During this phase, the following four-hour verification is mainly completed:
1. File Format Verification: Verify that the byte stream conforms to the class file specification, such as whether the primary and secondary version number is within the current virtual machine scope, and whether constants in the constant pool have unsupported types.
2. Metadata validation: Semantic analysis of the information described by the bytecode, such as whether the class has a parent class, whether it integrates the classes that are not inherited, and so on.
3. Bytecode verification: It is the most complex phase of the whole verification process, through verifying the data flow and control flow analysis, to determine the correctness of program semantics, mainly for the verification of the method body. Such as: the type conversion in the method is correct, the jump instruction is correct, and so on.
4. Symbolic reference Verification: This action occurs in the subsequent parsing process, primarily to ensure that the parsing action is performed correctly.

Get ready
The preparation phase allocates memory for the class's static variables and initializes them to default values, which are allocated in the method area. The preparation phase does not allocate memory for instance variables in the class, and the instance variables are assigned to the Java heap along with the objects when the object is instantiated.

    The public static int value=123;//The initial value of 0 in the preparation phase. The initialization phase becomes 123.

This phase mainly completes the conversion action of the symbol reference to the direct reference. Parsing an action is not necessarily possible until the initialization action completes, or after initialization.

The final step of class loading, the previous class loading process, in addition to the user application in the load phase can be engaged by the custom ClassLoader, the rest of the action is completely driven and controlled by the virtual machine. In the initialization phase, the Java program code defined in the class is actually started. 17. Briefly describe Java class loading mechanism?

The virtual machine loads the descriptive data from the class file into memory, verifies the data, parses and initializes it, and eventually forms a Java type that can be used directly by the virtual machine. 18. Class loader Parent delegation model mechanism.

When a class receives a class load request, it does not load the class on its own, but it assigns it to the parent class, which is loaded by the parent class, and if the parent class cannot load it, feed back to the subclass and subclass to complete the load. 19. What is a class loader and what is the class loader?

The code block that implements the binary byte stream of the class through the permission name of the class is called the class loader.
There are mainly four kinds of loaders:
1. The boot ClassLoader (Bootstrap ClassLoader) is used to load Java core class libraries and cannot be referenced directly by Java programs.
2. Extended class loader (Extensions class loader): It is used to load Java extension libraries. The implementation of the Java virtual machine provides an extension library directory. The class loader finds and loads Java classes in this directory.
3. Systems Class Loader (System class loader): It loads Java classes based on the Java application's Classpath (CLASSPATH). In general, Java-applied classes are loaded by it. It can be obtained by Classloader.getsystemclassloader ().
4. User-defined ClassLoader, implemented by inheriting the Java.lang.ClassLoader class. 20. A brief description of Java memory allocation and recovery rates and minor GC and major GC objects are assigned preferentially in the Heap's Eden area.
Big objects go straight into the old age.
Long-lived objects will go straight into the old age.
When the Eden area does not have enough space to allocate, the virtual opportunity performs a minor GC. Minor GC usually occurs in the new era of Eden area, in this area the object survival period is short, often occurs the frequency of GC is high, the recovery speed is relatively fast; The full gc/major GC occurs in the old age and, in general, does not trigger the minor GC when it triggers the old age GC, but by configuration, a minor GC can be performed before the full GC to speed up the recovery in the old age.

Next: Java Common face questions and answers 21-30

Related Article

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: 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.