Java Virtual machine

Source: Internet
Author: User

Java memory model

Program counter
Small memory space in memory, the value of the counter can choose the next execution of bytecode instructions, branch, loop, jump, exception handling, thread recovery and other basic functions need to rely on this counter to complete.

The thread is private, with the same life cycle as the thread.

If you are executing a native method, this counter value will be empty.

Virtual Machine Stack
The thread is private, with the same life cycle as the thread.

Each method creates a stack frame at the same time to store information such as local variable tables, operand stacks, dynamic links, method exits, and so on.

In the Java Virtual Machine specification, there are two exceptions to this area: if the thread requests a stack depth greater than the virtual machine allows, the STACKOVERFLOWERROR exception will be thrown;
If the virtual machine stack can be dynamically extended, the OutOfMemoryError exception is thrown if the extension cannot request enough memory.

Local method Stack
Similar to what the virtual machine stack does, the difference is that the virtual machine performs Java (that is, bytecode) service for the virtual machine, while the local method stack is the native method service used by the virtual machine.

Java heap
Used to hold object instances, the largest chunk of memory managed by a Java virtual machine, and a chunk of memory shared by all threads.

Because the Java heap is the main area of garbage collector management, it is often referred to as the "GC" heap. Since the collector basically uses the Generational collection algorithm, the Java heap can also be subdivided into

Cenozoic
Old age
Permanent generation (permanent generation is a unique concept of the Hotspot virtual machine, is an implementation of the method area, the other JVM does not have this thing.) In Java 8, the permanent generation is completely removed and replaced by another piece of local memory-the meta-space that is not connected to the heap. )
When an object is created, it first enters the Cenozoic, and then it may be transferred to the old age.

The new generation holds a large number of short-lived objects, so the new generation has the highest frequency of garbage collection in three regions. For more efficient garbage collection, the next generation continues to be divided into the following three spaces:

Eden
From Survivor
To Survivor
Method area
Like the Java heap, the memory regions shared by each thread store the class information, constants, static variables, even the compiler-compiled code, that have been loaded by the virtual machine.

Run a constant-rate pool
A part of the method area that holds the various literal and symbolic references generated by the compiler.

Another important feature of running a constant pool relative to a class file's const pool is its dynamic nature, and the Java language does not require constants to be generated only at compile time, which means that the contents of the constant pool in the class file are not pre-placed to enter the method area to run the frequent pool. It is also possible to put new constants into the pool during the run, which is the intern () method of the String class, which is used by developers more.

Direct Memory
In JDK1.4, a new NiO class is introduced, which introduces a channel-to-buffer I/O method that can allocate out-of-heap memory directly using the native library, and then operate on a Directbytebuffer object stored in the Java heap as a reference to this memory.
Directbytebuffer of out-of-heap memory

Hotspot Virtual Machine Object
Creation of objects
At the language level, creating an object is usually just a new keyword, and when the virtual opportunity is executed to a new one, it is a step:

Checks if the class is loaded, parsed, initialized, and does not perform the corresponding class loading process first.
allocating memory in the heap

Dividing free space:

Pointer collision: Heap Memory normalization
Idle list: Heap memory is not structured
Concurrency issues

Synchronization: Using CAs with failed retries to ensure atomicity of the update operation
Divide the memory allocation action into different spaces according to the thread
Initializes a 0 value to the allocated memory space
Sets information such as the class instance, metadata, hash code, GC generational age, and so on for an object.
Implementation <init> Methods
Memory layout of the object
The layout of objects stored in memory can be divided into 3 areas:

Object Header

Object runtime data, hash code, GC generational age, lock status tag, thread-held lock, biased thread ID, etc.
Type execution: An object that holds a pointer to its class metadata, indicating which instance of the object's data class.
Instance data

Valid information that the object is actually stored
Snap To fill

Placeholder Action
Access positioning of objects
Handle positioning
Direct pointer
Garbage collector
The three zones of program counters, virtual machines stacks, and local method stacks are thread-private, exist only during the lifetime of the thread, and disappear after the thread ends, so there is no need for garbage collection of these three areas. Garbage collection is primarily done for the Java heap and the method area.

Judging if the object is dead
Reference counting algorithm
Add a reference counter to the object, each time there is a place to reference it, the counter value is added 1, the reference time limit, the calculator value minus 1, when the counter value of 0 is not possible to use the object.

When two objects reference each other, the value of the reference counter is never 0, which prevents them from being garbage collected.

public class REFERENCECOUNTINGGC {
Public Object instance = null;

    public static void testGC() {        ReferenceCountingGC objA = new ReferenceCountingGC();        ReferenceCountingGC objB = new ReferenceCountingGC();        objA .instance = objB ;        objB .instance = objA ;        objA = null;        objB = null;        System.gc();    }}

Accessibility analysis algorithm
With GC roots as the starting point, the objects that can be searched are all alive, and unreachable objects are not available, starting from these nodes to search down.

In the Java language, the objects that can be used as GC roots include the following:

Objects referenced in the virtual machine stack
Objects referenced by static properties in the method area
Objects referenced by constants in the method area
The object referenced by the native method in the local method stack
Reference type
Whether the reference counting algorithm or the accessibility analysis algorithm determines whether an object is alive is related to the reference. After JDK1.2, Java extends the concept of references into four reference types with different intensities.

Strong references
By using new to create the object's reference type, the strongly referenced object is never reclaimed by the garbage collector.

Object obj = new Object ();
Soft references
It is implemented by the Sortreference class and is recycled only when there is not enough memory.

Object obj = new Object();SoftReference<Object> sr = new SoftReference<Object>(obj);obj = null;

Weak references
Implemented by the WeakReference class, only survives until the next garbage collection occurs.

Object obj = new Object();WeakReference<Object> wr = new WeakReference<Object>(obj);obj = null;

Weakhashmap's Entry is inherited from WeakReference, and is primarily used to implement caching.

private static class Entry<k,v> extends Weakreference<object> implements Map.entry<k,v>
The Concurrentcache in Tomcat uses WEAKHASHMAP to implement caching capabilities. Concurrentcache takes a generational cache, frequently used objects placed in Eden, and infrequently used objects in longterm. Eden is implemented using CONCURRENTHASHMAP, longterm uses weakhashmap to ensure that infrequently used objects are easily recycled.

Public final class concurrentcache<k, v> {

private final int size;private final Map<K, V> eden;private final Map<K, V> longterm;public ConcurrentCache(int size) {    this.size = size;    this.eden = new ConcurrentHashMap<>(size);    this.longterm = new WeakHashMap<>(size);}public V get(K k) {    V v = this.eden.get(k);    if (v == null) {        v = this.longterm.get(k);        if (v != null)            this.eden.put(k, v);    }    return v;}public void put(K k, V v) {    if (this.eden.size() >= size) {        this.longterm.putAll(this.eden);        this.eden.clear();    }    this.eden.put(k, v);}

}
Virtual reference
Also known as Phantom Reference or Phantom Reference, is the weakest reference relationship.

Implemented by the Phantomreference class, the sole purpose of setting a virtual reference association for an object is to receive a system notification when the object is reclaimed by the collector.

Object obj = new Object();PhantomReference<Object> wr = new PhantomReference<Object>(obj, null);obj = null;

Garbage collection algorithm
Mark Clear
The algorithm is divided into "mark" and "clear" two stages: first mark out all the objects that need to be recycled, after the mark is complete, all the tagged objects are collected uniformly.

Insufficient:

Efficiency issues, labeling and clearing two processes are not efficient
Spatial problems, the Mark cleanup generates a lot of discontinuous memory fragmentation.

Replication Algorithms
Divide the memory into two blocks of equal size, use only one of them at a time, and when this memory is used up, the surviving objects will be held on top of the other, and then one is to be sad to get rid of the memory space once.

Insufficient:

The cost is too high to use only half the memory.

Marker Grooming algorithm
First mark out all objects that need to be recycled, then move all the surviving objects to one end and finally clean out the memory outside the end boundary.

Generational collection Algorithms
Divides the memory into blocks based on the lifetime of the object. The Java heap is generally divided into the new generation and the old age, so that the characteristics of each age can be based on the most appropriate collection algorithm.

New Generation: Replication Algorithms
Old age: Marker grooming or marker cleanup algorithm.

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.