Unveil Java memory management and java Memory Management

Source: Internet
Author: User

Unveil Java memory management and java Memory Management
Preface

Compared with high-performance languages such as C and C ++, Java has the function that envy such programmers: Automatic Memory Management. It seems that Java programmers do not have to worry about memory or know relevant knowledge. But is the result true? Especially for Android programmers like ours, it is a nightmare to eat to the dead of memory when there are complicated memory leaks and overflow problems. Therefore, a general understanding of Java memory management seems to have become a required skill for qualified Android programmers. Even New Kotlin is also based on JVM. Let's take this opportunity to unveil it together.

 

 

Object

Java is an object-oriented programming language, which has always been a saying: Everything is an object. Therefore, Java memory management can be understood as the creation and release of objects. So what is the object? Boyfriend? Girlfriend? Or? What is the relationship between objects and memory? There are too many problems here. Let's take a step.

Tips1: take common Virtual Machine HotSpot, common memory area Java heap, and common Java object as an example. Tips2: if you have read "deep understanding of Java Virtual Machine", you don't have to read it. Please go to the upper right corner. If you forget, continue!
Concept

Boyfriend or girlfriend you can understand as an object. Objects actually exist, such as Dad and Mom. At the same time, they are accompanied by an abstract concept. Class: they are abstract objects, both boyfriend and girlfriend are human beings. The concept is almost introduced here. I feel like I am in college... My day (cover your face ).

Object and memory Creation

What if a programmer has no daughter-in-law? New. Old, simple, tall, short, thin, fat, and whatever you want. The only thing you don't regret in this life is being a programmer, although it's a bit cold.

 

 

New is the creation of an object. What is the process? When the JVM encounters a new command, it first checks whether the parameter of this command can be located in the constant pool as a symbol reference of a class, check whether the class referenced by this symbol has been loaded, parsed, and initialized. If no, you must first execute the corresponding class loading process. After the class loading check is passed, you can say that the model of an object has come out, but Java is only a programming language after all, still need to allocate memory? Otherwise, what should I do?

Allocate

The allocation of object memory is the same as that in many real scenarios. For example, in some scenarios, there may be only 100 parking spaces. First come, stop at the first vacant space, in this way, one vehicle stops in order. Such allocation is called "pointer Collision ". There is also a way to stop where you want to stop, as long as you can plug in. Such an allocation is called an "Idle list ". Whether it is the former or the latter, we rely on our eyes to see the parking space, where there is space to stop, so how does JVM "look? The former relies on a pointer as an indicator, and the size of the memory allocated to the object will be moved back. The latter maintains a list to record the available memory (Pluggable parking space ).

Those who are sensitive to concurrency will certainly ask questions. How can they be correctly allocated to the corresponding position during concurrency?Generally, there are two solutions: one is to stop one vehicle, to ensure that the previous vehicle stops, and the next one starts to stop; the other is the area where we say we want to stop, such as A, B, and C. Then A, B, and C will stop Zone A each time, it has nothing to do with other regions (the region refers to the thread). If they invite a friend D, I'm sorry. I can only wait until the others in other regions stop. You can stop again.Therefore, object creation is not an atomic operation. Remember to remember.

 

 

Layout

We already know where the car is parked. How can we stop it? Some people like to stop while others like to stop. Similarly, how are objects placed in the memory? It consists of three parts: object Header, Instance Data, and Padding ).

After all, this concept is too strong.

The object header contains two parts of information, the first part is used to store the runtime data of the object, such as the hash code, GC generational age, lock status mark, lock held by the thread, biased thread ID, and time stamp; another part is the type pointer, that is, the pointer to the class metadata of the object. The VM uses this pointer to determine the class of the object. I don't understand the terms mentioned above. I may explain it in subsequent articles. After all, I am still learning the terms. If you want to know the terms, you can refer to the relevant materials, remember it as a concept.

The instance data is easy to understand. It is the valid information that the object actually stores and the various types of fields defined in the program code.

Alignment filling does not exist because the memory management system requires that the initial address of an object must be an integer multiple of 8 bytes. In other words, the object size must be an integer multiple of 8 bytes. The size of the object header is an integer multiple of 8 bytes. Therefore, if the instance data size is not an integer multiple of 8 bytes, you need to fill in alignment.

Access

After you stop the car, you have to drive home. Do you have to find your own car? How to find it? Which parking space do you choose? Remember your license? So how can we access our objects in the memory? Let's look at a group of figures:

 

 

 

 

The former is called handle access, and the advantage is obvious. If an object moves, you only need to modify the pointer in the handle and it does not involve reference. The latter is called direct pointer access, which has obvious advantages, it is fast, and the handle layer is directly missing. The HotSpot discussed in this article uses the latter.

Reclaim

What should I do if a car is blown up? Of course, I bought a new one (manual giggle ). So how can we determine that an object is not shit? Before that, we introduced two kinds of reference algorithms: the first one is to reference the counting algorithm. It is easy to understand that, to give the object a counter, the initial value is 0. If there is a local reference, add 1, and if it fails, subtract 1, the counter is 0. The second is the accessibility analysis algorithm, which is also easy to understand. It starts from GC Roots and references objects downward, if an object has a path from GC Roots to itself, it means the object is still alive, otherwise it will crash. For example, object567 is shit:

 

 

Which functions can be used as GC Roots?

  • Objects referenced in the Virtual Machine stack (the local variable table in the stack frame)
  • Objects referenced by class static attributes in the Method Area
  • Objects referenced by constants in the method Area
  • Objects referenced by JNI (Native method) in the local method Stack

Our HotSpot uses the latter. Why didn't we use the former? It is difficult to solve the issue of circular reference between objects. For example:

ReferenceCountingGC objA = new ReferenceCountingGC();ReferenceCountingGC objB = new ReferenceCountingGC();objA.instance = objB;objB.instance = objA;objA = null;objB = null;

So the question is, is it true that the unattainable object is shit? Of course not. At least two marks will be used to declare the death of an object. The first mark indicates that the object is inaccessible, and the finalize () method or the finalize () method has been called by the virtual machine, can be recycled (isn't it marked only once at this time? Are you sure you want to answer this question?) the remaining objects will be placed in the queue of F-Quenue, And the GC will mark these objects for the second time and execute finalize () the method is also the time to save yourself (as long as you re-establish the association with other objects on the reference chain in the method ).You 'd better forget the existence of this method. It runs at a high cost and has great uncertainty, and cannot guarantee the call sequence of each object. Avoiding this method is also mentioned in objective Java.

The Simple Analysis of objects is almost over here. Do you think it's all over here? Naive.

 

 

What are the terms such as the Virtual Machine stack, Method Area, and Java stack?

Runtime data Zone

International Convention, No picture, say a J8!

 

 

When you see this picture, you must know what I want to do... I don't want to, either. It seems like I wrote it in plain text. My God, I am a thief.

 

 

Program counters

The program counter is a small memory space, which can be seen as the row number pointer of the bytecode executed by the current thread. For example, basic functions such as branch, loop, jump, exception handling, and thread recovery depend on this counter. We can see from the figure that it is thread-proprietary, that is, each thread has an independent program counter and does not affect each other. And it isThe only region in which the Java Virtual Machine specification does not specify any OutOfMemoryError Conditions.

Java Virtual Machine Stack

The VM stack describes the Memory Model of Java method execution: each method createsStack frameStores information about local variable tables, operand stacks, dynamic links, and method exits. The process from calling to execution of each method corresponds to the process from stack frame to stack. Careful friends will find that the local variable table appears in the object access section diagram. What is important is that when you enter a method, the size of the local variable space to be allocated in the frame is completely determined. In other words, the memory space required for the local variable table is allocated during compilation.

In the Java Virtual Machine specification, two exception conditions are specified for this region: If the stack depth requested by the thread is greater than the depth allowed by the virtual machine, an StackOverflowError exception will be thrown; if the Virtual Machine stack can be dynamically expanded (most of the current Java virtual machines can be dynamically expanded, but the Java Virtual Machine specification also allows a fixed-length Virtual Machine stack), if the expansion cannot be applied for enough memory, an OutOfMemoryError is thrown.

Local method Stack

The role of the local method stack and the virtual machine stack is very similar. The difference between them is that the virtual machine stack executes Java (also known as bytecode) Services for the virtual machine, the local method stack is the Native method service used by virtual machines. Therefore, the exception thrown by the Java Virtual Machine stack is the same.

Java heap

You can think that almost all object instances are allocated on the stack. Isn't it all? This is an optimization technology. If an object cannot be accessed by other methods or threads through any channel, why not allocate it directly to the stack?

According to Java Virtual Machine specifications, Java heap can be in physically discontinuous memory space, as long as the logic is continuous, this also means that, if there is not enough memory to allocate and the heap cannot be expanded, an OutOfMemoryError will be thrown.

Method Area

The method area is the same as the Java heap. It is the memory area shared by various threads. It is used to store data such as class information, constants, static variables, and Code Compiled by the real-time compiler. However, in addition to the Java heap and Java heap, it does not require continuous memory and cannot choose a fixed size or the extended memory will throw an OutOfMemoryError exception. In addition, it can also choose not to implement garbage collection.

The data zone for running hours is almost introduced. Here we add a concept called direct memory. The NIO added in jdk1.4 is useful. If you are interested, you can check it out. Everyone must have noticed that there is a memory overflow in each region (except the program counter). Some people will ask when OOM will be generated, so don't say that there is not enough memory, it hurts.

 

 

Garbage collection Algorithm

The Java heap mentioned above can be said to be the largest part of the memory managed by virtual machines. It is a frequent occurrence of GC, and thus is also called the "GC Heap ". GC, as its name implies, is garbage collection, which is also a major advantage of Java. memory that is not used can be automatically recycled. Since it is garbage collection, there can be a garbage collection device, and a broom is used for sweeping the floor.

 

The figure below shows the hot spot garbage collector, which is a new generation and an old generation. I will not introduce the specific history of the garbage collector. It is not necessary. I hope you will have a rough understanding of it. So, if you have a spammers, you have to have a solution. You still need to use a straw for drinks. What is the principle of the straw? Don't you have to order 13? This section describes the ideas of several algorithms.

 

Mark-clear Algorithm

For details, first mark the objects to be recycled, and then clear the marked objects at a time. It can be said that it is the most basic collection algorithm, and even the algorithms introduced later are all improved based on it. Since improvements are made, there must be intolerable shortcomings. In addition to low efficiency, there is also a serious problem, even if a large number of discontinuous memory fragments are generated, we can see from the reason why we mentioned the OOM in Java, it is very easy to allocate, and the second execution of garbage collection, or direct OOM. Execution Process:

 

 

Copy Algorithm

This algorithm is easy to understand. It converts the available memory into two parts and uses only one of them at a time. When recycling, it copies the available objects to the other one and then cleans up the original one at a time, it can be said that the efficiency is greatly improved, but the fatal weakness is that the memory is halved.

 

 

Copy Algorithm Execution Process:

 

 

Tag-Sorting Algorithm

The replication algorithm is highly efficient theoretically, but if you think there are 100 objects, 98 of them are available, you have to copy 98 objects. In extreme cases, 100 objects survive, you have to copy it all over again, which is unacceptable. This algorithm improves the Mark-clear algorithm to generate a large amount of memory fragments. It first moves the available objects to one end, and then directly clears the memory outside the end boundary. Execution Process:

 

Generational collection Algorithm

From our analysis, we can see that the replication algorithm seems to be more suitable for objects that are born overnight, while the remaining two algorithms are more suitable for objects that are hundreds of years old. The regions where the objects are located are called the new generation, and the regions where the objects are located are called the old generation. Our generational algorithms use different algorithms based on the new generation and old generation.

So here is a question: How come objects in the old age come from? In other words, how can we enter the old age? First, analyze A special case: the large object enters the old age directly; then, the normal step is: Object A is preferentially allocated to the new generation of Eden space during allocation, when the Eden space is insufficient to allocate memory, A Minor GC will be performed. After that, object A will survive and be able to be accommodated by the kernel vor space, and then it will be moved to the kernel vor space, then, set the age counter to 1. After that, every time the object A spends Minor GC and is alive, the age increases by 1. When it reaches MaxTenuringThreshold, will be promoted to the old age (applaud ). Of course, this is not absolute. If the total size of all objects of the same age in the region vor space is greater than half of the region vor space, objects of the same age or age can be promoted directly.

The main content of this article has almost reached this point, leaving a key question at the end,How does the Garbage Collector perform garbage collection?? Here is an awesome term called "Stop The World ".

 

 

Miscellaneous

First of all, I want to explain that a deep understanding of the Java Virtual Machine (version 2nd) is really a good book. I have no chance to know such a great guy, nor can I talk about advertising, everyone who has read it should know it. Secondly, all the content in this article comes from the book, or even a word without a word. This article can be said that I have read the second part of this book: notes on the automatic memory management mechanism. Many of the concepts in this article are conceptual knowledge. For example, why is Earth called Earth? This is a convention, but for our Android programmers, it is best to have a general understanding of it, but not all of them have read the book (either bought or not ), therefore, I have shared this article, some of which are my own understandings. If you have any questions, I should correct them in time. You 'd better buy the original articles and read them carefully. Here I will introduce them to you --!

Learning a little bit every day is also excellent. Since it is learning, the object must have been summarized by some predecessors. What you should do is to understand it and convert it into your own things (translate it with your own ideas, the essence remains unchanged. Otherwise, it is called exploration. The other sentence is that the good memory is not as good as the bad pen. The teacher must have said this sentence, and I didn't even get into my ears.

If you have any questions during Java learning or want to obtain some learning resources, please join my Java learning and communication QQ group:495273252

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.