Java Virtual Machine Summary: Java Virtual Machine

Source: Internet
Author: User
Tags java reference

Java Virtual Machine Summary: Java Virtual Machine
Jvm Memory Model

UProgram counters

UJavaStack(Virtual Machine Stack)

ULocal method Stack

UJavaHeap

UMethod Area and Its runtime pool

Garbage Collection Mechanism

U New Generation and old generation

U parameter settings

U garbage collection (Minor GC and Full GC) and collection Algorithm

U finalize (), reduce GC overhead, trigger conditions for main GC

U determines useless objects, four reference methods, and why garbage collection

U String, StringBuffer, and StringBuilder

U class loading mechanism

Class loading mechanism 1: jvm Memory Model

 

1. program counter (PC)

A Program Counter (Program Counter Register) is a small memory space. It can be seen as the row number indicator of the bytecode executed by the current thread, when the bytecode interpreter is working, it is to change the value of this counter to obtain the next bytecode instruction to be executed.

BecauseJavaThe multi-thread of a virtual machine is implemented by switching threads in turn and allocating the execution time of the processor. At any definite moment, a single processor (for a multi-core processor, a single kernel) only the commands in one thread are executed. Therefore, in order for the thread to be switched back to the correct execution position, each thread requires an independent program counter. The counters between each thread do not affect each other and are stored independently, we call this type of memory area"Thread privateMemory.

If the thread is executing a Java method, this counter records the address of the Virtual Machine bytecode instruction being executed; if the Natvie method is being executed, this counter value is null (Undefined ).

Note: The program counter is private to the thread. Each thread has an independent program counter.

2. Java stack (Virtual Machine stack)

Java stack is the memory model for method execution in Java. Each method createsStack frame(Next to stack frame), this stack frame is used to store information such as the local variable table, operand stack, dynamic link, and method exit. The process from calling to execution of each method is complete, it corresponds to the process of putting a stack frame into the stack of the Virtual Machine stack to go out of the stack.

Note: The Java stack is also thread-proprietary.

Exception possibility: There are two kinds of stack exceptions: If the stack depth requested by the thread is greater than the depth allowed by the stack, an StackOverflowError exception will be thrown. If the VM stack can be dynamically expanded, an OutOfMemoryError error will be thrown if sufficient memory cannot be applied during expansion.

Stack frame

1)Local variable table

2)Operand Stack

3)Integer addition

4)Return address

Third, local method Stack

The role of the local method stack and the Java stack is very similar. The difference between them is that the Java stack executes the Java method, and the local method stack executes the local method.

Note: The local method stack is also thread-proprietary.

Exception possibility: like the Java stack, StackOverflowError and OutOfMemeryError may be thrown.

4. Java heap

For most applications, Java heap is the largest memory managed by the Java Virtual Machine. It is created when the virtual machine is started. The only purpose of this memory area is to store object instances. Almost all object instances allocate memory here. Of course, when we talk about the content of the garbage collector, java heap is the main area for managing the garbage collector.

Note: The heap is shared by threads.

Exception possibility: If the heap does not have memory for instance allocation and the heap cannot be expanded, an OutOfMemeryError exception will be thrown.

Fifth, the method area (If a system continuously produces new classes without recycling, it is very likely to cause permanent zone overflow .)

The method area is used to store class information loaded by virtual machines (Type information, field information, method information, and other information) staticAmount, real-time compiler compiled code and other data. The method area is thread-safe.

Note: The method area and heap are shared by threads.

Exception possibility: when the method area cannot meet the memory allocation requirements, an OutOfMemeryError exception will be thrown.

Runtime constant pool

Used to store various literal and symbolic references generated by the compiler

Parameter configuration

  • -Xmx3550m: Set JVMMax heap memoryIt is 3550 M.
  • -Xms3550m: Set JVMInitial heap memoryIt is 3550 M.
  • -XX: NewSize = 1024 m: Set the initial value of the new generation to 1024 M.
  • -XX: MaxNewSize = 1024 m: set the maximum value of the new generation to 1024 M.
  • -XX: PermSize = 256 m: Set the Old AgeInitial ValueIt is 256 M.
  • -XX: MaxPermSize = 256 m: Set the Old AgeMaximum ValueIt is 256 M.
  • -XX: NewRatio = 4: Set the ratio of the young generation (including one Eden and two vor regions) to the old generation. Indicates that the new generation is compared with the old generation.
  • -XX: Required vorratio = 4: SetYoung GenerationEdenZone and region vorArea Ratio. The ratio of two vor zones to One Eden zone is, that is, one vor zone accounts for 1/6 of the size of the entire young generation.
Ii. Jvm garbage collection

Java's garbage collection mechanism is the capability provided by the Java Virtual Machine. It is used to dynamically reclaim the memory space occupied by non-referenced objects in an irregular manner during idle time.

Heap Memory Allocation

Young Generation)(Default Eden: required vor = 8:1)

1. All newly generated objects are first placed in the new generation. The goal of the new generation is to quickly collect objects with short lifecycles as much as possible.

2. The new generation memory is divided into one eden zone and two VOR (same vor0, same vor1) zones according to the ratio. One Eden zone and two vor zones (generally ). Most objects are generated in the Eden area. When recycling, copy the surviving objects in the eden area to a region vor0, and then clear the eden area. When the region vor0 is full, then, copy the surviving objects in the eden and region vor0 areas to another region vor1, and then clear the eden and region vor0 areas. At this time, Region vor0 is empty, and then switch between region vor0 and region vor1, that is, keep region vor1 empty.

3. When region vor1 is insufficient to store the surviving objects of eden and region vor0, the surviving objects are directly stored in the old age. If the old age is Full, a Full GC will be triggered, that is, the new generation and old generation will be recycled.

4. the GC of the new generation is also called Minor GC. the occurrence frequency of MinorGC is relatively high (not necessarily triggered when the Eden zone is full)

During Minor GC, the new generation of living objects will be copied into a vor, and then Eden and another vor will be cleaned up. Therefore, the common available new generation size is the size of Eden + the size of an Elastic vor. All Minor GC will trigger the pause of the world (stop-the-world threads except the garbage collection collector thread are suspended), stop the application thread, but this process is very short. No memory fragments exist in the Eden and vor regions.

 

When the object was born on Eden,AfterMinor GCIf the object is still alive andSurvivorRegion(The above is assumed as the from region. Here it should be the to region, that is, the to region has enough memory space to store the objects in the Eden and from regions ),The replication algorithm is used to copy the surviving objects to anotherSurvivorRegion(That isToRegion)MediumAnd then clear the used Eden and region vor regions (I .e. from Region ),And set the age of these objects1InSurvivorEvery time the Zone passesMinor GCThe object's age+ 1When the age of the object reaches a certain value(The default value is15Years old, you can use parameters-XX: MaxTenuringThresholdTo set), These objects will become the old age.

For some large objects(That is, a large continuous memory space needs to be allocated.)Is directly into the old age.

 

On the execution mechanism, JVM provides the SerialGC, ParallelScavenge, and ParNew functions)

Old Generation)

1. objects that are still alive after N garbage collection in the young generation will be put into the old generation. Therefore, it can be considered that objects with long lifecycles are stored in the old generation.

2. the memory size is much larger than that of the New Generation (about). When the old generation has Full memory, the frequency of triggering Full GC is relatively low. The old generation has a long object survival time and a high survival rate.

Under what circumstances will the new generation of objects enter the old age?

When Minor GC is used, the surviving objects of the new generation are larger than those of the Minor vor. When a Minor vor cannot be installed, they will enter the old age.

Every Minor GC in the new generation will be given to objects + 1 years in the new generation. By default, this critical point will be set from the new generation to the new generation-XX: MaxTenuringThreshold by default.

If-XX: PretenureSizeThreshold3M is set, objects larger than 3 m will directly enter the old age.

3. finalize ()When is the method called?

L when the garbage Collector (garbage colector) decides to recycle an object, it will run the finalize () method of the object, but unfortunately in Java, if the memory is always sufficient, so garbage collection may never be performed, that is, filalize () may never be executed. Obviously, it is unreliable to expect it to finish the work. So what exactly does finalize () do?

L it is mainly used to reclaim memory applied by special channels. Since the Garbage Collector only knows the memory space allocated by the new display, it does not know how to release this "special" memory area, in this case, java Allows defining a finalize () method in the class.

3. Measures to Reduce GC overhead

(1) do not explicitly call System. gc ()

(2) minimize the use of temporary objects

(3) it is best to explicitly set the object to Null when it is not used.

(4) Try to use StringBuffer instead of String to accumulate strings.

 

2. Conditions for triggering the master GC (Garbage Collector)

(1) When the application is idle, that is, when no application thread is running, GC will be called.BecauseGCIn the thread with the lowest priority,So when the application is busy, GCThe thread will not be called.,Except for the following conditions.

(2)JavaWhen the heap memory is insufficient, GCWill be called.

1. How to determine if an object is "junk" (useless object )?

Reference COUNTING METHOD

If an object does not have any references associated with it, it means that the object is rarely used elsewhere, and the object becomes a recyclable object. The referenced objects in the loop cannot be recycled.

Accessibility Analysis

The basic idea of this method is through a seriesRoot objectFrom these root objects, any objects that can be touched are considered as "active" objects. Objects that cannot be touched are considered as spam because they do not affect the future execution of the program.

Ii. Typical garbage collection algorithms

1. Mark-Sweep (Mark-clear) Algorithm

This is the most basic garbage collection algorithm. The most fundamental reason is that it is the easiest to implement and the simplest to think about. The tag-clearing algorithm is divided into two phases: the tag phase and the clear phase. The task in the mark phase is to mark all objects to be recycled, and the clear phase is to recycle the space occupied by the marked objects.

It is easy to see that the tag-clearing algorithm is easier to implement, but a serious problem is that memory fragments are easily generated, too many fragments may cause insufficient space to be found when large objects need to be allocated in the subsequent process, and a new garbage collection action will be triggered in advance.

2. Copying Algorithm

To solve the Mark-Sweep algorithm defect, the Copying algorithm is proposed. It divides the available memory into two equal-size blocks by capacity and uses only one of them at a time. When the memory of this block is used up, copy the still living objects to the other block, and then clear the used memory space, in this way, memory fragmentation is not prone. The problem is that the memory usage is large.

3. Mark-Compact Algorithm

To solve the Copying algorithm defect and make full use of the memory space, the Mark-Compact algorithm is proposed. The algorithm Mark phase is the same as Mark-Sweep, but after the Mark is completed, it does not directly clear the recyclable object, but moves the surviving object to one end, then, the memory outside the end boundary is cleared.

4. Generational collection Algorithm

GenerallyJavaHeap is divided into the new generation and the old generation, so that the most appropriate collection algorithm can be used according to the characteristics of each age. In the new generation, when a large number of objects are found to die during garbage collection, the replication algorithm is used, and the collection can be completed with the replication cost of a small number of surviving objects. In the old age, because the object has a high survival rate and no extra space to allocate a guarantee for it, you must use the "tag-clean" or "tag-sort" algorithm for recovery. The method area is permanently replaced, and the recovery method is the same as in the old age.

 

In the old age, the Mark-clear or mark-sort algorithm was used. The two algorithms mainly depend on which collector the virtual machine uses. The difference between the two algorithms is: mark-clearing may generate a large number of consecutive memory fragments.

Iii. Differences between String, StringBuffer and StringBuilder

The String is always bright, and the underlying layer is implemented by arrays.

StringBuilder: non-secure thread

StringBuffer: thread-safe

Summary:

1. If you want to operate a small amount of data, use = String

2. A single thread operates on a large amount of data in the string buffer = StringBuilder

3. multi-threaded operations on a large amount of data in the string buffer = StringBuffer

4.Why garbage collection?

In C ++, objects are occupied until the program ends running and cannot be allocated to other objects before explicit release. in Java, when no object references the memory originally allocated to an object, the memory becomes garbage. A jvm system-level thread will automatically release the memory block, reducing the programming burden. In fact, in addition to releasing useless objects, garbage collection can also clear memory record fragments.

5.JavaVirtual Machine Loading Mechanism

The class loading process includes loading, verification, preparation, parsing, and initialization.

L load

The first phase of the class loading process during loading. In the loading phase, the virtual machine must complete the following three tasks:

1. Get the defined binary byte stream through the full qualified name of a class.

2. Convert the static storage structure represented by this byte stream into the runtime data structure of the method area.

3. Generate a Java. lang. Class Object that represents the Class in the java heap as the access entry to the data in the method area.

For any class, its class loader and the class itself need to determine its uniqueness in the Java Virtual Machine.

Class Loader: Start the class loader, extended class loader, application class loader, and custom class loader.

Parent-Child Assignment Model: If a Class Loader receives a request for class loading, it first does not attempt to load the class itself, but delegates the request to the parent loader to complete the process in turn. Therefore, all class loading requests should eventually be passed to the top-level startup Class Loader. Only when the parent loader does not find the required class in its search range, that is, the sub-loader will try to load the class by itself.

L Verification

The purpose of verification is to ensure that the information contained in the byte stream in the Class file meets the requirements of the current virtual machine and does not endanger the security of the virtual machine itself.

L preparation

The preparation phase is the phase in which the class variable is formally allocated memory and the initial value (zero) of the class variable is set. These memories will be allocated in the method area.

L Parsing

The parsing phase refers to the process in which the Virtual Machine converts the symbolic reference in the constant pool into a direct reference.

L Initialization

Initialization is the last step in the class loading process. At this stage, the Java program code defined in the class is actually executed (static statement block and constructor)

4.Four JAVA reference methods

Strong reference, soft reference, weak reference, and Virtual Reference

L strong reference: When we use the new keyword to create an object, the created object is a strong reference, and the garbage collector will not recycle objects with strong references.

L soft reference: if an object has soft reference, if the memory space is sufficient, the garbage collector will not recycle it. If the memory space is insufficient, the object will be recycled. Of course, this object can still be called by the program before it is recycled. Java. lang. ref. SoftReference

L weak reference: if an object has only weak references, the garbage collector will be immediately recycled and the corresponding memory will be released as long as the thread detects the object in its own memory space. Java. lang. ref. WeakReference

L Virtual Reference: if an object only has virtual reference, it will be recycled as garbage at any time as it does not have any reference. Purpose: To receive a system notification when the object is recycled by the Collector. Java. lang. ref. PhantomReference

 

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.