Java Virtual Machine

Source: Internet
Author: User

Java Virtual Machine
Java Virtual Machine

Java supports platform independence, security, and network mobility. The Java platform consists of a Java virtual machine and a Java core class. It provides a unified programming interface for pure Java programs, regardless of the underlying operating system. It is precisely because of the Java Virtual Machine that it claims to be "one compilation, running everywhere" to be guaranteed.

The Java Virtual Machine has completed several major tasks:

Compile the java file into a. class file, parse and execute the. class file, and use it to enable java to implement platform-independent features. Automatic Memory Management is implemented. The existence of garbage collection removes the need to focus on memory allocation and release during programming. I. Memory Zone

JVM clearly divides the memory.

Start with Program Execution

To better understand the associations between different regions in the memory area, we can start with the execution of a program.

1. to execute a program, the virtual machine must first parse it, convert the program to a format that can be recognized by the virtual machine, and place some classes, compiled code, and always brightMethod Area.

2. A program starts from the main () method. We all know that the main () method actually corresponds to a thread. Therefore, to execute a method, you must first establish a thread, so there will beVirtual Machine StackThe method is controlled through the out stack and in the stack mode during method calling. At the same time, in order to ensure that the program can return to the correct position for further execution when multiple threads are switched, each thread is assigned a correspondingProgram counters. There are virtual machine stacks, and java local methods also have correspondingLocal method StackUsed to manage local methods such as wait and signal.

3. When the program is executed and a new object is createdHeapAllocate memory for it, and store the corresponding reference in the stack to point to the object instance in the heap.

In additionConstant poolUsed to store constants in the program.Direct MemoryAs a memory independent of the Data zone of the VM runtime, some local methods can directly use the memory outside the heap.

Runtime data Zone

The method area, Java Virtual Machine stack, program counter, local method stack, heap, and constant pool mentioned above all belong to the jvm runtime data zone.

Shows the internal architecture of an abstract virtual machine.

Ii. Garbage Collection

There is a "high wall" between Java and C ++ that is surrounded by dynamic memory allocation and garbage collection technologies. The people inside the wall Think About It. This is garbage collection. Garbage collection is not created in java, and the earliest garbage collection was produced in the god-like Lisp Language.

In java, all objects are allocated to the heap for unified management. Compared with the advantages of using this unified management method when various threads open up storage objects independently, my understanding is that unified management is conducive to making full use of the memory and facilitating management, when memory is recycled, every thread can use it because the idle area is shared, maximizing the space usage.

To dynamically manage the memory space, garbage collection is automatically performed. To solve the following problems:

1. What objects need to be recycled?
2. How to efficiently recycle garbage?
3. When will it be recycled?
Next, we will discuss these issues.

1. What objects need to be recycled?

To recycle objects, make sure that they are recycled when they are no longer used by the program. That is, this object is no longer "alive ".

To determine whether an object is still alive, there are mainly

1) reference counting method. This method adds a reference counter for each object. Every time a counter is referenced in a place, the counter is added. When the reference is effective, the counter is reduced by one. This method is simple and convenient, but it cannot solve the problem of circular reference.

2) Accessibility analysis. This is the mainstream implementation method in various languages. He uses a series of GCRoots objects as the start point to perform a downward search. If no path can reach an object, the object is considered inaccessible, that is, the object is no longer "alive. Objects that can serve as GCRoots include objects in the Virtual Machine stack, objects with static properties in the Method Area, constant objects in the Method Area, and objects referenced in the local method stack. Other surviving objects can be reached through the reference chain of these objects.

2. How to efficiently recycle garbage?

Find the objects that no longer exist in the program. The next step is to clear the objects to release the memory space. There are two main solutions: Clear the objects to be recycled, or sort useful objects in a way similar to Windows disk, and release other spaces. Therefore, there are currently several garbage collection mechanisms:

1) Mark to clear.

Mark the object to be recycled and release the memory. This solution is convenient and fast, but will produce a large amount of memory fragments.

2) Tag-Sort algorithms.

Mark the objects to be recycled, and move the surviving objects to one end in the same way as the Windows disk. This method does not produce memory fragments, but the efficiency is low. If the number of surviving objects is large, it will be a tragedy.

3) copy the algorithm.

Divide the memory into two equal-size areas. When one area is used for GC, the surviving data is copied to the other area. This method is convenient and does not produce memory fragments, that is, the utilization is too low. Considering that a large number of objects are "active and dead" in actual situations, the upgraded replication algorithm divides the memory into Eden and logical VOR ), eden is used to allocate and use normal objects. When recycled, the surviving objects are copied to the same vor area. In this way, the memory usage reaches 80%, which is much better. However, what should I do if there are many inventory objects at a GC and the VOR region is insufficient? You need to assign a guarantee.

4) Generational collection

Java heap is divided into the old age and the new generation. For the new generation, the replication algorithm is used. In the old age, Mark-clear or mark-organize is used.

3. When will it be recycled?

In java, there is a System. gc () method. However, this method only recommends JVM garbage collection, and the final decision is controlled by JVM.

When the space of the new generation of Eden cannot allocate new objects, the VM performs a Minor GC operation.

New Generation GC (Minor GC): refers to the garbage collection action that occurs in the new generation. Because most Java objects have the feature of extinction, Minor GC is very frequent, generally, the recovery speed is also relatively fast.

GC in old ages (Major GC/Full GC): refers to the GC that occurs in old ages, where Major GC occurs and is often accompanied by at least one Minor GC (but not absolute, in the collection policy of the Parallel Scavenge collector, there is a policy selection process for direct Major GC ). The speed of Major GC is generally 10 times slower than that of Minor GC.

Iii. Class Loading Mechanism

After writing a java class, it must first be compiled into a. class file. Then, you need to load the. class file to the virtual machine through the class loader to run. Set. the byte Transfer of the class file is converted to a format that can be recognized by the Virtual Machine (converted to java. lang. an instance of the Class), that is, the behavior of parsing the binary stream and loading the memory, is the behavior of the Class loader.

Why is there a class loader?

To achieve platform independence, java compiles all classes into. class files. to parse. class files, the appearance of the class Loader becomes natural. It's just that this name sounds a little more advanced. In my opinion, it's a file parser.

The important thing about the class loader is that it loads classes during program execution, which makes class operations more flexible. For example, during program execution, A. class file can be transmitted over the network and loaded to the class for execution. During program execution, some behaviors (ioc) can be dynamically added to the class )...

What has the classloader done?

For example:

1. Load: search for and load binary data of the class.

2. Link:
Verify: ensure the correctness of the loaded class.
Preparation: allocate memory for static variables of the class and initialize it as the default value;
Resolution: converts a symbolic reference in a class to a direct reference.

3. Initialization: Assign the correct initial value to the static variables of the class.

Parent-parent Delegation Model of the Class Loader

I think this is a very important concept of the class loader. Although implementation is very simple, there are only several inherited relationships.

Let's look at the figure:

The top BootStrap class loader is a local method used to load the specific class libraries required for running <JAVA_HOME> \ lib, such as rt. jar.

ExtClassLoader, used to load extension classes in <JAVA_HOME> \ lib \ ext.

APPClassLoader, an application class loader, is responsible for loading the jar files on the user-specified class path. developers can obtain the jar files through the getSystemClassLoader () method.

The hierarchical relationship between the class loaders is called the parent-parent Delegation Model of the class loaders (Parents DelegationModel). In this way, when the lower-level class loader needs to load a class, it will first delegate the upper-level class to load. If the upper-level class loader cannot load, it will be processed by the lower-level class. (Of course, you can also leave this specification aside and load all classes by a custom Class Loader .) The advantage of following the Parent-Child delegation model is that the top-level class is required by the jre, such as the Object class. In this way, even if you customize an Object class, it will not be loaded (because the top layer will still load the most basic class of the system), that is, it can ensure that the base class library will not be overwritten.

Application scenarios of custom class loaders

First, we need to know that the purpose of the custom class loader is to perform some custom operations after reading the. class file and then load it into the corresponding class.

Encrypted transmission is required. class file. after the class file is encrypted, the default class Loader cannot correctly identify the file content. Therefore, you need to customize the class loader to decrypt the file, it is then loaded by the application class loader. In the cglib and asm packages, You need to modify the byte stream of. class before loading it by the class loader. To realize the visibility between modules, OSGI creates a class loader for each module. 4. Support for concurrency

Why does JVM talk about concurrency? Because of multithreading. How to Implement multithreading? How can we solve the problem of data competition among multiple threads? These are all considerations for virtual machines.

1. multi-thread support for virtual machines

A Java memory model is defined in the Java Virtual Machine specification so that its access to each platform can achieve consistent memory access results. Before that, mainstream programming languages (such as C/C ++) directly use the memory models of physical hardware and operating systems. Therefore, due to the differences in memory models on different platforms, it is possible that the concurrency of the Program on one platform is completely normal, while the concurrent access on the other platform often fails. Therefore, in some scenarios, you must write the program on different platforms.

Java Memory Model

Each thread has its own working memory and the main memory shared by each thread. All variables are stored in the main memory. The thread needs to COPY Copies of the variables to the working memory through specific operations (read and load). In other words, the thread can only directly access its own working memory. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Kernel + kernel/vfjQ0LLZ1/kernel + KOpIKO61/kernel/o6zL/kernel + kernel/ssW/kernel + kernel/o6zL/LDR0ru49rHkwb + kernel/ examples/samples + samples/fE2rTmtcSx5MG/o6zL/samples + Na00NDS/cfmo6wgw7 + 1sdDpxOK7 + samples/samples + samples/a1vdK7uPa4 + LHkwb + samples/Samples/ fE2rTmtcSx5MG/o6zL/release/fTw9Pa1vfE2rTmtcSx5MG/o6zL/release/1tChow0KPHA + release/release + DQo8aDQgaWQ9 "multithreading implementation"> multi-thread implementation

Multi-threaded implementation is more relevant to the operating system than virtual machines. We all know that there are three ways to implement threads:

Use the kernel thread.

This implementation method is directly implemented by the thread controlled by the operating system kernel. Users often use an advanced interface of the kernel thread-Lightweight Process (LWP), which is implemented by threads in the general sense. The threads in a program correspond to the kernel threads.

This method is easy to implement, but all calls need to be switched to the kernel state for operations. Therefore, system calls produce a high price for switching.

Implemented using user threads

Threads fully built on the user space can be understood as simulating the effect of multithreading using a kernel-state thread. This method is flexible and does not need to be switched to the kernel mode for operations, greatly reducing the overhead. However, because the underlying layer of the user thread is still a thread, if the underlying kernel thread is suspended, all user threads Based on the kernel thread will be suspended unconditionally. In addition, the implementation is very difficult.

Implementation using user threads + lightweight threads

This method maps all created threads to one kernel thread, which is different from pure user threads. It maps N user threads to M kernel threads. In this way, it not only retains the high flexibility and low operation cost of user threads, but also avoids the risk that all user threads will be blocked due to kernel thread blocking.

2. Thread Security

In Java, thread security is classified into five categories from strong to weak. Immutable, absolute thread security, relative thread security, thread compatibility, and thread opposition.

Immutable. This is the simplest method of control. The final object does not change because its status does not change and there are no unsafe factors. For example, the String type in java is absolutely thread-safe. Regardless of the runtime environment, the caller does not need any additional synchronization measures, which ensures thread security. In fact, most classes cannot guarantee this. Relatively thread-safe. It needs to ensure that the separate operations on this object are thread-safe. We do not need to do any extra safeguard measures during the call, but for some sequential calls, you may need to use additional Synchronization Methods on the caller to ensure the call is correct. Most of the thread-safe classes we currently use are like this. For example, individual operations such as get, add, and remove of vector are thread-safe, but if continuous operations are required, such as after getSize, then, get all the element output requires external independent synchronization to ensure the correctness of the data (otherwise, the data obtained may be inaccurate due to the removal of the halfway through data ). Thread compatibility. For example, the ArrayList and HashMap we are familiar with are thread-safe, but we can use external synchronization methods to safely use thread opposition. Thread opposition refers to the code that cannot be used concurrently in a multi-threaded environment regardless of whether the call side adopts the synchronization measures. This situation is rare. An example of a Thread opposition is the suspend () and resume () Methods of the Thread class. If two threads hold one Thread object at the same time, one tries to interrupt the Thread and the other tries to recover the Thread, if concurrent execution is performed, the target thread has a deadlock risk regardless of whether the synchronization is performed during the call. If the thread interrupted by suspend () is the thread that is about to execute resume, the deadlock will surely occur. Thread Security Implementation Method

1. mutex Synchronization

In this way, the synchronized keyword is used to synchronize some operations. If a thread is in the synchronized critical section, any other thread entering the critical section will be blocked and enter the waiting queue.

2. Non-blocking Synchronization

Compared with the method in which the thread in the previous middle will block the way into the waiting queue, considering the large cost of thread status switching, in many cases, the thread will be able to obtain the lock after waiting for a short period of time, introduced an optimistic concurrency mechanism-non-blocking synchronization. When the synchronization block is entered, if the lock cannot be obtained, the lock will be continuously obtained through the while loop until the lock is successful.Spin lockIn this case, you can set the number of spin operations. If the number is exceeded, the thread suspends and waits. JDK1.6 introduces more advancedAdaptive spin lockThe number of spin times can be automatically set based on the previous lock spin and the lock time. So smart!

 

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.