Java Virtual machine related knowledge collation

Source: Internet
Author: User
Tags array length call back export class

1.java of Memory Area
Thread sharing
(1) Heap: The largest chunk of memory managed by a Java virtual machine for holding object instances, all object instances and arrays allocated on the heap
Based on the garbage collector is divided into the new generation and the old age, and can be further divided into Eden,survivor, the default ratio is 8:1 Eden, from survivor, to survivor three parts
Depending on whether the thread-private allocation buffer is turned on (Tlab)
There are also outofmemoryerror anomalies
(2) Method Area: Class information, constants, static variables, such as the compiler compiled code and other data
A memory OutOfMemoryError exception is generated, and the recovery of this area's memory is mainly the recovery of the constant pool and the unloading of the type.
Thread Isolation
(3) Java Virtual machine stack: Execute Java method
For each executed method there is a stack frame (local variable table, return exit, operand stack, dynamic link, etc.) when the stack size exceeds the STACKOVERFLOWERROR exception, when unable to request enough memory will throw OutOfMemoryError exception
(4) Local method stack: Execute native local method, other parts similar to Java virtual stack
(5) Program counter: Used to record the address of the Java Bytecode directive, so as to ensure that the thread can be switched back to the execution location, each thread has a thread program counter, the only one does not specify OutOfMemoryError exception

Chang: is a part of the method area that primarily stores the various literal and symbolic references produced by the compiler
Direct Memory: The NIO class introduced in jdk1.4, introduces channel-and buffer-based I/O, uses the native function Qurei directly allocates out-of-heap memory, and operates this part of memory by Directbytebuffer stored in the Java heap. There are also outofmemoryerror anomalies
The difference between memory overflow and memory leak:
Memory leaks: Memory leaks are when a program requests memory, it cannot release allocated memory, and memory leaks can cause the final memory to be consumed
Memory overflow: Memory overflow when the program is requesting memory, there is not enough memory space to use

2. Creation of objects
Virtual opportunity to a new instruction, first check whether the parameters of the directive in the constant pool to locate a symbol reference to a class, and check whether the symbol refers to the class is loaded, parsed and initialized, if not loaded, it involves the class loading process
If it has been loaded, then the new object allocated memory, two allocation methods, depending on whether the Java heap is structured, if the regular use of pointer collisions (that is, the pointer to the unused heap to move the size of the object), the use of the idle list, depending on whether the garbage collector with the function of compression.
Allocating memory to multithreading also requires consideration of synchronization issues. The object is then set up as necessary, in the object header (which instance of the class, how to find the metadata information of the class, the object's hash code, the object's GC generational age), and execute the <init> method to initialize the object according to the programmer's will to produce a complete object

3. Layout of objects in memory
(1) Object header (hash, generational age, lock status flag, biased thread ID, second part type pointer, pointer to its class metadata, to determine which class to which the instance, if the array also has a record array length of data)
(2) Instance data: The object is really valid data
(3) Align padding: not necessarily present, guaranteed to be an integer multiple of 8 bytes

4. Object Access Targeting
(1) using a handle: Separate a piece of memory in the heap as a handle pool, storing the handle address of the object (including specific address information for object instance data and object type data)
(2) Direct pointer: The address of the object to be stored (fast speed)
Settings for common parameters in the JVM:
-xmx for specifying the maximum heap size
-XMS the minimum value for specifying the heap size generally makes the maximum and minimum values equal to the size of the heap
The size of the Cenozoic in the-xmn heap
-XSS the size of the specified stack

5. How to determine whether an object survives
(1) Reference counts (problems with circular references, resulting in non-recyclable) Java is not in this way, you can use mutual references to test
(2) Accessibility Analysis: Select some GC roots as the starting point to search down, traversed by the path to form a reference chain, when an object does not have any reference chain connected, it is unreachable
Points as GC roots: objects referenced in virtual machine stacks and local method stacks, class static properties in the method area, and objects referenced by constants

6. Four types of references
(1) Strong reference: The most common a = new A (); This reference, as long as a strong reference is in, does not reclaim the object pointed to
(2) Soft reference: used to describe useful but not necessary objects, when the system to occur memory overflow, these objects are included in the recovery scope for a second recycle
(3) Weak references: Similar to soft references, but weaker in strength and can only survive until the next garbage collection
(4) Virtual reference: The purpose of using a virtual reference is to receive a system notification when the object is reclaimed by the collector
Where other references are defined for the purpose of caching

7. Recovery Method Area
Mainly for the collection of constants and classes, the recovery of the constant only need to determine that no other place to use the constant can be
The collection of classes needs to meet the following:
All instances of the class have been recycled
Class loader has been recycled
The Java.lang.Class object that corresponds to the class is not referenced anywhere and the method of accessing the class through reflection cannot be

8. Garbage collection algorithm
Mark-Clear (Mark-sweep)
First mark out all the objects that need to be recycled, and then collect them uniformly, there are efficiency problems, labeling and purging are inefficient, and there are a lot of discontinuous fragments after recycling, and you have to start a garbage collection action in the future when the program needs to allocate large objects
Copy
Divide the memory into equal two blocks, each time using one piece, when used up will also survive the object copied to another piece, and then all this piece of clean up, to achieve simple, efficient operation but the memory is reduced to one by one half, the virtual machine is generally used eden,survivor,survivor, One piece of survivor is idle, but when copying survivor not enough to store the surviving objects, it is necessary to use the old age to guarantee, this feasible reason is that the vast majority of the new generation of objects are facing the birth of the Dead
Mark-Organize
The preceding processing is similar to mark Cleanup, which is to move all surviving objects to one end in subsequent processing

9. Enumerate the root nodes, security points, and security zones
GC pauses (Stop the word) to ensure consistency, the need to stop executing threads in the accessibility analysis
The workaround is to record stacks and registers in a particular location where those locations are references, such that the location is referred to as the security point, and the choice of the security point is generally to have the program be selected for long execution as a feature, because if each instruction is executed in a very short time, it will not run long because the instruction sequence is too long

10. Garbage collector
Cenozoic: Serial, parnew, Parallel scavenge using replication collection algorithms
Older years: CMS (concurrent Mark Sweep), Serial old, Parallel, and Mark Clear
G1
Serial collector: A single-threaded collector that, when used, must suspend all other worker threads until the collection is complete. Simple and efficient, and without the overhead of thread interaction, you get the most efficient single-thread collection efficiency. General Client Mode
Parnew Collector: In fact, is the serial multi-threaded version, in addition to serial only he can use with the CMS, in the server mode use
Parallel scavenge Collector: pay more attention to throughput (user code run time/cpu total elapsed time), mainly suitable for in the background operation and not too many interactive tasks
Serial old collector: Use tag grooming collection algorithm, single-threaded collector, mainly used in client mode, if in server mode, there are mainly two uses, one is jdk1.5 and parallel scavenge used together, two is when the CMS occurs CMF (Concurrent model failure) as a fallback scheme
Parallel Old collector: multithreading and tagging, but still cannot implement concurrent execution of user threads and garbage collection threads
CMS Collector: The main purpose is to obtain the shortest recovery stop as the target collector, suitable for the pursuit of service response speed, short pause time, user experience high demand, Mark clear
is divided into four processes:
Initial tag, concurrency token, re-tagging, concurrency clearing
The initial tag primarily marks the objects directly associated with GC root, and the initial tag and re-tagging will still stop the world, but these two processes take little time
A more time-consuming reference trance process and cleanup process can be performed concurrently with the user thread
Cons: CPU-sensitive, floating garbage (resulting in concurrent garbage, may appear concurrent model failure), resulting in the full GC, the last is to use the mark clear, there is fragmentation
G1 Collector:
Features: Concurrency and parallelism, generational collection, spatial integration (global tagging, local replication algorithms), predictable pauses
Dividing the entire Java heap into areas of equal size, although preserving the concepts of the Cenozoic and the old, but no longer physically isolated, there is a plan to avoid the entire heap of garbage collection, but rather to track the value of each garbage accumulation (recycling can get the space size and the time required to reclaim the experience), maintain a priority queue table, The area with the greatest value is reclaimed each time, and each region has a renmenber set to ensure that no full heap scan is used
Process:
Initial tag, concurrency token (this time object change is recorded in remembered set logs), final tag (merge logs into remembered set), filter recycle
New generation: The main use of stop-copy recovery algorithm
Old age: Mainly using marker-clear, labeling-sorting and recycling algorithms
Minor GC: Garbage collection action occurring in the Cenozoic, frequently recycled, faster
Full GC: Occurs in the old age and is usually accompanied by at least one minor GC, which is very slow

11. class file Structure
(1) class file mainly uses a pseudo structure similar to C language data structure to store data. Only unsigned numbers and table two types of data
Unsigned number: u1 u2 U4 U8
Table: Multiple unsigned numbers or other tables conform
Generally the first four bytes are the magic number CA FE BA by, followed by the minor version number of U2, the major version number of U2
Next is the number of constants for the constant pool and each constant (record literal and symbol reference)
Finally contains the number and description of fields, methods, etc.

12. The entire life cycle of class loading
Load, connect (validate, prepare, parse), initialize, use, uninstall
The difference between a class and an interface loading process: When a class is initialized, it requires that its parent class is all loaded, but the interface does not require that its parent interface be all initialized, only in the true use of constants in the parent interface, such as the parent interface. If this is not the same as the class, the use of constants in the class does not cause initialization).
Load: Gets the binary byte stream that defines this class through the fully qualified name of a class, and then transforms the static data structure represented by the bytes stream into the run-time data structure of the method area, and finally generates a Java.lang.Class object that serves as the access entry for various data of this class of method area
The array class is not created by the class loader, but is created directly by the virtual machine

Verify: The security of the virtual machine is not compromised in order to ensure that the information contained in the class file byte stream conforms to the requirements of the current virtual machine
If you verify that the file does not conform to the class file format constraint, the java.lang.VerifyError exception or its subclass exception is thrown
(1) file format verification: Whether the magic number starts with 0xCAFEBABE, the major and minor version number is the processing range of the processor, the constant pool of constants have not been supported by the constant type, the various index values pointing to the constant whether there are non-existent constants or non-conforming to the type of constant, etc. Mainly to ensure that the byte stream can be correctly parsed and stored in the method area, in order to ensure that the requirements of Java type information, only through this authentication will enter the memory method to store
(2) meta-data validation: Semantic analysis of the information described in bytecode to ensure compliance with the Java language Specification
Does this class have a parent class, whether the parent inherits a class that does not allow inheritance, whether the class is an abstract class, whether the parent class is implemented, or all of the methods that need to be implemented in the interface, etc.
(3) Bytecode verification: Determine whether program semantics are legitimate and logical through data flow and control flow, and ensure that the method of checking class does not make the event that endangers the security of the virtual machine at runtime
(4) symbol Reference Validation: the fully qualified name of the string description can find the corresponding class, determine whether the class conforms to the Method field descriptor, and the methods and fields, classes, fields, and methods that are described by the simple name are accessible

Prepare: To formally allocate memory for class variables and set class variables for the initial worthwhile stage but for the static final decoration, the values that are directly assigned to the program are allocated in the method area
Parsing: A virtual machine replaces a symbolic reference within a constant pool with a direct reference procedure
Symbol Reference: is a set of symbols to describe the referenced target, can be any form of literal, as long as the use of a non-ambiguous positioning to the target can be, regardless of the memory layout of the virtual machine, the reference target is not necessarily loaded into memory
Direct reference: A pointer that can be directed to a target, relative offset, or a handle that can be indirectly anchored to the target, related to the memory layout of the virtual machine, the target exists in memory
Parsing of classes or interfaces
Parsing of Fields
Parsing of class methods
Parsing of interface methods

Initialization: This stage is really starting to execute Java code (bytecode), the initialization phase is the process of executing the class constructor <clinit> () method (1) This method is formed by the compiler to collect all the class variables in the class and the statements in the static statement block. The order of the collection is determined by the order in which the statements appear in the source file, note: Static statement blocks can only access variables defined in the static statement block, define variables after him, static statements can be assigned values, but cannot access (2) This method differs from the constructor, and does not need to display the constructor that invokes the parent class. The virtual opportunity guarantees that when the subclass is called, the method of the parent class has been executed (3) if the class or interface does not have a static statement block and there is no assignment to the variable, the compiler will not generate the method for the Class (4) interface to execute the method without first executing the method of the parent interface. The interface implements the initialization of the class and does not execute the interface, only if the variables defined in the interface are used, the parent interface will use the (5) virtual opportunity to ensure that the class's method is properly locked and synchronized in a multithreaded environment.

13. Class Loader
For any class, it needs to establish its uniqueness in the Java Virtual machine, together with the class loader that loads it and the class itself
Parental delegation Model
From the perspective of the Java Virtual machine: Start the ClassLoader (Bootstrap ClassLoader) and others (all inherit Java.lang.ClassLoder).
From Java Developer: Start the ClassLoader, be responsible for class libraries in the <java_home>/lib directory, extend the ClassLoader (extension classloader) <java_home>/lib/ext directories, The application ClassLoader (application ClassLoader), also known as the system ClassLoader, is responsible for loading the class library specified on the user's classpath, which is typically the default class loader in the program
Note, however, that the parent-child relationship of the loader is implemented by combining rather than inheriting
Parental delegation Model Workflow: If a class loader receives a request for a class load, it first does not attempt to load the class itself, but instead delegates the request to the parent ClassLoader to complete, so that all the load requests should be routed to the top-level startup ClassLoader. Only the parent loader feedback could not complete the request, the sub-loader would try to load itself
Benefit: Let the Java class have a hierarchical relationship with precedence as its classloader

13. Destruction of parental mandates
1. Before the jdk1.2 release
2. The disadvantage of parental delegation: when the underlying class needs to call back to the user's code (such as Jndi), the solution to this problem uses a less elegant design: The threading context ClassLoader (thread ClassLoader), This ClassLoader requests the subclass loader to complete the action of class loading (JNDI, JDBC)
3. Third destruction: The user's pursuit of the dynamic nature of the program caused by the Code hot replacement, module thermal deployment, etc.
OSGi implements a modular thermal deployment using its own class loading mechanism: Each module has its own classloader, and when a module is replaced, the same loader replaces the thermal substitution of the implementation code.
No longer a tree structure, but a net structure.
1) Java.* class delegate to the parent ClassLoader load
2) Otherwise, delegate the class in the delegate list to the parent class loader to load
3) Otherwise, delegate the class of the import list to the class loader of the bundle of the export class to load
4) Otherwise, find the classpath of the current bundle and load it with your own class loader
5) Otherwise, the lookup class is in its own fragment bundle, and if so, the class loader delegated to the fragment bundle loads
6) Otherwise, find the bundle for the dynamic import list, and delegate the class loader to the corresponding bundle to load
7) Otherwise, the class lookup fails
OSGi allows the class to be loaded as a peer model is not a traditional hierarchical model, forming a mesh structure, but this also increases the complexity of the implementation, and may also be thought

14.java memory model
Java Threads---Working memory--(Save and load operations)---main memory
The main goal is to define the access rules for each variable in the program, to store variables in the virtual machine into memory and to go from memory to middle variables such as the underlying details
The Java memory model defines 8 operations to complete the above operations
(1) lock
(2) Unlock
(3) Read
(4) Load
(5) Use
(6) Assgin
(7) Store
(8) Write
Volatile keyword: The most lightweight synchronization mechanism provided by a Java virtual machine
Ensure that the variable it modifies is visible to all threads, meaning that when a thread modifies the value of the variable, the new value is immediately available to other threads
Volatile can also be inconsistent, because the operation in Java may not be atomic, causing the variable to be the same as unsafe, such as i++, which is actually three operations (fetch, +1, Assignment)
Volatile only guarantees visibility, and does not guarantee atomicity
The second feature of volatile is to prevent command reordering optimizations (by inserting some memory barriers), and the reordering of instructions should not affect the correct results of the program.
The concurrency process mainly revolves around: atomicity, visibility, and order of three characteristics
Order in addition to rely on volatile and synchronized keyword to ensure that more important is the principle of first occurrence
(1) Program Order rules: In a thread, in the order of the code, the preceding code first occurs in the following
(2) Tube lock principle: A ulock must first occur after the lock operation facing the same lock
(3) Volatile variable rule: The write operation of a volatile variable takes place in the back of the read operation of the variable.
(4) thread start rule: Thread Start () method first occurs in other actions
(5) Thread abort rule: All operations of the thread are detected by terminating the remaining thread
(6) Object finalization rule: Initialization of an object occurs at the beginning of the Finalize () method

15. Threads
A thread is the smallest unit that is scheduled for a processing machine.
Status: New, running (ready and running), waiting indefinitely, waiting for a deadline, blocking, ending

16. Fair lock and non-fair lock
Depending on the order in which the lock is requested
Synchronized use of the non-fair lock
While lock provides a fair and unfair lock

17. Optimization of the Lock:
No lock
Biased lock
Lightweight lock
Heavy-weight lock

Java Virtual machine related knowledge collation

Related Article

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.