The compilation and execution of a Java program is as follows:. java--compiles the-->. Class ClassLoader is responsible for loading individual bytecode files (. class) after loading. class, executed by the execution engine, which requires the runtime data area to provide data during execution
According to the JVM specification, JVM memory is divided into five parts: virtual machine method area, heap, stack, program counter, local method stack.
PC Register (program counter): Used to record the current thread at the time of the runtime, each thread has a separate program counter, thread blocking, recovery, suspend and so on a series of operations require the participation of program counters, so must be thread-private.
Java Virtual machine stack: Created when a thread is created, used to store stack frames, and therefore thread-private. When a method in a Java program executes, a stack frame is created to store the temporary data and intermediate results of the method runtime, including local variable tables, operand stacks, dynamic links, method exits, and so on. These stack frames are stored on the stack. Throws a Stackoverflowerror exception if the stack depth is greater than the maximum depth allowed by the virtual machine. Local Variables table: A local variable list of methods, written at compile time on the class file operand stack: int x = 1; You need to push 1 into the operand stack, and then assign 1 to the variable x
Java heap: The Java heap is shared by all threads, and the primary role of the heap is to store objects. Throws a OutOfMemoryError exception if the heap space is not sufficient, but the extension cannot request enough memory.
Method Area: The square hair area is shared by each thread, which is used to store information such as static variables, running frequent pools, and so on. Local method Stack: The main function of the local method stack is to support the native method, such as calling C + + in Java
1.Java is one of the advantages of garbage collection compared with C language.
One advantage of Java compared to C is that the memory space can be allocated and reclaimed automatically through its own JVM.
The garbage collection mechanism is implemented by the garbage collector garbage collection, which is a low priority daemon in the background.
Run automatically when the memory is low to a certain limit, so the time of garbage collection is indeterminate.
2. Why this design (GC recovery time is not fixed, automatically run).
Because the GC also consumes resources such as CPU, if GC execution is too frequent, it will have a significant impact on the execution of Java programs, thus implementing an irregular GC.
3. Are all automatically recycled through GC?
No, the garbage collection GC can only recycle the memory that was requested through the New keyword (on the heap), but the memory on the heap is not allocated entirely through the new request.
There are also local methods that can cause memory leaks if they are not manually released, so the GC method needs to be used in finalize with local methods (Nativemethod) such as free operations.
4. What is rubbish.
References between objects can be abstracted into a tree structure, where the root (GC Roots) is used as a starting point, and when an object to the GC Roots is not connected to any reference chain (unreachable), the object is proved to be a recyclable object.
There are three kinds:
(1) The object referenced by the local variable table in the stack frame.
(2) The objects in the method area that are referenced by the class static properties and constants.
(3) The object referenced by Jni (native method) in the local method stack.
"Examples of rubbish generation"
1. Change the reference of the object, such as null or point to another object
Object obj1 = new Object ();
Object obj2 = new Object ();
Obj1 = Obj2; Obj1 become rubbish
obj1 = Obj2 = null; Obj2 become rubbish
2. Reference type:
Strong reference: Is the most difficult to be collected by GC, rather the virtual machine throws an exception, interrupts the program, and does not reclaim the instance object that the strong reference points to.
Strong reference (point to instance object, existing heap) there is not enough memory to use OutOfMemoryError will not be recycled
Object Obj=new object ();
Soft Reference (SoftReference), in the case of low memory, the GC reclaims the object pointed to by the soft reference (soft reference can be used to implement memory-sensitive caching.) )
Soft references can be used in conjunction with a reference queue (Referencequeue), and if the soft reference references an object that is garbage collected, the Java Virtual machine adds the soft reference to the reference queue associated with it.
Soft references
String str= "Hello Yihaha";
softreference<string> soft=new softreference<string> (str);//Convert a strong reference to a soft reference
System.out.println (Soft.get ());
Weak references (weakreference), regardless of the insufficient memory, as long as I GC, I can reclaim the weak reference to the object (. However, because the garbage collector is a very low priority thread, it is not necessarily easy to find those weakly referenced objects soon. )
Weak reference
weakreference<string> wreference=new weakreference<string> (str);
System.out.println (Wreference.get ());
3. After each execution of the loop, the generated object object becomes recyclable
for (int i=0;i<10;i++) {
Object obj = new Object ();
System.out.println (Obj.getclass ());
}
A virtual reference (phantomreference) that must be used in conjunction with a reference queue (Referencequeue).
When the garbage collector discovers that an object has a virtual reference, first executes the Finalize () method of the referenced object, adding the virtual Reference object to the reference queue before reclaiming the memory.
You can see whether the object is going to be garbage collected by judging whether the reference queue has that virtual reference object.
You can then use the virtual reference mechanism to accomplish some of the work before the object is recycled. (Note: When the JVM inserts a virtual reference into the reference queue, the object memory that the virtual reference executes is still present.) However, Phantomreference does not expose API return objects.
So if I want to do cleanup work, I need to inherit the Phantomreference class so that I can access the object it points to. )
Virtual reference
Referencequeue<string> queue=new referencequeue<> ();
Phantomreference<string> phantomreference=new phantomreference<string> (str,queue);
System.out.println (Phantomreference.get ());
4. Class nesting
Class a{
A A;
}
A x = new A ();//Allocate a space
X.A = new A ();//And a space is allocated.
x = null;//generates two garbage
5. Garbage in the thread
CALSS A implements runnable{
void Run () {
//....
}
}
Main
A x = new A ();
X.start ();
X=null; X object is considered garbage after thread execution completes
5. How to efficiently carry out garbage collection.
Reference counting method
The reference counting method is the most classic one of the garbage collection algorithms. The implementation is simple, for a object, as long as any object references a, then A's reference calculator adds 1, when the reference is invalid, the reference counter is reduced by 1. Object A can no longer be used if a reference counter value is 0.
Disadvantage: The problem of circular references cannot be handled, so the algorithm is not used in the Java garbage collector
The reference counter requires an addition operation and subtraction for each reference generation and elimination, which will have a certain impact on the system performance.
Mark-sweep (Mark-purge) algorithm
The tag-purge algorithm is divided into two phases: the marking phase and the purge phase.
The task of the mark phase is to mark all objects that need to be reclaimed, and the cleanup phase is the space occupied by the object being tagged.
The tag-purge algorithm is easy to implement, but one of the more serious problems is that it is easy to generate memory fragmentation, and too much fragmentation may cause the GC to be triggered in advance by the need to allocate space for large objects in a subsequent process.
Copying (copy) algorithm
The copying algorithm divides the available memory by capacity into two blocks of equal size, using only one piece at a time. When this piece of memory is exhausted, the surviving object is copied to another piece.
The first block of memory is then cleaned up so that it is not easy to have memory fragmentation problems and is running efficiently.
But the algorithm reduces the amount of memory that can be used to half the original. Moreover, the efficiency of the algorithm is very much related to the number of the surviving objects, if there are many surviving objects, then the efficiency of the copying algorithm will be greatly reduced.
Mark-compact (labeled compression) algorithm
In order to solve the defects of copying algorithm and make full use of memory space, a mark-compact algorithm is proposed.
The algorithm tag phase marks all the objects that need to be reclaimed, but instead of cleaning the recyclable objects directly after the tag is completed, the surviving objects are moved to one end, and then all the memory outside the dropped bounds is cleared (leaving only the surviving object).
Generational Collection (generational collection) algorithm
The core idea is to divide the heap division into old age (tenured Generation) and Cenozoic (young Generation), the old age is characterized by a small number of objects to be recycled each time garbage collection, and the new generation is characterized by each garbage collection has a large number of objects need to be recycled, Then you can take different collection algorithms that are most appropriate for different generations.
The new generation adopts copying algorithm. But it is not divided into two of the same size space, is to divide the Cenozoic into a larger Eden space and two small survivor space (from space, and to space) (proportional 8:1:1) each use Eden space and survivor from space, when recycling,
Copy the surviving objects into the survivor to space, and then clean out Eden and from space. After the first GC, the Eden area and from are emptied, from and to swap roles, and the next GC will replicate the surviving objects to the to space, looping back and forth.
The Cenozoic recovery occurs when the Cenozoic memory is full, or the remaining memory is less than the volume of the object to be new. A new generation of GC is occurring at this time.
The old age adopts the labeling compression algorithm. It has the advantage of being simple and efficient, but the downside is that it can bring a pause to the user.
Old age recycling occurs when the remaining memory cannot load a new generation of surviving objects and cannot load large objects (large objects go straight into the old age).
The method area has a permanent generation, which is used to store class files, static objects, method descriptions, and so on. Recycling for a permanent generation mainly reclaims two parts: discarded constants and unwanted classes.
Persistent generation size through-xx:maxpermsize=< N> is set up.
Note: When an object escapes a GC in the Survivor area, the age of the object is added by 1, by default, when the object ages to 15 (or when Survivor to space is full) will move to the old age. In general, large objects will be directly assigned to the old age, the so-called large object refers to the need for a large number of continuous storage space objects, the most common one of the big object is a large array, such as: byte[] data = newbyte[4*1024*1024].
Partitioning algorithm
Algorithm thought: The partition algorithm divides the entire heap space into the continuous different cell, each individual area uses independently, the independent recovery.
The advantage of the algorithm is: You can control how many small interval recovery
Generally, the larger the heap space is, the longer the time required for a GC, and thus the longer the pause time is generated. In order to control the pause time produced by GC, a large memory area is divided into several small blocks, each reasonable recovery of several small intervals, rather than the whole heap space, can reduce a GC pause time according to the target pause time.
6. About the collector introduction.
For the Cenozoic copying algorithm,
The Seria l collector is single-threaded and must suspend all user threads when it is garbage collected.
The Parnew collector is a multi-threaded version of the serial collector, which, in a single CPU or even two CPU environments, cannot guarantee performance beyond the serial collector due to the overhead of thread interaction.
Parallel scavenge, a new generation of multi-threaded collectors (parallel collectors), is primarily designed to achieve a manageable throughput
For older generations, using the mark-compact algorithm,
Serial old: Single-threaded, older versions of serial collectors.
Parallel Old multi-threaded controllable throughput (older versions of Parallel scavenge collectors)
The CMS (current Mark Sweep) collector uses the tag-purge algorithm, and the memory fragmentation problem is unavoidable. is a concurrent low pause collector. (You can use-xx:cmsfullgcsbeforecompaction
Set up several CMS recoveries, followed by a memory defragmentation. )
The G1 collector is the most cutting-edge achievement of today's collector technology, and it is a collector for service-side applications, making full use of multiple CPUs and multi-core environments. So it is a parallel and concurrent collector, and it can establish a predictable pause time model.
7. About GC types.
There are only two major types of GC that are accurately classified:
Partial GC: The pattern of the entire GC heap is not collected
Young GC (Minor GC): A GC that collects only young gen (triggered when the Eden area in young Gen is allocated full). )
Old GC (Major GC): GC that collects only old Gen. Only CMS concurrent collection is this mode
Mixed GC: Collects GC for whole young Gen and part old Gen. Only G1 has this pattern.
Full GC: The pattern of all parts of the entire heap, including young Gen, Old Gen, Perm Gen (if present), and so on.
(When young GC is ready to trigger, the full GC is triggered when the data in the young GC is stored in the older generation is larger than the remaining storage space in the older generation, or when there is not enough space to allocate space in the persistence generation)
Finishing from: https://blog.csdn.net/seu_calvin/article/details/51892567
https://blog.csdn.net/lojze_ly/article/details/49456255https://blog.csdn.net/u010429424/article/details/77333311