Initial knowledge of the JVM

Source: Internet
Author: User

Prior to know the knowledge of the JVM, but are smattering, a lot of things are not very clear concept, today to comb. JVM Model

Program Counter

Each thread running in the program Counter Register JVM has its own PC register, and the PC register holds the value undefined when the thread executes the method is local, otherwise the address of the instruction currently executing within the JVM is saved. Java Virtual machine stack

The Java Virtual machine stack (Java Stacks) is also thread-private, with the same life cycle as the thread. The virtual machine stack describes the memory model that the Java method executes. Local Method Stack

The local method stack (Native) can be understood as essentially the same as the virtual machine stack, except that the local method stack is used to perform the Native method service, and in some virtual machines (such as sun hotspot virtual machines), the local method stack and the virtual machine stack are directly merged. The local method stack area also throws Stackoverflowerror and OutOfMemoryError exceptions. Method Area

The method area is the area of memory shared by each thread, and it is used to store data such as class information, constants, static variables, and code compiled by the immediate compiler that have been loaded by the virtual machine.
Although the Java Virtual Machine specification describes the method area as a logical part of the heap, it has an alias called Non-heap (Not a heap), which should be distinguished from the Java heap.
For developers who are accustomed to developing and deploying programs on a hotspot virtual machine, many people prefer to call the method area the "permanent generation" (Permanent Generation). Removed in 1.8PermGen, replaced by Metaspace. For other virtual machines (such as Bea JRockit, IBM J9, etc.) there is no concept of a permanent generation in the method area there is also an area that is running a constant pool (runtime Constant pools) ; A key feature of the constant pool of the run-time pool relative to the class file is its dynamic nature;
The Java language does not require constants must be compiled only to produce, that is, not pre-placed in the class file of the constant pool content to enter the method area to run the frequent pool, the runtime may also put new constants in the pool, this feature is used by developers more than the String class intern ( Method
According to the Java Virtual Machine specification, a OutOfMemoryError exception is thrown when the method area does not meet the memory allocation requirements. Direct Memory Area

Direct memory is not part of the data area when the virtual machine is running, nor is it an area of memory defined in the Java VM specification.
New NIO classes have been introduced in JDK 1.4, introducing a channel-to-buffe I/O approach that can be used to directly allocate out-of-heap memory using the native function library. It then operates as a reference to this memory through a Directbytebuffer object stored in the Java heap. This can significantly improve performance in some scenarios because it avoids copying data back and forth in the Java heap and native heap.
The allocation of native direct memory is not limited by the size of the Java heap, but is limited by the total memory size of the machine and the processor addressing space. If the sum of each memory region is greater than the physical memory limit (including physical and operating system-level restrictions), the OutOfMemoryError exception occurs when the dynamic scale is extended. Need to limit direct memory can be used:-XX:MAXDIRECTMEMORYSIZE=XXM limit; This value defaults to 0; unlimited size

The JVM model differs in different versions. Here is an example of hotspot (build 25.91-b14, Mixed mode).
In jdk1.8, the hotspot cancels the permanent zone and uses the meta-space instead.
By VISUALVM you can see that the heap is divided into the following portions of the heap (heap)

The Java heap (Java heap) is the largest piece of memory managed by a Java virtual machine. The Java heap is a piece of memory that is shared by all threads and created when the virtual machine is started.
The only purpose of this area of memory is to hold object instances where almost all of the object instances are allocated memory. Java heap is the main area of garbage collector management
As the collector is now basically using the Generational collection algorithm, the Java heap can also be subdivided into: the new generation and the old age, the more detailed there is Eden space, Survivor 0/survivor 1 space and so on. The subdivision heap is just to better reclaim memory, or to allocate memory more quickly;
The Java heap can be in a physically discontinuous memory space, and a OutOfMemoryError exception will be thrown if there is no memory completion instance allocation in the heap and the heap cannot be extended.

Eden: Objects are allocated in the New Generation Eden area. When the Eden area does not have enough space to allocate, the virtual machine will initiate a minor GC.
Survivor 0/survivor 1: When recycled, objects that are still alive in Eden and Survivor are copied one at a time to another Survivor, and finally the Survivor space that was used in Eden and just before is cleared away.
Old: Large objects directly into the older age (-the Xx:pretenuresizethreshold parameter causes objects larger than this setting to go straight into the old age) to avoid large amounts of replication between Eden and Survivor. Multiple minor GC will still survive after being copied to the old age.
Metaspace: Uses local memory to store metadata for the class. (-xx:maxmetaspacesize=10m to set the maximum value)

The virtual machine defines an object age counter for each object. If the object is still alive after Eden was born and after the first minor GC, and can be accommodated by survivor, it will be moved to survivor space, and the object age is set to 1. Objects in the Survivor area each "through" a minor GC, age increased by 1 years, when its age increased to a certain extent (by default, 15 years old), will be promoted to the old age. The age threshold at which an object is promoted to the old age can be set by parameter-xx:maxtenuringthreshold.
Eden,survivor0,survivor1 is called Younggen (Cenozoic), using the replication algorithm;
The mark-compact algorithm, the tagging process is still the same as the tag-purge algorithm, but the next step is not to clean up the recyclable objects directly, but to let all surviving objects move toward one end.
Oracle has made a very important change in java7.-string Pool is assigned to the heap. This means that you will no longer be confined to a single fixed-size memory area. All the strings are allocated in the heap, Like most ordinary objects. This way you only need to manage the heap size when adjusting your program.
All strings in string pool are recycled by GC when no references point to them. garbage collection Mechanism Reference Count

The reference count is an early policy in the garbage collector. In this approach, each object (not a reference) in the heap has a reference count. When an object is created, and the object is assigned to a variable, the variable count is set to 1. When any other variable is assigned a reference to this object, the count is added to 1, but when a reference to an object exceeds the life cycle or is set to a new value, the object's reference count is reduced by 1. Any object with a reference count of 0 can be garbage collected. When an object is garbage collected, it refers to any object count minus 1.

Advantage: The reference counting collector can be executed very quickly, interwoven in the program running. It is advantageous to the real-time environment that the program is not interrupted for a long time.
Disadvantage: cannot detect a circular reference. If the parent object has a reference to a child object, the child object in turn references the parent object. In this way, their reference count will never be 0. Analysis of accessibility

With some columns called "GC root" as a starting point, searching down from these contacts, the search path is called the reference chain, and when an object is connected to the GC root without any reference chain, it proves that the object is not available.

The objects in Java that can be used as GC roots include:
1. Objects referenced in the virtual machine stack (local variable table)
2. Objects referenced by class static properties in the method area
3. Objects referenced by constants in the method area
4. Objects referenced in the local method stack (native objects) some common garbage collection algorithm tag-purge (Mark-sweep)

This is the most basic garbage collection algorithm, the reason is that it is the most basic because it is the easiest to achieve, the idea is the simplest. The tag-purge algorithm is divided into two stages: the tagging phase and the purge phase. The task of the tagging phase is to mark out all objects that need to be recycled, and the purge phase is to reclaim the space occupied by the tagged objects. One of the more serious problems is that it is prone to memory fragmentation, and too many fragments can cause a new garbage collection action to be triggered in advance by not finding enough space to allocate space for large objects in subsequent processes. copy (Copying)

Divide available memory by capacity into two blocks of equal size, using only one piece at a time. When this piece of memory is used up, copy the surviving object to another piece, and then clean up the used memory space once, so the memory fragmentation problem is not easy. This method is suitable for short-lived objects, which consistently replicate long-lived objects, resulting in reduced efficiency and the ability to use memory to shrink to half the original tag-compression (mark-compact)

In order to solve the defect of copying algorithm and make full use of memory space, the mark-compact algorithm is proposed. Sometimes also called Mark-purge-compress collector, with the mark-purge collector has the same marking stage. In the second stage, the tag object is copied to the new domain of the stack to compress the stack. This collector also stops other operations. Incremental

The incremental collector divides the stack into multiple domains, collecting garbage from only one domain at a time, or it can be understood to divide the stack into a small chunk, one at a time, and only one block is garbage collected. This results in a smaller application outage time, which makes the user generally unaware that the garbage collector is working. Generational Recycling

The disadvantage of the copy collector is that all tagged objects are copied each time they are collected, causing objects with long life cycles to be copied back and forth multiple times, consuming a lot of time. The generational collector solves this problem by dividing the stack into two or more domains for storing objects of different lifetimes. A new object generated by the JVM is typically placed in one of the domains. Over time, objects that continue to exist (non-short-lived objects) will receive a lifetime and go into a longer-lived domain. The generational collector uses different algorithms for different domains to optimize performance. Several garbage collectors provided by the HotSpot (JDK 7) virtual machine serial serial/serial old

The serial/serial old collector is the most basic and oldest collector, which is a single-threaded collector and must suspend all user threads when it is garbage collected. Serial Collector is for the new generation of collectors, the use of the copying algorithm, Serial old collector is a collector for the older era, using the mark-compact algorithm. Its advantages are simple and efficient, but the disadvantage is that it will bring a pause to the user. Parallel Parnew

The Parnew Collector is a multithreaded version of the serial collector that uses multiple threads for garbage collection. Parallel Parallel Scavenge

The Parallel scavenge collector is a new generation of multi-threaded collectors (parallel collectors) that do not need to pause other user threads during recycling, using the copying algorithm, which differs from the first two collectors, primarily to achieve a manageable throughput. Parallel parallel old

Parallel old is the older version of the Parallel scavenge collector (parallel collector), using multithreading and Mark-compact algorithms. Concurrent CMS

The CMS (current Mark Sweep) collector is a collector that targets the shortest payback time and is a concurrent collector, using the mark-sweep algorithm. G1

The G1 collector is the forefront of today's collector technology, a collector for service-side applications that leverages multi-CPU, multicore environments. So it is a parallel and concurrent collector, and it can build a predictable pause-time model

GC Type and timing

Scavenge GC? Typically, when a new object is generated and the Eden application space fails, the scavenge GC is triggered, the heap Eden Zone is GC, the non-surviving objects are cleared, and the surviving objects are moved to the survivor area. Then tidy up the two districts of survivor.

Full GC? Organize the entire heap, including young, tenured, and perm. The full GC is slower than the scavenge GC, so the full GC should be minimized as much as possible.
The full GC may be caused by the following reasons:
-tenured was written full
-perm field is full
-SYSTEM.GC () is displayed call
-Each domain assignment policy of the heap after the last GC dynamic change class loading mechanism class loading

Class loading refers to reading the binary data in the class's. class file into memory, placing it in the method area of the run-time data area, and then creating a Java.lang.Class object of this class in the heap that encapsulates the class's objects in the method area class. The JVM divides the class loading process into three steps: Mount (load), link, and Initialize (Initialize) links in a three-step way.

class Loader

The ClassLoader is an innovation in the Java language and one of the most important reasons for the popularity of the Java language. It enables Java classes to be dynamically loaded into a Java virtual machine and executed.

The ClassLoader emerged from JDK 1.0 and was originally developed to meet the needs of Java applets. Java applets need to download Java class files from the remote to the browser and execute them. Class loaders are now widely used in Web containers and OSGi. the tree-like structure of the ClassLoader

The ClassLoader in Java can be broadly divided into two categories, one for the system, the other for Java application developers. Boot class loader (bootstrap class loader):

It is used to load the Java core library, is implemented with native code, C + + implementation, does not inherit from Java.lang.ClassLoader. Extension Class loader (Extensions class loader):

It is used to load the Java extension library. The implementation of the Java virtual machine provides an extension library directory. The ClassLoader finds and loads the Java class in this directory. System class Loader (loader):

It loads the Java class according to the Classpath (CLASSPATH) of the Java application. In general, Java-applied classes are loaded by it. It can be obtained by Classloader.getsystemclassloader (). Custom Loader (Customize ClassLoader):

The ClassLoader that the application customizes according to its own needs, such as Tomcat and JBoss, will be implemented according to the Java EE specification itself ClassLoader

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.