java improve the JVM entry

Common interview questions

  1. java against garbage collection algorithm
  2. The advantages and disadvantages of each algorithm and principles of GC
  3. How to determine whether an object is garbage
  4. What kind of objects can be used as GC ROOTS
  5. Talk about your understanding of the minorGC and fullGC
  6. Four kinds of java reference types and their meanings
  7. Speak work in common abnormality
  8. Class loading mechanism

JVM entry

1. How to determine whether the object is alive

  1. Question: Java is determined whether the algorithm is rubbish

Object is not referenced is a waste.

Tip: Counter

JDK 1.2, the reference counting algorithm

Creating a counter for each object, if there is a reference pointing to it, counter + 1, when a reference is no longer to it, the counter is -1, and finally determine whether the counter is greater than 0, if more than 0, indicating it has references to If not greater than zero, indicating that no references to it.

Reference counting algorithm causes of failure: a circular reference problem

public class Demo01 {
    Demo01 instance = null;

    public static void main(String[] args) {
        Demo01 a = new Demo01();
        Demo01 b = new Demo01();
        a.instance = b;
        b.instance = a;
        a = null;
        b = null;
    }
}

Here Insert Picture Description

The reference counting algorithm, and when a = b = null null, their counters are each other than 0, a target point which has to b, a and b have the object to point to it, but once when reference is null that object can not be invoked, in essence they should be garbage, so the reference flawed counting algorithm.

Reachability algorithm:

Select a node as a GC of ROOTS, and other references to point to the objects of ROOTS GC, GC if these objects can reach the apex of ROOTS, then that object is not garbage, a garbage contrary, point chain formed of ROOTS referred GC GC chain.

Four kinds of objects

  1. Virtual Machine stack (local variable table objects pointed to by the stack frame)
  2. Method static property class object referenced by region
  3. Method of constant region
  4. native method object reference

Interview questions:

4 kinds of references

Different reference types, mainly reflected a different object reachability status and the impact on garbage collection.

  • Strong reference to the common ordinary object references. As long as exceeding the scope or explicitly assigned to null, it can be garbage collected.
  • Soft references (soft reference) relative weakening, it could make objects exempt some garbage collection. Before the system memory overflow exception occurs, it will clean up the soft reference object pointing. SoftReference class implements soft references, usually achieve sensitive cache memory.
  • Weak reference (weak reference) regardless of the adequacy of the current memory, the recovery will be only weakly associated with the object reference. WeakReference class implements weak references
  • Virtual reference, a reference phantom (Phantom Reference) weakest, which can not be obtained by the object instance. The sole purpose is to track the object to be recovered garbage collector activity, associated objects will receive a notification system before being recycled collector. Only provides the method is, do certain things after finalize.

finalize the object of self-rescue

The design aim is to ensure that object prior to garbage collection to complete the recovery of a particular resource . JDK9 has been marked as deprecated

Three states object:

  1. Up
  2. Recoverable state
  3. unachievable

When the two conditions are met (it is likely to finalize method calls):

  1. This method is overridden
  2. finalize one and can only be executed once

F-Queue will be placed in the queue Once satisfied, to be performed by a low-priority thread Finalizer can not guarantee successful.

finalize () can do, try-finally do better, more timely, so I do not encourage the use of this method to save the object.

2. java virtual machine runtime data area

Here Insert Picture Description
Jvm according to specifications, java virtual machine memory management include the following runtime data area:

Program Counter

program counter register, can be seen as the current line number indicator bytecode execution thread. By changing the bytecode instruction to be executed to select a value of the counter. Each thread requires a separate program counter. If the thread is executing the java method, the counter records the address of the virtual machine bytecode instruction being executed; native method is being performed if the counter value is null (undefined).

java virtual machine stack

With the program counter, just as a thread private, life cycle and the same thread. Each method execution will create a stack frame. Each method call to the procedure is finished, the stack frame corresponds to a push to the stack in a virtual machine process stack.

Native method stacks

And stack effect similar service for the native method.

java heap

Its sole purpose memory area is stored object instance, specification: all object instances that allocate memory here. But the mature development of the JIT compiler and escape analysis techniques, it is no longer absolute.

java heap is the main area managed by the garbage collector. Many times also referred to as "GC heap." From the recovered memory, generational collection algorithm in accordance with, java heap may be subdivided into: the old generation and the new generation, the proportion of 1: 2. Further details are Eden space, From Survivor space (s0), To Survivor (s1) space. A ratio of 8: 1: 1.

Here Insert Picture Description

Methods district

In jvm specification states: method area belongs heap, while the constant pool area belongs to the method, the constant pool in the heap space; in jvm implementations: do not comply with this specification. Methods district alias: non-heap.

Hotspot zone method is also called permanent-generation (Permanent Generation), because the design team used the method to achieve permanent generations area only. 1.7 out of permanent generation of constant pool. 1.8 Generation permanently removed, increasing the metadata area.

And heap as class information storage has been loaded in the virtual machine, constants, static variables, the time compiler to compile the code and other data.

JVM size

JVM is a segment size, the initial size (maxMemory) and Maximum size (totalMemory The)

The actual development is usually adjusted to the same, to avoid unnecessary waste of resources, generally adjusted to 3/4 of memory

3. Memory allocation and recovery strategies

  • Great direction, is allocated on the heap memory allocated in the Eden district main targets of the new generation, a few cases directly assigned years old (trigger guarantee the principle of allocation)

  • minorGC: the new generation GC, very frequently, recover faster

  • majorGC / Full GC: old's GC, often accompanied by at least one minorGC, minorGC slower rate than more than 10 times.

  • Objects priority allocation in Eden District

  • Large objects directly into the old year (and therefore avoid writing "short-lived large object" advance trigger garbage collection when writing programs), typically a long string or array

  • Long-term survival of the object will enter the old year (such as pool object)

  • Old generation characteristics: high survival rate target, there is no guarantee extra space is allocated

Garbage collection algorithm

Old's use of mark - sweep and tags to organize algorithm.

Mark - sweep algorithm (Mark-Sweep)

Mark and sweep into two phases, the first mark all objects need to be recovered, all unified object is marked recovery after completion mark

Inadequate: a question of efficiency, two process efficiency is not high ; a space problem, it will produce a large number of discrete memory fragmentation , resulting in the allocation of large objects, can not find enough contiguous memory and advanced trigger another garbage collection action .

Replication algorithm (copying)

Eden area allocation preferentially objects, each object defines a target age (age) counter. When eden district is full, this time triggered minorGC-> eden region will live objects copied to s0-time zone, age is set to 1, then clean out the area eden memory, when s0 area is full, trigger minorGC, this time will the s0-time area live objects copied to s1 area, then clean out the area s0 memory, s0-> s1. Each survived a minorGC, plus the age of 1, it will default to 15-year-old was promoted to the old era.

New Generation Characteristics: Object Chaosheng 98% evening death. Special Scenes, survivor space is not enough to trigger the security principle of distribution, depend years old.

Only need to pay a small amount of live objects replication costs to complete the collection.

Pros: Fast; no memory fragmentation

Tags to organize algorithm (Mark-Compact)

The labeling process with the mark - sweep algorithm, the subsequent steps are not directly recycled objects to clean up, but to all surviving objects are moved to the end, then clean out the memory beyond the boundary.

Advantages: Continuous Memory

Cons: object features its own decision, slow

The garbage collector

stop the world

CMS parallel collector hardly pause

The class loading mechanism

From the class of the class file into memory, according to the order to go through to load, and link initialization three steps.

1. Load

Load (loading) is a class loading stage (class loading) process.

It refers to locate the byte stream, and the process of creating the class accordingly.

Array no corresponding byte stream, generated directly by the java virtual machine, while the other classes, the class loader needs the complete process to find the byte stream.

  1. Binary stream generated class file
  2. The method of generating a data structure region
  3. Generate class files

2. Links

It refers to merge to create the class into java virtual machine, so that the process can be executed. Divided validation, preparation and analytical stages.

1. Verify

Check the correctness of the binary files, make sure that the constraints are loaded class to meet the java virtual machine

2. Prepare

Specific initialization, initialization will be carried out at a later stage to the loaded class static fields allocated memory.

Class object and class variables default initialization; if it is done directly assigned final action

3. Resolving

The symbol is replaced with a direct reference cited

Reference symbol: In java, a class compiled into a java class file, at compile time, java class does not know the actual address of the class referenced, it is used only to replace the symbolic references, such as class org.simple.People cited org.simple.Language class, the class at compile time People do not know the actual memory address Language classes

Direct quote: The actual memory address, pointing to the actual memory

If you have a direct reference, the reference target must have been loaded into memory

3. Initialize

Marked as a constant value field assignment, and performing <clinit>the process method, class initialization is executed only once, this feature is used to implement lazy initialization single embodiment.

4. The class loader

Class loader 1. Introduction

ClassLoader loading stage process is responsible for loading classes , though only the operation for loading implementation class, however, for any class, it needs to load a class loader and the class itself together determine its uniqueness in the virtual machine .

2. Methods

An important method of ClassLoader

  • public Class<?> loadClass(String name) throws ClassNotFoundException Was charged and returns a Class -> parent class loader mechanism parent delegated
  • protected final Class<?> defineClass(byte[] b,int off,int len) Define a class, do not call the public
  • protected final Class<?> findClass(String name) Examples of suitable look for the name corresponding to the Class, this method does not guarantee that the parent class parents delegate mechanism

3. Category

1. Start the class loader (Bootstrap Classloader)

Use C ++ implementation, is part of the virtual machine itself is responsible will be stored in <JAVA_HOME>\libthe directory, or by -Xbootclasspaththe parameters specified in the path, and a virtual machine identification (by file name identification rt.jar) libraries loaded into the virtual machine memory. It can not be directly referenced.

2. The extension class loader (Extension Classloader)

Responsible for loading <JAVA_HOME>\lib\extthe directory, or by java.ext.dirsall libraries, developer of system variables specified path can be used directly extend the class loader

3. The application class loader (Application Classloader)

The class loader is the ClassLoader getSystemClassLoader return value () method, generally referred to as the system class loader is responsible for loading the user class path (the ClassPath) specified on the library. Program default class loader.

The delegation model parent (Parents Delegation Model)

1. Concept

Parent delegation model in addition to the rest of the boot class loader needs to have its own parent class loader

Parent-child relationship is like the relationship between father and son kind of logic, not the parent-child relationship class inheritance

When a class loader class received a request: he will not be loaded first, but delegated to the parent loader to load each level loader are like this.

Each request will be loaded so that the final through boot class loader. Only when the parent class loader loads the child can not return to the loader will be loaded.

Parents of the benefits of delegating: Because each class loader will start after the top-level class loader, for example, java.lang.Objectsuch a class in each class loader are of the same class (only if both are from the same class loader loads the class makes sense, these two classes are equal.)

If there is no parent delegation model, by each class loader to load their own words. When you have written a java.lang.Objectclass, so the system will be more Object, so that Java programs can not guarantee the most basic behavior, the program will become very confusing.

2. Delegate mechanism to break the parent class parents

  1. jdk1.0 emerging class loader, the parent class parents delegate mechanism is jdk1.2 arise, forward-compatible
  2. Hot deployment: hot deployment of each class will form a class loader, a number of class loader forming a network structure , thereby destroying the parent parent delegation mechanism
  3. Root class loader loads the contents of rt.jar, and the contents rt.jar Once loaded, the corresponding end of this operation, but the contents will be used to some third-party rt.jar jar package, this time on We need to reverse delegate thread class context class loader to load the reverse of these elements, such as jdbc driver problem.

Guess you like

Origin blog.csdn.net/wjl31802/article/details/91360969