In-depth understanding of Java virtual Machines--Learning Notes

Source: Internet
Author: User

JVM memory model and partitioning

JVM memory is divided into:

1. method Area : A thread-shared zone that stores data such as class information, constants, static variables, instant compiler compiled code, etc. that have been loaded by the virtual machine

2. Heap: thread-shared areas, storage object instances, and memory regions allocated to arrays are also here.

3. Virtual machine stack: a thread-isolated area in which each thread has its own virtual machine stack with the same life cycle and thread. The virtual machine stack describes how the method executes the memory model, in the station stack frame unit, each stack frame storage and the method runs the local variable table, the operand stack, the dynamic link, the method returns the address and so on information.

4. Program counters: thread-isolated areas, each of which has its own program counter, which stores the line number of the byte code that the program is currently executing.

5. Local method stack: thread isolation, similar to a virtual machine stack, is used when a virtual machine calls the native method.

The partitioning of the heap, as well as the characteristics of each partition:

Java heap is the main area of garbage collector management, according to the partition of collection algorithm, heap memory space can continue to be subdivided into the younger generation, the old age . The younger generation can also be divided into larger Eden areas, two of the same size from the survivor,to Survivor area. The default Eden and survivor areas have a size ratio of 8:1:1, which can be adjusted. When allocating memory for newly created objects, the objects are assigned to the Eden and from survivor areas, and the objects that are still alive in the Eden and survivor areas are copied to the to Survivor zone when they are immediately reclaimed, if the to The size of the survivor area does not accommodate the surviving object, and the surviving object is assigned to the old age area. In general, the newly created small objects will be placed in the younger generation, most of the younger generation objects are recycled during the next garbage collection, and the older generations store large objects and long-lived objects.

Object creation method, object's memory layout, object access location

Object is created:

1. Ordinary object creation process: Virtual opportunity to a new directive, first check whether the parameters of this directive (class type) can be located in the constant pool of a class symbol reference, and check that the symbol refers to the class is loaded, parsed, initialized, If there is no class loading process to perform.

2. creation of Array objects: virtual opportunity to a newarray bytecode instruction allocates an area directly in memory.

3.Class object creation: When the virtual machine loads the class, obtains this kind of binary byte stream through the class's fully qualified name, and then passes the file verification to convert the static structure represented by the byte stream into the runtime data structure of the method area, and generates a class object representing the class in memory, which exists in the method area, Access to a variety of data for this class.

The memory layout of the object:

The layout of the object in memory is divided into three areas: Object header, instance data, aligned padding

Object Header : Stores run-time data for the object itself, including hashes, GC generational age, lock status identification, thread hold lock, bias thread ID, bias timestamp, etc. the other part of the object header is the type pointer, which is the pointer to its class metadata in the method area, which the virtual machine uses to determine which class the object is an instance of. If the object is an array, the object header also has a term that records the data of the array length.

instance Data : Valid information that an object is actually stored is the various types of field content defined in the class.

Snap To fill : The virtual machine requires that the size of the object must be an integer multiple of 8 bytes, the alignment is padded with the placeholder, and the object size is guaranteed to be an integer multiple of 8 bytes.

Access positioning of objects : Java programs use reference data on the stack to manipulate specific objects in the heap, with access to objects in two ways: handle access, direct pointer access .

Handle Access : The Java heap divides an area for use as a handle pool, where the handle address of the object is stored in the reference, and the handle only actually contains the specific address information of the object instance data and the object type data.

Direct pointer Access : The reference in the stack points directly to the address of the object in the heap, which in the header data points to the address of its class metadata in the method area.

The advantage of using a handle is that a stable handle address is stored in the reference, and only the instance data pointers are changed when the object is moved (garbage collection causes the object to move). The benefit of using direct pointer access is faster.

how to determine garbage collection: Reference counting method, reference chain method

Reference Counting Method : Add a reference counter to the object, have an object reference counter plus 1, reference the invalidation counter minus 1, and a counter of 0 to indicate that the object is no longer being used and can be recycled.

reference chain method (Accessibility analysis): through GC Roots as a starting point, when an object is connected to a GC roots without any reference chain, the proof object is not available.

can be used as GC roots objects are objects referenced in the virtual machine stack, objects referenced in the local method stack, objects referenced by class static properties in the method area, objects referenced by constants in the method area (execution context and global references)

Four types of reference and features of Java:

1. Strong reference: a common in the program, similar to "String s=" Hello Wold "" Such a reference, the strongly referenced object will not be recycled.

2. Soft references : useful but not required objects are garbage collected for soft-referenced objects before the system is about to have a memory overflow, andthe SoftReference class implements soft references.

3. Weak references : Objects that are not required, objects associated with weak references can only survive until the next garbage collection occurs.

4. Virtual Reference : The weakest reference relationship, cannot get an instance of an object through a virtual reference, and the sole purpose of setting a virtual reference for an object is to receive a system notification when the object is reclaimed by the collector.

The four kinds of reference strength weaken in turn, strong weakness and deficiency.

The principle and characteristics of GC three collection algorithms, use, optimization ideas

three types of garbage collection algorithms: copy algorithm, Mark -clear algorithm, marker-collation algorithm

tag -purge algorithm : First mark all objects that need to be recycled, and then uniformly reclaim all tagged objects when the tag is complete. cons : Marking and clearing two processes are inefficient; when marked, space debris is generated, and space debris causes a large object to be allocated in advance for garbage collection.

copy algorithm : Divide the available memory into two regions, use only one piece at a time, and when the piece of memory is used up, copy the surviving objects to another piece of memory, and then clean up the used memory space once. Pros: Solve the space debris problem and achieve simplicity. disadvantage : Reduce memory to two blocks, memory usage is not high. Replication operations frequently become less efficient.

Tag -grooming algorithm : After the object tag is recycled, all surviving objects are moved to one end, and then the memory outside the boundary is cleared away. Advantage: No space fragmentation is generated, which increases memory space utilization compared to the replication algorithm.

The replication algorithm is used in the garbage collection of young generations, and the labeling and labeling cleanup algorithms are used in collectors of garbage collection in the old age.

What are GC collectors? Features of CMS and G1 collectors

GC Collector According to the recycling area, the Cenozoic has Serial,parnew,paralell scanvage, the old age has Serial Old,cms,parallel, and the new generation of the old age general G1

Serial and Serial old is a garbage collector released in the early JDK, characterized by a single-threaded, new generation using the replication algorithm, the old age using the tag sorting algorithm, two garbage collector in the work must stop all user threads, until the collection is completed before the user thread can be replied to, because it is a single-threaded mode of work, Without the overhead of thread interaction, it is possible to live the highest single-thread collection efficiency, using virtual machines in client mode.

parnew collectors are The multi-threaded version of the serial collector is a young generation of garbage collectors that can be used with serial old and CMS collectors. Parnew performance in a single CPU environment is not serial good, because the single CPU environment of multithreading in chronological order, but also to bear the additional cost of interaction between threads, but in a multi-CPU environment, parnew performance is much better, is the preferred Cenozoic collector for virtual machines running in server mode.

in jdk1.4 The new garbage collector is Parallel scanvage and corresponding Parallel old, Span style= "font-family: Microsoft Black" > New generation based on the replication algorithm, the old age based on the tag collation algorithm . Parallel Scanvage is also a parallel multi-threaded collector, and the difference between it and parnew is that they have different concerns. Parnew focuses on reducing the amount of time a user thread pauses when garbage collection occurs, while Parllel Scanvage focuses on getting the maximum throughput, which is the ratio of the CPU running user code to the total CPU elapsed time. Short pause time is suitable for interacting with the user program, high throughput can be efficient use of CPU time, as soon as possible to complete the operation of the task, mainly and in the background operation does not require too many interactive tasks.

Jdk1.5 the ability to execute concurrently with the user thread CMS collector CMS is the old garbage collector. CMS is a collector with the goal of obtaining the shortest recovery pause time, which is realized based on the tag clearing algorithm. Its working process is divided into initial tag, concurrency tag, re-tagging, concurrency cleanup Four steps, where initial markup and re-tagging are required to halt the user thread, concurrent tagging and concurrent cleanup processes can be performed concurrently with the user thread, and in the overall garbage collection time, the initial and re-tagging takes little time, The re-tagging phase can also be performed in parallel by multiple garbage collection threads, so the overall user thread pauses for a short time. cms disadvantages : for CPU resource-sensitive, the CMS default startup garbage collection thread number is (CPU number +3)/4, in the concurrency phase due to the use of user threads caused by slow application, CPU less than 4 times to the user program is very large; the CMS is unable to handle the new garbage generated during the concurrent cleanup phase. Only after waiting for the next garbage collection flag to be cleared; CMS based on the tag cleanup algorithm will produce space debris, the solution is to open the full GC when the memory collation, this process can not concurrency, the user thread to prolong the pause time.

G1 Collector is the term introduced in the jdk1.7 of the new generation and generations of garbage collectors, facing the server model. G1 divides the memory area into multiple independent areas of the same size, G1 tracks the value of garbage accumulation in each area, maintains a prioritized list in the background, and prioritizes recovery of the most valuable areas per time, based on the allowable collection times, which can capture the highest possible collection efficiency for a limited time. G1 Garbage Collection process : initial tag (single thread, pause), concurrency token (single thread, concurrency), final tag (multi-threaded, parallel, pause), filter recycle (multithreading, parallelism, pauses).

When did the Minor GC and full GC occur separately?

When the created object allocates insufficient memory space, it starts a Minor GC, collects the new generation of Eden and from Survivor, and assigns the surviving objects to the to Survivor area if the to The space in the survivor area is not enough to accommodate the surviving object, which allocates the surviving object to the old age, and if the old age does not have enough space to start a full GC.

Class loading process: Load, validate, prepare, parse, initialize

the class loading mechanism of a virtual machine is to take the data from the description class The class file (or other path) is loaded into memory, and the data is validated, converted, parsed, and initialized, resulting in a Java type that can be used directly by the virtual machine.

Loading : 1. Get the binary byte stream that defines this class by the fully qualified name of a Class 2, convert the static structure of the byte stream into the Daixiao of the method area 3, generate a Class object representing the classes in memory, and serve as the access entry for various data of this class in the method area.

Validation :1, file format verification, to ensure that the input byte stream in the format of the format of the class file to ensure that the input byte stream can be correctly parsed, only through this verification, the byte stream will be stored in the method area 2, metadata validation, the metadata of the class for semantic verification, Ensure that the information described by the class conforms to the Java language specification. For example, to verify that the class is implemented in the parent class or interface methods, such as 3, bytecode verification, through the analysis of data flow and control flow, ensure that the class method conforms to the logic, not at runtime to the virtual machine harm 4, symbol reference verification, occurs in the parsing phase, to ensure that the parsing phase of the symbolic reference to the normal execution of

Prepare : Formally allocates memory for class variables (static) and sets the initial values of class variables (0 values of data types), and the memory used by these variables is allocated in the method area.

parsing : Virtual machines convert symbolic references within a constant pool into direct drinking, and parsing actions are primarily for classes or interfaces, fields, class methods, interface methods, method types, method handles, and call Point qualifier 7 class symbol references.

Initialize : The initialization phase does not actually perform the classes defined in the Java code, the initialization phase is the process of executing a class constructor <init> method. The <init> method (class constructor) is generated by a combination of static variables and static code blocks in the compiler's auto-collection classes. The initialization process for subclasses and parent classes takes precedence over the following: parent class constructor , subclass class constructor, parent class object constructor, subclass object constructor. Static class variables and static code blocks in a class are executed in the order defined in the class.

When does initialization of class be performed?

The JVM specifies that there are only 5 of cases--an active reference to the class, and the initialization of the class must be performed immediately.

1), when encountering new,putstatic,getstatic,invokespecial four bytecode instruction, if there is no initialization of the class to be initialized immediately. The programming environment for these four bytecode directives is to instantiate the object with the new keyword, read or set the static variable of the class, and invoke the static method of the class.

2), when using the Java.lang.reflect package to reflect the class, if there is no initialization to initialize immediately.

3), when initializing a class, if its parent class is not initialized, the initialization of the parent class should be started first

4), when the virtual machine starts,the main class where the Main method resides is initialized by the virtual machine first

5), using dynamic language in the Lava.lang.invoke.MethodHandle instance the final parse result is the Ref_getdtatic,ref_putstatic,ref_invokestatic method handle, The corresponding class of this handle is not initialized and needs to be initialized first.

Parent delegation Model:

The class loader's parental delegation model refers to the boot class loader, the extension classloader, the application ClassLoader, the custom ClassLoader, from the top level to the bottom layer, respectively . The parent-child relationship between the ClassLoader is not implemented by inheritance, but by composition. The working process of the parent delegation model is that if a class loader receives a request for a class load, it first delegates the request to the parent ClassLoader to complete, and all the load requests should eventually be routed to the top-level startup class loader, and only when the parent class is unable to complete the class load request. The loader will not attempt to load itself.

benefits of using the parental delegation Model : The Java class has a hierarchy of priorities with his loader, and the most basic classes are loaded by the top-level classloader, which ensures that the same class is used wherever the class is used in the program.

In-depth understanding of Java virtual Machines--Learning Notes

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.