Deep Java Virtual Machine (ix)--FAQ Summary

Source: Internet
Author: User
Tags compact

1. JVM Runtime Memory structure

1. As constituted. The Runtime Data area has the following areas, where the PC program counter, the virtual machine stack, and the local method stack are thread-exclusive, and the heap and method areas are thread-shared. The classload is used to load the class file, the execution engine executes the program, and the local method interface calls the Local method library.

2.java stack is simple, each of which is a stack frame, each stack frame is composed of three parts. Local variable area, operand area, and frame data area. A local variable is a memory area that is managed as an array, and the No. 0 bit is the this reference to itself, and the rest is the base data type and the reference type and the returnedaddress type. The operand area is not accessed through an index, accessed by a stack of stacks, and is a storage area for temporary data, such as mathematical calculations. The frame data area is a pointer to a constant pool that accesses constant pool data when constant data is required.

3. Shared memory Area: divided into permanent space, old space, from survivor, to Survivor and Eden. The premanent includes runtime constant pool and loaded class information and method information. Old space (tenured generation) contains long-lived objects. The from Survivor and Eden store objects that are relatively short lived, and to survivor are used to replicate saved surviving objects.

4.JVM parameter settings.

Heap:

-XMX: Maximum heap memory, such as:-xmx512m

-XMS: Initial heap memory, such as:-xms256m

-xx:maxnewsize: Max Young area Memory

-xx:newsize: initial young area memory. Typically, the Xmx is 1/3 or 1/4. New generation = Eden + 2 Survivor space. Actual free space = Eden + 1 Survivor, or 90%

-xx:maxpermsize: Maximum persistent with memory

-xx:permsize: initial persistent with memory

-xx:+printgcdetails. Print GC Information

-xx:newratio the new generation and the old age ratio, such as –xx:newratio=2, then the Cenozoic accounted for the entire heap space of 1/3, the old age accounted for 2/3

The ratio of Eden to Survivor in the Cenozoic of-xx:survivorratio. The default value is 8. That is, Eden accounts for 8/10 of the Cenozoic space, and another two survivor 1/10.

Stack:

-XSS: Sets the stack size for each thread. jdk1.5+ each thread stack size is 1M, generally, if the stack is not very deep, 1M is absolutely enough.

2. Object and memory overflow.

1. Object.

A Create. First check that the parameters of the instruction can find the symbol reference of the class in the constant area, and check whether the class is loaded, parsed and initialized, and if not, execute the loading process of the class. Next is the memory allocation, the class load knows to allocate the memory size, the allocation method has two, one is a pointer collision, is a piece of memory is used, a piece is unused, with a pointer to split, the new allocated memory pointer to the idle move, compact function of the virtual machine is a pointer collision Another is the idle list, which is a list of idle memory blocks, constantly updating the list, the newly allocated memory in the list looking for a suitable size block of memory, the sweep function of the virtual machine is to use the idle list. Thirdly, concurrency is also considered when allocating memory space. There are two methods, one is synchronous processing, such as the use of CAs and failure retry method, the other is to divide the memory allocation action according to the thread in different space, each thread in the heap pre-allocated a small block of memory, the local thread allocation buffer Tlab, the thread needs to allocate memory on that Tlab allocation, Only when the Tlab is used up, it is needed to synchronize the lock and reassign. Make the necessary settings for the object, for example, the object belongs to that class, how to find the metadata information of the class and object Hashcode, and the object GC generational age.

B The memory layout of the object. Divided into object headers, instance data, and alignment fills. The object header consists of two parts, the first part is storing the object's own information, such as HASHCODE,GC age, lock state, etc. the second part is a pointer to the type, the object points to the metadata of its class, and the virtual machine determines that this is an instance of that class by this pointer.

C Object access targeting. In two ways, a handle is accessed, a handle pool has pointers to access object instance data, and a pointer to an object data type. The greatest benefit of this visit is that reference is a stable handle pool address, and the object change is to change the pointer inside the handle pool, while the reference itself does not move. The other is a direct pointer, which has pointers to object type data and instance data. The benefit of this visit is that it is faster and saves the overhead of a pointer location.

2. Memory overflow oom.

A Heap overflow. Heap is the object instance, as long as the object is constantly created, and to ensure that the GC root to the object has a large path to avoid the garbage collection to eliminate the object, then the number of objects reached the maximum heap capacity limit will be oom. Using the Memory image analysis tool, Eclipse Memory Analyzer analyzes.

B The virtual machine stack and the local method stack overflow. There are two types, one is to throw a Stackoverflowerror exception if the stack depth requested by the thread is greater than the maximum allowable depth of the virtual machine, and the other is to throw a OutOfMemoryError exception if the virtual machine cannot request enough memory space on the scale stack. You can reduce the maximum heap and stack capacity to get more threads.

C Method area and constant pool overflow. There will be additional hints PermGen space.

D Native Direct Memory overflow. This heap dump file does not see memory footprint, but if you have direct or brief use of NIO, it is possible that the native direct memory overflow.

3. GC algorithm.

1. The Judgment object can be recycled.

A The reference counter method. The object is quoted and one is added, minus one when it expires, and can be released at 0 o'clock. The disadvantage is that the GC does not release when it has a ring.

B GC Root. Starts with the root object and then searches down based on the associated relationship. If the root object cannot find any paths to connect to, it is judged that the object can be reclaimed. There are four GC root selections: The Reference object in the virtual machine stack, the static property Reference object for the class in the method area, the Const reference object in the method area, and the Jni reference object in the local method stack. The accessibility analysis algorithm marks the object, the default is the first mark, if the object does not implement the Finalize method, it is directly recycled; If the Finalize method is implemented, the first tagged object should be placed in a f-queue queue, The virtual opportunity then launches a finalizer thread to execute, and then the second token is made. Objects that are marked for the second time are recycled directly. If you want to live once, rewrite the Finalize method, and if you want to resurrect it, in finalize, associate yourself with any one, such as assigning yourself to a class variable or to a member variable of an object.

C Strongly referenced objects are not recycled at any time, and soft references are not recycled when memory is sufficient, softreference classes are not enough, and weak references are recycled directly when the virtual machine is reclaimed, weakreference. A virtual reference does not constitute any effect on the object, and is created to give the system a notification message when the object is reclaimed, phantomreference.

2. Garbage collection algorithm.

A Mark-Clear (mark-sweep). The disadvantage is that there is more memory fragmentation.

B Tag-Copy (mark-copy). Divides the memory into two pieces, and a piece of memory retains all copies of the object into another free memory. The disadvantage is that memory is halved. So the partition to achieve, EDEN,S0,S1, according to a certain proportion, the default 8:1:1 can be. This is minor GC, in general, the object in Eden to apply for space, when found not enough space, the occurrence of minor GC, will be the Eden and from survivor the reserved objects inside to survivor, and then empty the Eden and from Survivor memory and then swap from survivor and to survivor. If the to survivor space is not enough, the from Survivor object is copied directly to the old space, or some objects of sufficient age are copied directly to the older spaces. When the from survivor copies the object to the tenured zone, if the handlepromotionfailure is set (allowing the warranty to fail), only the minor GC is allowed, and if not allowed, the full GC is triggered.

C Mark-Organize (mark-compact). When finishing, clear out the objects that should be cleared, then compress the surviving objects to one end of the heap and discharge them sequentially. Full GC requires the entire heap to be recycled. Let's say tenured is full, the permanent is full, and System.GC shows the call, and it will happen. Permanent to recycle, a constant pool of constants and useless class information is generally recycled. All instances of the class are recycled, the ClassLoader of the loaded class has been reclaimed, and the class object is not referenced (it is not referenced by reflection) and the class is not recycled until the three are satisfied.

4. Garbage collector.

A Young space, Serial (its advantages are simple and efficient, but the disadvantage is that it will bring a pause to the user.) ) and Pranew (serial multithreaded version) and parallel scavenge (to achieve a controlled throughput).

B Old space, the Serial old (mark-compact) and Parallelold and CMS, a collector that targets the shortest recovery pause time, is a concurrency collector that uses the "mark-and-sweep" algorithm, The part that reduces the time to pause is to put the search for the concurrency tag on one thread.

C G1 (mark-compact). Make multiple regions of the same size for the entire heap, and then prioritize the reclaimed area.

5. class file structure.

A Magic number. Cafebabe. Coffee, baby.

B Minor version number and major version number, 1.7 is 51.

C The constant pool counter and the constant pool data area. The Constant pool table index is valid within 1-constant_pool_count, and the first one is pointing to null.

D Access flag, access_flags. Is mainly public final Super interface abstract enum and so on. is the access permission for a class or interface. There are methods and variables in the back, similar to this, but the flags are not exactly the same.

E. Class index, parent class index. This_class and Super_class.

F. interface counters and interface information data areas. Each of the interfaces implemented here has an interface information data area, starting from No. 0 to Interfaces_count.

G Field counter and field information data area. All field information for the class is saved.

H. Method counter and method information data area. All method information for the class is saved.

I. The property counter and the property information data area. Save the property sheet. Commonly used is the code,deprecated,constantvalue,exceptions and so on.

6. Load the class.

A Load, find, and import class files. Load general time: 1. If a class is not initialized in three cases, initialize: A.new an object, B. Reads and sets a static field (except for the final decoration), C. Calls the static side of a class. 2. When the package is called by reflection, the class is initialized first if it is not loaded. 3. When a subclass of a class is called, its parent class initializes the parent class if it is not initialized. 4. When a virtual machine is started, a class containing the main method must be initialized first. 5. A Java.lang.invoke.MethodHandle instance concludes with a method handle of ref_getstatic, ref_putstatic, and Ref_invokestatic, And the class that corresponds to this method handle is not initialized, it should be initialized first.

B Links, divided into three steps. The first step is validation, which checks the correctness of the loaded class file data, including file format, metadata validation, bytecode validation, and symbol reference validation. The second step is the preparation phase, where the class variable (static) is allocated in the method area storage space. The third step is parsing, transferring the symbolic reference to direct reference, class and interface parsing, and parsing the field and interface methods.

C Initialization The class words of the restrictive constructor <clinit> then executes and then executes the <init> of the instance object, and of course the parent class's <clinit>; interface is executed first, without first executing the <clinit> of the parent interface. That is, the subclass calls the static code block of the parent class first, then the static code block of the subclass.

7. Class Loader

A, Bootstrap ClassLoader: Will be stored in the <java_home>\lib directory, or the path specified by the-xbootclasspath parameter, and is recognized by the virtual machine (only according to the name of the file, such as Rt.jar Class libraries with names that do not conform are loaded into virtual machine memory even if they are placed in the Lib directory. The startup ClassLoader cannot be referenced directly by a Java program.

B, Extension ClassLoader: Load the <java_home>\lib\ext directory, or all class libraries in the path specified by the Java.ext.dirs system variable. Developers can use the extension class loader directly.

C, Application ClassLoader: Responsible for loading the user class path (ClassPath) specified on the class library, developers can use directly.

D, working process: If a class loader receives a request for a class load, it first delegates the request to his parent ClassLoader to complete, and so is the classloader for each level, so all load requests should be routed to the top-level startup class loader. The child loader tries to load itself only when the parent loader has feedback that it cannot complete the load request (it does not find the desired class in the search scope).

E. Benefits: The Java class has a hierarchical relationship with precedence as its classloader. For example, the class Java.lang.Object, which is stored in Rt.jar, regardless of which class loader is loading the class, will eventually be delegated to the startup ClassLoader for loading, so the Object class is the same class in the various class loader environments of the program. Conversely, if the user writes a class named Java.lang.Object and puts it in the program's classpath, there will be several different object classes in the system, and the most basic behavior in the Java type System is not guaranteed and the application becomes chaotic.

8. Reflections.

A In the running state, all the properties and methods of the class can be known for any class, and any one of the objects can invoke any of its methods and properties; This dynamically acquired information and the method function of the dynamic call object are called the reflection mechanism of the Java language.

B There are three ways to get a class: 1. Class C1 =class.forname ("name"), 2.Class C2 = name.class;3.name n = new name (); Class C3 =n.getclass ();

C By getting the class, create its object, using Newinstance. Object o =c1.newinstance ();

D Get its properties and methods: Get all properties: field[] fs = C.getdeclaredfields (); Get the property specified, such as Get ID: FIELDIDF = C.getdeclaredfield ("id"); Of course, this get property is not public or private, if you use GetFields can only get the properties of public. The method is the same, just under the name change, Getdeclaredmethods, get the constructor is getdeclaredconstructors.

9. How to apply garbage collection in the program, pay attention to those problems.

A , release the reference of the useless object as soon as possible, and assign null value; B , use collection data types sparingly, such as arrays, trees, graphs, linked lists, and other data structures because GC more complex; C , avoid displaying the application array memory, have to display the application, as far as possible to accurately estimate its reasonable value; D , avoid creating and initializing a large number of objects in the class's default constructor, and prevent unnecessary waste of resources when calling the constructors of their subclasses; E , try to avoid forcing the system to do garbage collection, increase the system to do garbage collection of the final time; F , and try to improve the system performance by using the object pool technology in the appropriate scenario; G , try to do the remote method call class application development uses the instantaneous value variable, unless the remote caller needs to get the value of the instantaneous value variable.

Deep Java Virtual Machine (ix)--FAQ Summary

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.