Java Virtual machine

Source: Internet
Author: User

I. JMM memory model
1. Program counter: The line number indicator of the byte code executed by the current thread. Determine the next byte-code directive to execute by changing the value of the counter.
2.java Virtual machine stack: The memory model executed by the Java method, in which each Java method creates a stack frame to store information such as local variable tables, operand stacks, dynamic links, method exits, and so on.
3. Local Method Stack
4.java Heap: Storage object instance, heap can be subdivided into Cenozoic (Eden area and Survivor1, Survivor2) and old age
5. Method Area: Stores information such as the class information loaded by the virtual machine, constants, static variables, the code compiled by the instant compiler, and so on. Permanent generation
6. Run a constant pool: part of the method area.
7. Direct Memory
Two. Anomaly Determination

three. Algorithms
1. Object Survival decision algorithm,
1.1 Reference count: Adds a reference counter to the object, each time a place references it, the counter adds 1; When the reference fails, the counter is reduced by 1
1.2 Accessibility analysis algorithm: Through a series of GC roots as the starting point of the object, starting from these nodes to search down, search traversed the path called the reference chain, when an object to the GC roots no reference chain connected, the proof object is not available.
1.3 Four references: a strong reference, similar to object obj = new Object (), as long as a strong reference exists, the object is never recycled; soft references, useful but non-essential objects, before memory overflow exceptions, will attempt to reclaim such objects, weak references, garbage collection, regardless of the current memory is sufficient, will reclaim such objects; Virtual references cannot get object instances for virtual references.
1.4 objects require two tokens to be recycled, after an object has been analyzed for accessibility, there is no reference chain to the GC roots, then the first time is marked and filtered, and a Finalize () method is used to save itself.
2. Garbage collection algorithm
2.1 Mark-Clear
The first stage marks the object that needs to be reclaimed, and the second stage reclaims the tagged object.
The disadvantage of:1> marking and clearing inefficient,2> marks results in a large amount of discontinuous memory fragmentation.
2.2 Replication
Divide the memory into two blocks of the same size, one at a time, when the memory is exhausted, copy the surviving object to another memory, and then clean out the object used by this block of memory.
Advantage: High efficiency, no memory fragmentation
Disadvantage: The memory is reduced to half the original, the cost is too high, not suitable for high object survival (such as the old age)
At present, the commercial virtual machine adopts this algorithm, which is suitable for the object of Asao. The Cenozoic is divided into 8:1:1 (Eden:Survivor1:Survivor2), using only the Eden area and one of the survivor zones, when recycled, the surviving objects in the Eden and survivor are copied to another survivor zone, Then empty the Eden and survivor area.
2.3 Marking-Finishing
The first stage marks the object, the second stage organizes the tagged objects, the surviving objects move toward one end, and the objects outside the end boundary are cleared.
2.4 Generational collection algorithm
The Java heap is divided into the new generation and the old age, and the appropriate algorithms are used in each era. (The new generation uses the assignment algorithm, the old age uses the mark-sweep or the marker-collation algorithm)
Algorithm implementation of 2.5.HotSpot
2.5.1. Enumerating the root nodes
2.5.2. Security point: GC pauses can take place after the thread executes to a secure point.
How to let a thread run to a safe point when a GC occurs:
2.5.2.1. Steals interrupt (deprecated): Directly interrupts all threads, not the security point, resumes the thread, and runs to the security point.
2.5.2.2. Active Interrupt: Sets a flag for each thread to poll this flag for true-time automatic interrupt hangs.
2.5.3. Security Zone
For threads that handle the sleep and blocked states: Use a security zone to resolve, when a thread executes to code in safe region, signs itself into safe area, when this time
When the JVM initiates the GC, the thread that is marked safe region is not processed, and when the thread leaves the safe zone, it is necessary to determine if the system has completed the enumeration root node
Continue to execute, otherwise wait.
four. Garbage collector
1.Serial Collector, Serial old
Serial/serial old: Single-threaded collector, stop the world: runs when all user threads are paused, only garbage collection
Serial: Replication algorithm
Serial old: Markup Grooming algorithm

Advantages: Simple and efficient
Cons: Stop the World
Application scenario: In the new generation of client mode, the new generation occupies little memory space.
2.ParNew Collector
The new generation collector, the multi-threaded version of the serial collector, a new generation collector for virtual machines in server mode, for multicore CPUs. Serial and parnew can be configured for the CMS collector.
3.Parallel Scavenge,parallel Old
Parallel multi-threaded collectors, the collector's focus is different, the Parallel scavenge collector's goal is to achieve a controllable throughput. The time/cpu the CPU runs the user code is the total elapsed time.
Parallel Scavenge: Replication algorithm
Parallel old: Markup Grooming algorithm
Use in situations where throughput and CPU resource sensitivity are a priority.

4.CMS Collector
Service-oriented
A collector that targets the shortest recovery pause time.
Implementation based on the tag clearing algorithm for the old age
The entire process is divided into four steps:
4.1 Initial Tag: Mark the object that GC roots can relate to, stop the world, time is short
4.2 Concurrency token: The process of GC ROOTS tracing, executed concurrently with the user thread.
4.3 Re-tagging: Fixed an object tag record that caused the tag to cause a table movement during concurrent tagging because the user program continued to work. Stop the world, short time
4.4 Concurrent Cleanup: Cleans up garbage objects and executes concurrently with the user thread.
Pros: Concurrent collection, low pauses
Cons: 1. Very sensitive to CPU resources
2. Unable to handle floating garbage, handling concurrent Model failure failure: garbage generated during the concurrency cleanup phase is called floating garbage.
3. Generate memory Space fragmentation: +usecmscompactatfullcollection, open by default, defragment on full GC. -xx:cmsfullgcbforecompaction, after performing the number of uncompressed full GC, then perform a full GC with compression by default of 0, each time is full GC.
5.G1 Collector
Service-oriented
Collection process:
1. Initial tag: Mark the object that GC roots can be associated with, and modify the value of Tams (Next Top at Mark Start) to ensure that the user is able to execute concurrently in the correct available
Create new object in region, stop the world, time is short
2. Concurrency tag: The analysis of the objects in the heap, find the inventory objects, time can be executed concurrently.
3. Final tag: Fix the tag record that marks have changed during concurrent tagging because the user program continues to work. Stop the world, short time
4. Filter recycling: The recovery value and cost of each region are sorted first, and the recovery plan is based on the desired GC pause time.
Pros: 1. Concurrency and parallelism: G1 can take advantage of hardware advantages in multi-CPU and multi-core environments
2. Generational collection: No additional collector configuration is required to manage the entire GC heap independently, with different ways to manage newly created objects and old objects that have survived multiple GC.
3. Spatial integration: The overall view is based on the tag-collation algorithm. A partial view (between two region) is based on the replication algorithm.
4. Predictable pauses that allow the user to explicitly specify that the garbage collection time must not exceed n milliseconds in a length of M milliseconds
The principle of the G1 collector: the memory is divided into multiple independent regions of equal size (region) (so that the new generation and the old age are no longer physically isolated), G1 tracking the value of garbage accumulation in each regionn
Small (the amount of space available and experience of the time required to reclaim), maintaining a prioritized list in the background, prioritizing the recovery of the region with the largest value per time, based on the allowable collection times, ensuring G1
The collector can obtain the highest possible collection efficiency in a limited time.

6. Garbage collector parameters

Parameters Describe
Useserialgc Default value of the virtual machine running in client mode, when this switch is turned on, the collector combination for serial+serial old is used for memory reclamation
Useparnewgc When this switch is turned on, a collector for parnew+serial old is used for memory reclamation
Useconcmarksweepgc When this switch is turned on, the collector combination for parnew+cms+serial old is used for memory reclamation, and the Serial old collector will appear as a backup collector for concurrent Mode failure failure as a CMS collector
Useparallelgc Default value for virtual machine running in server mode, after you turn on this switch, use parallel scavenge+serial old collector for memory reclamation
Useparalleloldgc After you turn on this switch, use the collector combination of Arallel scavenge+parallel old for memory reclamation
Survivorratio The capacity ratio of the een region to the Survivor region in the Cenozoic, the default is 8, which represents eden:survivor=8:1
Pretenuresizethreshold Directly promoted to the object size of the old age, after setting this parameter, objects larger than this parameter will be allocated directly in the old age
Maxtenuringthreshold The age of the object to the old age. Each object is aged plus 1 after it has persisted once minor GC, and enters the old age when it exceeds this parameter value.
Useadaptivesizepolicy Dynamically adjusts the size of each area in the Java heap and the age of entry into the old age
Handlepromotionfailure Whether to allow the allocation of collateral failure, that is, the remaining space in the old age is not sufficient to cope with the extreme circumstances in which all the objects of the Cenozoic entire Eden and survivor area survive.
Parallelgcthreads Number of threads that are memory-collected when parallel GC is set
Gctimeratio The ratio of GC time to total time, with a default value of 99, which allows 1% GC time to take effect only when using the parallel scavenge collector
Maxgcpausemillis Sets the maximum pause time for the GC. Effective only when using the parallel scavenge collector
Cmsinitatingoccupancyfraction Set the CMS collector to trigger garbage collection after the old age space is used. The default value is 68%, which takes effect only when using the CMS collector
Usecmscompactatfullcollection Sets whether the CMS collector will perform a memory defragmentation once the garbage collection is complete. Effective only when using the CMS collector
Cmsfullgcsbeforecompation Set up the CMS collector to start a memory defragmentation after several garbage collection sessions. Effective only when using the CMS collector


7. Memory allocation and recovery policy
1. Object Precedence in Eden Assignment
2. Large objects directly into the old age
3. Long-lived objects go straight into the old age
The sum of objects of the same age in 4.survivor space is greater than half the size of the survivor space, and objects older than or equal to that age can go straight into the old age

Java Virtual machine

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.