Java JVM basic knowledge

1.JMM Java Memory Model

   Each thread has its own working memory [Working Memory]
   Thread of working memory to save a copy of a copy of the main memory variable is used by the thread
   Threads among all the threads of the variables can not directly access the working memory of the other variables, the variable value passed between threads are required to complete the main memory.

 2.java heap and stack

1) stack heap: dynamically allocated memory space (memory space free record list is maintained by the operating system);       

    Wherein the memory can be recovered when not needed, to assign to the new memory request, which memory data is disordered ;
    Generally freely assigned by the user, malloc heap is allocated, need to manually release;
    It is shared by all threads in a memory area created when the virtual machine starts, the sole purpose of this memory area is stored object instance .

2) Stack stack: last-out data structure, usually a method for storing parameters (functions) of local variables;.

    In java, all basic and reference types are stored in the stack data in the stack in the living space in the current generally Scopes ({...} is the enclosed area).;

     After the first allocated memory must be released ;
    Generally assigned automatically by the system, storing the parameter value of the function, local variables are automatically cleared
3. Stack the local area method
 1) the method area Method Area: Java heap and, like, alias called Non-Heap (non-heap), each thread is a shared memory area;
          It is used to store class information has been loaded virtual machine, constants, static variables, the time compiler to compile the code and other data
  Runtime constant pool Runtime Constant Pool: Method part region;         
          Class file versions in addition to the classes, fields, methods, and interface description information, the information is also a constant pool (Constant Pool Table), and for storing various literal symbols compile generated reference, this part the method of operation of the content stored in the pool area of the time constant after the class is loaded
2) native method stacks Native Method Stacks: the use of virtual machines to Native Method Services
    Note: JVM composition

 4 . JVM run-time data area

  Program Counter: is a small memory, records where the current program run;

      Working bytecode interpreter is by changing the value of the counter byte code to select a next instruction to be executed , a branch, looping, branching, exception handling, and so need to rely on this reply thread counter to complete;

       If a thread is executing a main method, the counter records the address of the virtual machine bytecode instruction being executed;

      If you are performing is a local method, the value of the counter was empty;

      The only one in the Java virtual machine specification does not specify any area of abnormal situations OutOfMemoryError

 2 and 3 with reference to the remaining

 4.GC

  GC Garbage Collection: the object can be automatically exceeds the scope to achieve the purpose of automatically reclaims the memory

5. How to determine the recovery of the object

 1) Morgenthau algorithm: each object is seen as the root node, GC Roots, which is the root object , if there is no path to reach the root object from an object, or from the root object can not be a reference to the object that is unreachable of

      GC Roots objects:

    Object reference (local variable table stack frame) stacks in a virtual machine, the method performed each time, the JVM creates a corresponding stack frame (stack frame including operand stack, local variable table, runtime constant pool references);

        Method zone class objects referenced by static properties (static keyword), not belonging to any of these instances;

     Object methods district constant references (using the keyword static final);

            Native method stacks (Native Stack) reference object, JNI art method using Native

 2) Reference counting (currently not used)

   java In operation, when there is a reference to the place of the object instance, this object instance will be incremented by 1, decrements the time references fail, JVM memory during scanning, the reference count value is found to be garbage objects is 0, the count value is greater than 0 compared with active objects

6.Java memory leak

   The actual development, there may be useless but reachable objects, these objects can not be recovered GC, so will lead to memory leaks (OutOfMemoryError)
   Common memory leaks:
     Object 1) long life cycle of holding short life cycle of reference, it is likely there will be a memory leak
public class Test {
    Object object;
    public void test(){
        Object = new new Object ();
         // ... other code 
    }
}

 2) static collections like memory leaks using HashMap, Vector, etc. most likely to occur, and consistent application lifecycle these static variables, all objects Object can not be released because they will always be applied with Vector, etc.

   3 does not work) set inside the object when the attribute is modified, then call remove () method;

   4) all kinds of connections, database connections, network connections, IO connectivity does not appear close close call , (Connection can not be automatically recovered at any time, but once recovered Connection, Resultset and Statement objects will be immediately NULL);

   Note: minimize the use of static variables, life cycle and class class static variable synchronized;

    Clear and effective scoped memory object;

    Various connections (database connection, network connection, the IO connector) operation, make sure the display call close off;

    For the object is set manually without the use of a null value, regardless of GC when it will begin to clean up, we should be in a timely manner will be useless objects marked as an object to be cleaned

7.JVM garbage collection algorithm

   Java objects in the heap is divided into the old and the new generation's

 1) mark - sweep algorithm Mark-Sweep: First all need to be recovered objects, unifying all objects marked recovery after completion mark, but the mark and efficiency of the cleaning process is not high, it will produce a large number of clear mark after discontinuous memory fragmentation

        

  2) Mark - Collation Algorithm Mark-Compact: first mark all the recyclable objects and let live objects move toward one end, then clean out the direct memory other than the end border

        

  3) Copy Copying: jvm scan all objects, marking the object referenced by the root search algorithm, then will apply for a new memory space, copy the marked objects to the new memory space, live objects copied, it will clear the original memory space, the new memory most jvm object storage space, but at the cost of memory is reduced to half the original 

    

 4) recovering generational

      jvm common generational collection algorithm is recovered, the young generation to copy algorithm-based, finishing the old year to mark the main algorithm

      Younger generations are more objects, each garbage collection has a lot of garbage objects recovered, and as quickly as possible to reduce the short life cycle of an object, the object is less alive, so long as there is a copy flag of the object to another memory area the rest all clear, and the small number of replication, high efficiency;

     Old years younger generation of screening out the object, the object to be deleted is less clearly marked finishing with a higher efficiency

8.JVM garbage collector

The new generation of collectors : Serial, ParNew, Parallel Scavenge

Years old collector : CMS, Serial Old, Parallel Old

Whole heap Collector : G1

Parallel collection : refers to the number of threads in parallel garbage collection, but this time the user thread is still in a wait state.

Concurrent collection : refers to the user thread and garbage collection thread work at the same time (not necessarily parallel may be performed alternately). The user program continues to run, and garbage collection program running on another CPU.

Throughput : the ratio of the total time consumed CPU time and the CPU is used to run user code (user code to run a certain time = / (user code running time + time garbage collection)). For example: a virtual machine running a total of 100 minutes, the garbage collector to spend one minute, then the throughput is 99%

 1) Serial collector

     Serial;

     For the new generation of single-threaded collector using copying garbage collection algorithm;

  When Serial garbage collection, not just by a thread performs garbage collection, it collected at the same time, all the user threads must be suspended (Stop The World)

    Apply to virtual machines in Client mode, single-CPU
   

 2) ParNew collector

    Serial is a multi-threaded version, the other is no different with Serial;

 The same number of collection enabled by default and the number of CPU threads in a lot of CPU environment, you can use -XX: ParallelGCThreads parameter to limit the number of threads for garbage collection;

    The presence of Stop The World;

  Many preferred to run in a virtual machine under the Server mode, the new generation of collectors, in addition to Serial collector, currently only works with the CMS collector

  

 3) Parallel Scavenge collector

   Using the copy algorithm collectors, but also a parallel, multi-threaded collector;

  The difference with ParNew is ParNew goal is to shorten as much as possible when the garbage collection pause time user threads, Parallel Scavenge goal is to reach a throughput can be controlled ;

  GC adaptive: -XX: + UseAdptiveSizePolicy Open

      Provides two parameters for controlling a certain precision: XX: MaxGCPauseMillis controls the maximum pause time garbage collection 

                  XX: GCRatio size disposed directly calculated throughput is: 1 / (1 + n)

 4)Serial Old

       Serial old's version, is also a single-threaded collector, using mark - Collation Algorithm;

  Uses: Use in conjunction with Parallel Scavenge collector in JDK1.5 and previous versions;

     As a backup plan CMS collector

 5)Parallel Old

     Parallel Scavenge old's version, is a multi-threaded collection, the use of mark - Collation Algorithm;

  JDK1.6 has Parallel Old collectors can be used with Parallel Scavenge collector;

 JDK1.6 and later used in place of the old collector's Serial Old

   

 6)CMS(Concurrent Mark Sweep)

     For the shortest recovery time objectives pause collector, based on mark - sweep algorithm, concurrent collection, low pause;

  JDK1.5 introduced;

  CMS memory recovery is performed in conjunction with the user thread "concurrency"

  working process:

          1) Initial marker: Stop The World, marking only the initial GC Roots mark object can be directly linked to the very fast;

          2) concurrent mark: GC Roots Tracing of the process, and the user simultaneously turned GC thread, with a closure structure to record reachable objects to identify live objects and user threads can be executed concurrently;

          3) re-marked: because the user program continues to run during the correction concurrent mark which led to mark produced that mark recorded part of the object changes (using multiple threads execute in parallel to improve efficiency); require "Stop The World", and pause time stamp than the original longer, but shorter than the concurrent mark;

          4) Concurrent clear: open the user thread, while the GC thread starts to do the cleaning for the marked area, recycling all the garbage objects

      

    Disadvantages: very sensitive to CPU resources; can not handle floating garbage may appear Concurrent Model Failure failure caused another to produce Full GC; for the use of mark - sweep algorithm it will be a problem of space debris, resulting in a large object can not allocate space, not no advance trigger a Full GC

 7)G1(Garbage-First)

     jdk1.7 formally cited commercial collector in JDK1.9 has become the default collector;

     Extremely high probability of GC pause times meet requirements, but also have a certain high performance characteristics;

  Features:

        1) Parallel and Concurrent: G1 full advantage of the hardware can be in the CPU, multi-core environment, the use of a plurality of CPU (CPU or CPU core) to shorten the stop-The-World pause time. Some of the other collectors would otherwise require GC pause action Java thread execution, G1 collector still allows java through concurrent program continued to be implemented;

   2) generational collection:

    You can independently manage the entire GC heap (the old and the new generation's), without the need to mix with other collectors;
    can be processed in different ways at different times;
    while retaining generational concept, but the Java heap memory layout are very different;
    the entire stack is divided into a plurality of separate regions of equal size (region);
    CENOZOIC year old and are no longer physically separated, they are part region (not necessarily consecutive) set;
  3) spatial integration:

             On the whole, it is based on the mark - Collation Algorithm;

  •   From the local (between two Region) to see, is based on replication algorithms: no memory fragmentation, it is conducive to long-running;

       4) prediction can pause: G1 pursuing low except pause, the pause time can also create a prediction model; M can be explicitly specified within a millisecond time slice, time consuming garbage collection does not exceed N ms

                                Planned to avoid the entire Java heap garbage collection across the region; G1 tracking the size of garbage piled inside each Region, in the background to maintain a priority list, according to collect every time permits, priority recovery value largest Region; this you can get as high as possible to ensure that the collection efficiency in the limited time

    How G1 avoid scanning the entire stack: G1 Each Region has a corresponding Remembered Set ,, the virtual machine at the time of the discovery procedure Reference type write, will produce a Write Barrier temporarily interrupted write operation, check the reference objects Reference Region is in multiple (ie years old to check whether the object is referenced in the new generation), and if so, then by CardTable the relevant reference information recorded in the Region of Remembered Set the referenced object belongs. When the memory recovery, adding Remembered Set in the enumeration range GC root node can not guarantee there will not be a full stack scanning missing.

     Run the general process:    

           The initial mark : mark only GC Roots directly to the object, and change the value of TAMS (Next Top at Mark Start), so that the next phase of the user program to run concurrently, can create new objects in the correct available in the Region. (Need to pause the thread, but it takes very short.)

          Concurrent mark : begin to heap objects reachability analysis from GC Roots, find live objects. (It takes a long time, but may be complicated by the user program execution)

          The final mark : To mark a result of amendments made during the concurrent user program execution mark which led to that part of the record mark to produce change. And recording the change in the object inside thread Remembered Set Logs, the combined Remembered Set Logs Remembered Set inside the data. (Need to pause the thread, but can be performed in parallel.)

          Filter Recycling : The recycling value and cost of each Region to sort, to develop recycling programs according to user desired GC pauses. (Can be executed concurrently)

9. heap memory division
   Different objects, life cycle is not the same, and therefore the life cycle of different objects using different collection methods, can improve the efficiency of garbage collection 
   Serial serial, parallel parallel, and CMS, the heap memory is divided into three sections of a fixed size: the young generation (young generation), the old generation (old generation), and the permanent generation (permanent generation)

 

    1) the young generation Young Generation

            The new generation of objects          

           Is divided into three zones, a zone Eden, most of the objects generated in the region Eden, when Eden area is full, live objects are also copied to the Survivor areas (two in one), when this area is full Survivor, live objects in this area will be copied to another area of ​​Survivor, Survivor when this area was full when copying from the first Survivor over the area and this time also lived objects that will be copied to the old district (Tenured)         

          Note, Survivor of the two zones is symmetrical, has no relationship, so there may be objects from Eden over the same area at the same time, and a former Survivor copied object, and copied to the old area only from the first Survivor go over the object. Moreover, Survivor has a Chief is empty

    Meanwhile, according to program needs, Survivor region is configured as a plurality of (more than two), which may increase the time the object exists in the young generation, to reduce the old generation may be placed

   2) Old's Old Generation

        Longer life cycle of an object

        Experienced objects N times the garbage after the recovery is still alive in the young generation, the older generation will be put

  3) permanent generation Permanent Generation

      It used to store static files, and now Java classes, methods, and so on;

     There was no significant lasting impact on the generation of garbage collection, but some applications may call some or dynamically generated class, such as Hibernate, etc.

10. DESCRIPTION generational garbage recycling

.

 1) Eden District, the newly created object;

 2) When Eden is full (a certain percentage) can not create a new object, triggering garbage collection (minor GC), will clean out useless objects, and then copy the remaining objects to a Survivor, as S1, while empty the Eden area.

 3) When the Eden area is full again, the S1 of the object can not be emptied into another storage Survivor, as S2, while the Eden area of ​​the object can not be emptied, also copied to S1, and S1 to ensure Eden, It is empty.
 4) repeated many times (default 15) Survivor is not been cleaned objects will be copied to the old years Old (Tenured) area,
 5) When the Old district is full, it will trigger a once complete garbage collection (FullGC), before the new generation of garbage collection called (minor GC) 

  

Guess you like

Origin www.cnblogs.com/dxjx/p/12544717.html