[JVM Knowledge Framework of summary]

JVM memory distribution

  • Thread-shared data area:
    the method area -> class information, static variables
    heap -> array of objects
  • Thread quarantine
    virtual machine stack -> Methods
    native method stacks -> Local native method libraries
  • Stack, program counter
  • JVM operating data

Program Counter

Byte code line number thread in isolation, relatively small memory space, performed by the current thread is an independent execution units, the implementation of the only places without OOM by the CPU, maintained by the virtual machine, it will not appear OOM

VM stack

Java method is executed

Method call is the stack frame into a virtual machine stack during the stack frame: the local variable table (variable), the operand stack (storing a + b results), dynamic link (object reference address), the method outlet (value return of ) stack depth greater than the depth of the thread requested virtual machines allowed StackOverflowError

Native method stacks

Is a java execution memory area native methods, as there is a stack frame hotspot the Java Virtual Machine and native method stacks into one stack jvm java virtual machine is a standard native method stacks and stacks apart

stack

Java memory storage area object instance, almost all object instances are assigned here all the threads share the new generation, old years jmap -heap pid;

Methods district

Each thread shared memory area of ​​the memory has been loaded virtual machine information, constants, static variables, the time compiler to compile the code and other types of data Hotspot Implementation area with permanent-generation (let the garbage collector can management area), to recovery and uninstall constant pool area throws OOM, when he was unable to meet the needs of memory allocation

Runtime constant pool

Runtime constant pool is part of the zone method, Class field, in addition, the method, the interface of the constant pool, the amount of compiler-generated storing the literal and symbolic references, this part into the operating method of the time constant pool storage area loaded by the class .

StringTable structure HashSet method is part of the region, the method is limited by region, still OOM

Java object creation

-> static methods static block

  1. new instructions, the constant pool is determined there is no reference symbol, it has already been loaded through
  2. Determining whether the class is loaded, parsed, initialization
  3. For the new object is allocated in the heap memory java
    1) pointer collision (Comparative memory neat)

    : 1. 2. Move the pointer allocated memory, non-atomic step concurrency problems may arise, Java Virtual Machine CAS coupled by way of failure retry ensure atomic update operation
    2) the free list (chaotic memory)
    memory heap memory free address
    : 1. 2. modify allocated memory free list address non-atomic step concurrency problems may arise, Java virtual machine coupled CAS failure retry It means to ensure atomic update operations
  4. Will be allocated to the memory space is initialized to zero value
  5. Set object header information (GC generational Age, HashCode, metadata information of the object)
  6. carried out method

Java object memory layout

Attribute value of the object -> the first instance of the data object stored 64-bit 64-bit machine, the machine 32 memory 32, a multiple of 8

Accessing Java objects

  1. Direct access pointer
  2. Handle visit

    contrast:
  3. Access efficiency: High efficiency direct access pointer (Hotspot this way)
  4. Garbage collection: Handle high access efficiency, the garbage collector handle only update the pool, and direct access method will have to update the reference pointer address

Garbage collection algorithm

  1. Reference count

    when the object instance is assigned to a variable, the count variable is set to 1 when any other variable is assigned to the referenced object, counts +1 (a = b, then b object instance reference counter + 1) , when a reference to an object instance over the life cycle (executing the method) or set to a new value, the instance of the object reference counter of -1
    can not resolve the circular reference
    reachability analysis
    GC Root (VM stack object referenced objects referenced in native method stacks, the object attribute references the static method area, the method constant reference object region)
  2. Mark - sweep

    object tag need to be recovered, marking the completion of a unified recovery after
    less than:
    1. efficiency, marking two clear process efficiency is not high
    2. The space problem, a large number of discrete memory fragmentation mark after clearing, excessive debris when a program needs to allocate larger object, you can not find enough contiguous memory and had to trigger a garbage collection action in advance
  3. Mark - Copy

    copy live objects A memory block to memory block B (Survivor to), and then the memory block A (Eden + Survivor from) empty,
    only a small part of the object moves, the more the object is to be recycled
    Eden: from Survivor: =. 8 to Survivor:. 1:. 1
    98% target "death Chaosheng evening", the new generation memory is available to 90% (80% + 10%), 98% of the target is recycled general, when less than 90% when objects are recovered (10% or more of the objects survived), the Survivor to space is not enough, we need to rely on old's allocation guarantees
  4. Mark - finishing

    old's not suitable for replication algorithm
  5. 2. Additional copy operations increased 50% wasted space 3. often require additional space allocation 4. Possible guarantee 100% survival of the old era objects

step:

  1. mark
  2. Finishing the survival of the object is moved to one end (top left), structured and never become regular, then clean out the direct memory outside the boundaries

Serial Collector

Single-threaded garbage collector, user threads to secure a tentative point first, and then single-threaded serial GC threads were, recycling and other GC threads finish, and then the user thread before continuing Features: Stop the world
scene: Desktop Applications (gc short time) with in the new generation, client terminal

ParNew collector

Multi-threaded version of the Serial collector for the new generation, and the only way to work with the CMS collector, running in server mode -XX: ParallelGCThreads limit the number of threads the garbage collector = CPU core number (excessive consumption can cause context switching) Parallel : multiple threads in parallel garbage collection, users still pending concurrent threads: the user thread garbage collector concurrently, user threads and garbage thread runs on a different CPU

Parallel Scavenge collector

New generation of collectors, copying algorithm, parallel multi-threaded collector concerns certain priority collector (throughput = CPU running user code execution time / CPU total time, for example: 99% of the execution time of the user thread, 1% recovery time garbage, then throughput 99%) high throughput can be efficient use of CPU time computing tasks to complete the program as soon as possible, suitable for operation in the background without too much attention to shorten the interaction task CMS garbage collection pause time for the user interactive program, a good response rate can improve the user experience -XX: MaxGCPauseMillis GC pause time parameters, parameter is too small will frequently GC-XX: GCTimeRatio parameters, the default of 99% (accounting for 99% of the time user threads total time of CPU)

Serial Old collectors

Serial is a collector's version of the old single-threaded years old collector, a "mark - finishing" algorithm

Parallel Old collectors

Is the Parallel Scavenge collector's version of the old multi-threaded years old collector, a "mark - finishing" algorithm

CMS collector

Obtaining the shortest recovery time for the desired pause collector, a "mark - sweep" algorithm, in response to a system for Internet attention, B / S system

step:

  1. The initial mark (and not user threads run together, time-consuming short) - marking what objects can be linked directly to the GC Roots, very fast
  2. (And user threads run together, time-consuming) concurrent mark - concurrent marking phase is carried out GC RootsTracing, looking for GC reference chain
  3. Relabeled (not run with the user thread, short time-consuming) - To mark the correction period due to concurrent user threads lead to marked changes generated record mark
  4. Concurrent clear (and user threads run together, time-consuming) - scanning the entire memory area

Disadvantages:

  1. Very sensitive to CPU resources (concurrent mark phase for a long time, taking up the user thread CPU time)
  2. Can not handle floating garbage (the program during concurrent clear, user thread generated new garbage)
  3. Mark - sweep generation of space debris

G1 collector

The garbage collector for server applications Region-> Remembered Set (solve circular references)
check Reference (program type of reference write operation, check the reference reference types) steps:

  1. Initial labels - GC Roots object tag can be directly linked to the
  2. Concurrent mark - began to heap objects from GC Root reachability analysis to identify live objects, this stage takes a long time, but may be complicated by the user program execution
  3. The final mark (Remembered Set Logs-> Remembered Set) - corrected during concurrent mark due to the continued operation of the user program which led to marked changes in that part of the generated record mark, the virtual machine will be recorded in this period of time the object changes inside thread Remembered Set Logs, the final stage marks the need to merge Remembered Set Logs data into Remembered Set in
  4. Filter Recycling (Live Data Counting and Evacuation) - only need to scan Remembered Set
    advantages:
  5. Between the use of replication algorithm - "refresh tag" Based on the main and Region
  6. Predictable pause, pause time is reduced, but the G1 apart from the pursuit of low pause, the pause time model can establish predictable
  7. G1 directly on the Java heap for recycling Region (Cenozoic years old is no longer physically separated, they are part of the Region)
  8. Predictable pause time model, G1 track individual Regions inside the garbage accumulation value size (space recovery and recycling obtained the required experience time) in the background to maintain a priority list, according to each collection time allowed, priority recovery value largest Region

Heap memory allocation

Java heap distribution

Object allocation rules:

  1. The main objects of the new generation Eden partitioned region (region Eden, to copy live objects From To region area, region Eden, From zone is recovered, then copied to the target region From To area, then the next garbage collection)
  2. If you start a thread-local buffer allocation, priority will be allocated on the thread TLAB
  3. In rare cases it may also be directly assigned to the old year (From and To fit directly into the area of ​​the old year)

Large object allocation

Large objects are Java objects requires a large amount of contiguous memory space, the most typical is the kind of large objects is a long string, and an array of -XX: PretenureSizeThreshold Settings object is greater than the value assigned directly in the old era, in the Eden area and avoid a lot of memory replication occurs between two Survivior area

Analysis of the dispensing stack and escapes

Escape Analysis: analyte dynamic scope, when an object is defined in the method, it may be referenced by an external method, called Method escape. It may even be external thread access to, such as assignment to a variable or class instance variables accessed by other threads, called threads escape. Allocated on the stack: the process variables and objects directly allocated on the stack, automatically destroyed after the method completes, the garbage collector does not require intervention, thereby improving the system performance -XX: + DoEscapeAnalysis open escape analysis (jdk1.8 by default) - XX: -DoEscapeAnalysis close escape analysis

command

  1. ps -ef | grep java
  2. jps -m (startup parameters) -l (class name) -v (JVM parameters)
  3. jstat -gc 27660 250 20 monitor virtual machines running various state information
  4. jinfo 27660 view and adjust the process virtual machine (not displayed specified) parameter information
  5. jmap raw heap dump snapshot -XX: + HeapDumpOnOutOfMemoryError
    jmap -heap 9366;
    jmap -histo 9366 | More; display objects in a heap statistics
    jmap -dump: format = b, file = / Users / mousycoder / Desktop / a.bin 9366 generated dump file
    -Xmx20m -XX: + HeapDumpOnOutOfMemoryError -XX: HeapDumpPath = / the Users / mousycoder / Desktop /
    the jhat /Users/mousycoder/Desktop/java_pid9783.hprof graphical analysis Heap
    SELECT s.toString () from java.lang.String S WHERE ( s.value! = null && s.value.length> 1000 )
  6. jstack thread snapshots (stack collection methods within each virtual machine executing thread, the main thread is used to locate the problem)
    shutdownHook before closing the tasks performed
    jstack -l -F pid forced output

Thread State

  1. NEW
  2. RUNNABLE
  3. BLOCKED blocking a passive waiting for a blocking monitor thread in this state (Entry Set)
  4. WAITING is a waiting indefinitely for another thread to perform a particular action of the thread is blocked in this state (Wait Set) initiative explicit application
  5. TIMED_WAITING is a limit waiting for another thread to perform an action thread in this state
  6. TERMINATED thread completes a excution

JConsole

JMX-based visual monitoring, management tools JMX open port nohup java -Xms800m -Xmx800m -Djava.rmi.server.hostname = 192.168.1.250 -Dcom.sun.management.jmxremote.port = 1111 -Dcom.sun.management.jmxremote. ssl = false -Dcom.sun.management.jmxremote.authenticate = false -jar hc-charging-server.jar &

Internet development process Jconsole memory analytical thinking process

FullGC

Minor GC: When the Eden area is full, trigger Minor GCFullGC:

  1. Call System.gc () is recommended virtual machines Full GC, by -XX: RMI calls to hex System.gc + DisableExplicitGC ()
  2. Old's lack of space for large objects directly into the old era, long-lived objects into the old era, when space is still insufficient after the implementation of Full GC, then dished out OutOfMemoryError, in order to avoid the above reasons caused Full GC, as far as possible when tuning to make objects Minor GC stage is recovered, so that objects in the new generation of multi survive for some time and do not create too large objects and arrays
  3. Space allocation guarantees failure using the copy algorithm Minor GC memory space required as security for old age, if a failure occurs HandlePromotionFailure guarantee, it will trigger Full GC
    suggestions:
  4. -Xmx size reduction, shortening time GC (larger heap memory is provided, the longer the time Full GC pause time will be longer)
  5. Cluster deployment

Internet issues

  1. Whitelist problem
    Solution: list.contain-> set.contain-> Bloom filter (large users and user system a small amount of solution is not the same)
  2. Deadlock
    Solution: jstack and bring new thread name
  3. Heap memory leak
    FullGC appear normal frequency of 1 to 2 times a day
    Solution: jmap, heap dump on oom + jhat
  4. Heap external memory leaks
    heap heap usage is very low, but there OOM and Full GC
    Solution: btrace

Study Tips

  1. Knowledge System
  2. Before the interview facie knowledge maps
  3. Insist on victory

Guess you like

Origin juejin.im/post/5d91972ae51d457825210a50