Hello! Hello everyone, I am Xiaoqi, an untrustworthy programmer xiaoqi is going to share some technology in a light-hearted and humorous conversation. If you think you have learned something from Xiaoqi’s article, please give xiaoqi a like

preface

As a Java programmer, the Java Virtual machine is a skill point that we don’t have to learn to move bricks to work, but why do we need to talk about it? Is it to waste everyone’s 1 minute of precious time, a person 1 minute, 500,000 people is 1 year, 50 million people is 100 years, earn, small strange with his own success to hang a person (blood earn).

Of course not, and xiaoqi’s article is not so many people read, at most also waste a kidney bar.

Learning the Java virtual machine becauseThe interviewer has to ask! So we have to learn, what? Don’t you learn what isn’t practical? The neighbor xiaoqi can be hard to learn, when the interviewer as long as xiaoqi do not want you.As for why the interviewer asked about Java virtual machines, well… I’ll leave it to you the next time you go to an interview and the interviewer asks, “Tell me about the Memory model of the Java virtual machine.” You: “Hello, interviewer, why do you want to ask about Java virtual machine, you give me a computer, IFive minutesSet it up for youLibrary management systemDoesn’t he smell good? We’ll see it on the keyboard.” The interviewer will tell you the answer, and you can type your answer in the comment section to let Xiaoqi and other friends know exactly why you are asking.

The interview

On a sunny Sunday, I went to the park, a strange (don’t ask why is on Sunday, q) is 997, but in order to fill the stomach of the working people, only knowing that mountain tiger, race row), sitting in a strange room, waiting for HR little sister to call the interviewer, at this time my mood as mixed as your friend, will worry that the interviewer asks hard to? What should I do about my knowledge blind spot? Do you want to brag about my relationship with Kiki when we introduce ourselves later?

A handsome, eyes sharp the interviewer came in and saw the sharp, seemed to be able to see through all of his eyes, I don’t think or we’ll be 20 k, 8 k, the interviewer will not fool saw, but I think just before I came to see the small series of boring to learn programming, I have learned the essence of little odd, I immediately came to the confidence, decided to want 30K, not to learn small odd lai do not go (ha ha)

Interviewer: Xiaoqi, right? Did you bring your resume?

I: didn’t take, now color print two piece, my resume five piece, every time interview all want to spend ten piece, my friend said haven’t work first let you pay for the work don’t go.

Interviewer:… So what are you gonna do to get me to hire you

Me: Temperament?

(Instead of calling security, the interviewer brought out my waiting stick from behind the door. I lost my nerve.)

(I had to pull it out of my backpack from the other company I had failed this morningResume requestedThe morning went like this. The morning interviewer:That’s all for today’s interview. Go home and wait for the announcement! Me: Hello, interviewer. If you don’t want to hire me,Can I have my paper resume back, pleaseI have another interview this afternoon. Morning interviewer: I said your resume how wrinkled, originally you have been recycling ah! How long have you had this symptom? I:A half month…).

(Only after I handed in my crumpled resume did the interview continue…)

Java virtual machine memory model

Interviewer: I see Java virtual machine proficiency on your resume? (Hum, the interviewer gives a contemptuous smile.)

(at this time my heart very nervous, nervous is not the interviewer got me by asking, but if the virtual machine that I answer too professional interviewers don’t understand how to do, he answered to do, if you don’t believe me when I peeked hide me under the table of the deep understanding of Java virtual machine, if he does not believe that I will take out the book to confrontation with him)

I: also don’t calculate be proficient, all be peer people uplift love.

Interviewer: Tell me about the memory model of the JVM

Me: The JVM virtual machine has a runtime data area, which is mainly divided into program counters, virtual machine stack, local method stack, heap, method area

Interviewer: HMM. If we were to create a new object, where would we put it?

I:

Interviewer: HMM. Let’s say int defines a variable where does number go?

Me: in the stack

Interviewer: HMM. The young man is really precious words such as gold ah, can you introduce in detail what these several areas are

I: Then I will show you…

1. Program counter: Simply speaking, each thread has A record of which line it executes when executing code. For example, thread A has A program counter to record line 10 when thread A executes line 10. Program counters are private in the thread. So what’s in it for him? Although we can use multithreading to develop development, but the execution of A CPU thread thread B will need to wait for, wait until the CPU to perform A thread B thread needs to wait for again, so if this time to execute the CPU thread B, then coming back after execution of the executed know before when I was A thread to which line, You can continue from this line.

2. Vm stack: Virtual machines as well as the program counter, stack and thread private, virtual machine is the stack is to store the execution method used in some of the information, such as the method in the implementation of the virtual machine will create a stack frame is used to store the local variables are local variables (list), the operand stack (if you want to make some number of calculations, The number will be read into the operand stack for operation and then assigned to the local variable table), dynamic link, method exit and so on.

3. Heap: The heap is shared by threads. The heap is the largest chunk of memory managed by the VM. So our newly created object is in the heap.

4. Local method stack: The local method stack is used to execute local methods. For example, in Java, we will see many Native methods, which are written in C language and only called in Java.

5. Method area: The method area is shared by threads and is used to store type information, constants, static variables, etc., that have been loaded by virtual machines. In the methods section also contains a runtime constant pool part, this part is used for storing compile-time generated a variety of literal and symbolic references, this part will be deposit to the method after class loading the runtime constants in the pool, the so-called symbol is actually a reference application such as the main method this method reference into a pointer, It is much faster to find the actual location of the method on disk

Interviewer: HMM. Can, the answer is very comprehensive, how to learn to improve at ordinary times?

Me: Read Xiaoqi’s article (at this time I really want to give xiaoqi’s article a thumbs up)

Interviewer: Tell me about the object creation process

I :(also want to rest will drink saliva, so soon asked the next knowledge point, I secretly turn over the book to see…)

When the virtual machine receives the new Student() command, it checks the constant pool to see if the Student() class has a symbolic reference, and if the class has been loaded, parsed, and initialized, it needs to load, parse, and initialize the class first.

Interviewer: HMM. So how do I allocate memory to an object when I create it? What are the methods?

Me: You can use pointer collisions, free lists, etc.

Pointer collision: If heap space there is no data, and heap space is the space of a square, so we use a pointer on the starting position, which is close to the edge, this time there is a take up 1 m object to create, then our pointer is starting from the initial position from 1 m distance from left to right, this time there is a 10 m object to create, Our pointer moves 10M further to the right from where it is now, and a 1G object comes along. If the pointer goes to the right and it doesn’t go one gigabyte, you can’t create this one gigabyte object. Free list: Pointer collisions are used when the heap space is contiguous. If it is not contiguous, space cannot be allocated from left to right. In this case, the free list is used.

Interviewer: HMM. So we just created an object, can you tell us what the memory layout is inside the object?

I :(really to dig in ancestral grave… Read a book secretly

The object can be divided into three parts: object header, instance data, and alignment padding.

Interviewer: Uh… Can you expand on that, so people can answer it

Me :(just look at the book, can’t remember so much ah, forget to brave to come)

Object header: The object header stores the object’s own runtime data, such as hash code, GC generation age, lock status flags, thread-held locks, bias thread ID, bias timestamp, and a pointer to its type metadata (through which to determine which class the object is an instance of).

Instance data: This section is the information that we actually define in the object, such as some fields in the object, as well as some content inherited from the parent class and fields defined in the subclass.

Alignment padding: This part is not available for every object, because the virtual machine requires that the object’s starting address be a multiple of 8 bytes. If our instance data is only 4 bytes, we need to padding another 4 bytes to ensure that the object’s starting position is a multiple of 8 bytes. .

Garbage collector and memory allocation strategy

Interviewer: HMM. How does a virtual machine determine if an object is garbage

I :(so fast and change the next knowledge point, when can drink saliva…)

Reachability analysis algorithm and reference counting algorithm can be used to determine whether an object is junk.

Interviewer: HMM. Go on

I:

Reachability analysis algorithm: will start from a “GC Root” Root and search down based on the reference relationship. If the object cannot be found, it proves to be garbage.

Reference counting algorithm: Is when an object is referenced in this object references in the counter to add 1, if the reference fails, the value of the counter will be minus 1, when the object reference counter to 0 will prove that the object is garbage objects, this algorithm has a disadvantage, however, is the time when the two objects refer to each other will think that two objects are not garbage objects, However, these two objects are caused by the problem of circular dependency, which should be cleaned up, but this algorithm does not solve the problem of circular reference.

Interviewer: HMM. What are the garbage collection algorithms?

Me :(dichotomy, thirds, four… No, how do I feel back string, or not woven, secretly read the book)

Mark-clear algorithm, mark-copy algorithm, mark-tidy algorithm

Interviewer: HMM. Can you talk more about the specific content of the algorithm?

I:

Mark-clean algorithm: this algorithm is mainly used for garbage collector of an area of memory. After marking, the garbage collector does the clean operation directly and does not do subsequent operations.

Mark-copy algorithm: This algorithm is mainly used for garbage collector of two memory areas, mark the live objects, then put the live objects into the reserved area, and then clean up the previous area for the next reserved area.

Mark-collation algorithm: This algorithm is mainly used for garbage collector of an area of memory. It differs from the mark-clearing algorithm in that it recollates the surviving objects in the area of memory so that the remaining space can be contiguous.

Interviewer: HMM. Can you tell me what the garbage collectors are?

I :(three V meat, climb cattle, climb V meat dead cut stomach juice, three V meat accidentally, climb V meat accidentally, CMS, G1, ZGC, I think or draw it out, after all, my English level read out the interviewer may doubt life)

1, Serial collector (three V meat)

The Serial collector, the most basic and oldest, is a single-threaded collector.

2. ParNew collector (climbing bull)

The ParNew collector is essentially a multithreaded parallel version of the Serial collector that can use multiple threads simultaneously for garbage collection.

Hunt insane. 8. Parallel avenge

The Parallel Collector is a new generation collector based on the mark-copy algorithm. The goal of the Parallel Scavenge is to achieve a controlled throughput, which is the ratio of the amount of time the processor spends running user code to the total amount of time the processor consumes, i.e.

4, Serial Old collector

Serial Old is an older version of the Serial collector, which is also a single-threaded collector.

5, Parallel Old collector (climb V meat occasionget)

The Parallel Old collector is an older version of the Parallel Avenge collector that supports multi-threaded Parallel collection and is based on the mark-collation algorithm.

6. CMS collector

The CMS collector is a collector whose goal is to obtain the shortest recovery pause time. Its operation process is divided into four steps, including:

1> Initial tag

2> Concurrent flags

3> relabel

4> Concurrent cleanup

Initial tag: The initial tag needs STW, and the initial tag simply marks objects that GC Roots can be directly associated with, which is fast.

Concurrent marking: The concurrent marking phase is the process of traversing the entire object graph from the directly associated objects of GC Roots. This process is time-consuming but does not require the user thread to be paused and can be run concurrently with the garbage collection thread.

Relabelling: The relabelling phase corrects the marking record of the part of the object that is marked as the user program continues to operate during the concurrent marking phase. The pause time of this phase is usually slightly longer than that of the initial marking phase, but much shorter than that of the concurrent marking phase.

Concurrent cleanup: This phase of cleanup removes dead objects judged by the marking phase. Since no live objects need to be moved, this phase can also be concurrent with the user thread.

Garbage First collector (G1)

G1 no longer insists on a fixed size and a fixed number of generational regions, but divides the continuous Java heap into multiple independent regions of equal size. Each Region can act as the Eden space of the new generation, Survivor space, or old chronospace as required. As shown in figure.

The OPERATION of the G1 collector can be roughly divided into four steps:

Initial tag: Just mark the objects that GC Roots can be directly associated with,

Concurrent marking: Reachability analysis of objects in the heap is performed starting with GC Root, recursively scanning the entire heap object graph for objects to reclaim. This phase is time-consuming, but can be performed concurrently with user programs.

Final mark: Another short pause is made on the user thread to deal with the last few SATB records that remain after the end of the concurrent phase.

Filter recycling: You can update the statistics of a Region, sort the reclamation value and cost of each Region, and make a reclamation plan based on the pause time expected by users. You can select multiple regions to form a collection and copy the surviving objects of the Region to an empty Region. Then clean up the entire old Region. The operation here is designed to move live objects in such a way that the user thread must be paused, and multiple collector threads are done in parallel.

Interviewer: HMM. Can you talk about the JVM heap memory model?

I:

The heap memory model is divided into young generation and old generation. The young generation is divided into Eden region and Survivor region, and Survivor region is divided into S0 region and S1 region.

Interviewer: HMM. Can you talk a little bit about object circulation and recycle strategies in the heap?

Me :(that’s a lot… Said I don’t know if you can understand ah, forget it, not take out my book hidden under the table to tell you)

The object is allocated in Eden first: A new object will first be placed in Eden area. When Eden area is full, the surviving object in Eden area will be put into S0 area in Survivor area, and then Eden area will be emptied. In this case, the new object will still be put into Eden area. When Eden is full again, the viable objects in Eden and S0 will be removed and put into S1, and Eden and S0 will be cleared. When Eden is full again, the viable objects in Eden and S1 will be put into S0 together. That is, the loop takes the surviving objects in Eden and Survivor in one of Survivor regions and puts them in another Survivor region. In this loop, the GC age of the object increases by 1 each time, and when the GC age reaches 15, it will be moved to the old age. The GC in the old era can be called light GC, which takes a shorter time. When the old era is full, heavy GC will take a longer time.

Long-lived objects in the old age: objects in the young generation loop back and forth 15 times (by default, this number can be set) to put the object in the old age.

Large object directly into old age, when the newly created object is bigger we can put him in the old s directly, so that we can avoid back and forth in the young generation copy overhead caused by the specific how much object is large object we can according to – XX: PretenureSizeThreshold parameters to set.

Dynamic object age determination: If the total size of all objects under or equal to a certain age in the Survivor space is greater than half of the size of the Survivor space, then objects older than or equal to that age can enter the old age directly without waiting until the age reaches 15. If the largest object is now 10, but the Survivor space is half used, If no object reaches 15, the Survivor zone will be full, so the older object will be put into the old age in advance.

Space allocation guarantee: Before light GC occurs, the virtual machine checks whether the available space of the old generation is greater than the total space of all objects of the new generation. If so, even if all objects of the new generation are not garbage objects, then the old generation will be allowed. If not? The virtual machine checks whether a parameter is set to allow guarantee failure. If yes, the virtual machine determines whether the remaining space of the old age is greater than the average size of objects from the new generation to the old age. If it is larger, it will perform light GC and put the new generation survivable objects into the old age. This time it is risky because it is possible that this time the light GC will survive more than the average of the previous light GC, which will cause the old age memory to overflow directly. If it is smaller, a redo GC is performed to free up the space of the old generation, ensuring that the live objects of the younger generation can be put into it. If the configuration parameter is not allowed to guarantee failure, then every time we reach the old age remaining space is not the total space of all objects of the new generation, we will do a re-GC to clear the old age space first.

Interviewer: Sure, the young man has something

Me: ok (something you don’t give me some water to drink…)

Vm performance monitoring and troubleshooting tools

Interviewer: Just now it is all conceptual. Now I ask you some practical things. What are the methods of monitoring virtual machine performance?

Me :(just wanted to take a break… I would have said “Java Virtual machine” if I had known I was proficient in Java virtual machines.

JPS: tool for vm process statusCommand format: JPS [options] [hostid] JPS -l You can run the JPS -l command to view the full name of the main class. If the process is running a JAR package, the jar path is displayedThe JPS -v command displays THE JVM parameters when a VM process is started

Jstat: monitors vm statisticsCommand format: Hostid [options] hostid [ms] [count] jstat [options] hostid [ms] [count] Jstat -gc 66320 250 20

Jinfo: Java configuration information tool Jinfo is used to view and adjust VM parameters in real time.

Jmap: Java memory mapping tool The jmap command is used to generate heap dump snapshots.

Jhat: vm heap dump snapshot analysis tool The jhat command is used together with jmap to analyze heap dump snapshots generated by jmap.

Jstack: Java stack tracing tool The jstack command is used to generate a snapshot of a VM thread at the current time.

Interviewer: These are your commands. Are there any visual tools for troubleshooting virtual machines?

I: can use JDK built-in VisualVM visual tool command: jvisualvm

Interviewer: That’s a good guy. I don’t have any more questions for you. Do you have any more questions for me?

Me: Uh… Could the interviewer give me my paper resume? Could you please not write on my resume? I need to use it in the interview tomorrow.

Interviewer: What other companies to meet, come to me, the conditions open

Me: 100K then (the interviewer picks up his stick again)

Interviewer: If you don’t come, please recommend someone else to come to my office for an interview

I :(at this time I gave my in-depth understanding of the Java virtual machine book to the interviewer, and told him) you have a good study of the Java virtual machine, fortunately only I came today, if it is small strange loyal readers came, you will be abused of the very miserable. (I turned around and left only a handsome figure)

conclusion

Java virtual machine is a basic and a little esoteric things, so we want to collect after careful and repeated to learn, if you think my article is good, then click a like it.