Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand Java jvm garbage collection

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to understand Java jvm garbage collection". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to understand Java jvm garbage collection".

Common interview questions

How to judge whether the object is dead or not

A brief introduction to strong reference, soft reference, weak reference and virtual reference

How to judge that a constant is an abandoned constant

How to judge that a class is a useless class

What are the algorithms and characteristics of garbage collection?

What are the common garbage collectors?

Introduce the CMS,G1 collector?

What's the difference between minor gc and full gc?

1.JVM memory recovery and allocation 1.1 major areas?

Generate objects first in Eden

Then after a gc, go to the survival area.

If the age is greater than the threshold, it will be upgraded to the old age.

Calculation of threshold

If the size of a certain age group is more than half of the survival area, then take the threshold or the youngest one as the new threshold to upgrade to the old age.

During gc, the from of the survival area and the surviving objects of Eden are copied to to, and then other objects are cleaned up, and then from and to exchange pointers.

Gc test

The scenario is to allocate enough space to the eden first, and then apply for a lot of space. The problem is that there is not enough space in the survival area.

At this point, the allocation guarantee mechanism will be triggered to assign excess objects to the old age, rather than triggering the full gc. Still monor gc.

Public class GCTest {public static void main (String [] args) {byte [] allocation1, allocation2; allocation1 = new byte [50900 / 1024]; allocation2 = new byte [9500 / 1024];}}

1.2 Big objects enter the old age

Avoid taking up a lot of time when copying tags and reduce the efficiency of gc

1.3 long-term living objects enter the old age

Every time gc will put the surviving objects of eden and from to to, and each time the survival age of gc will be + 1. If the threshold is exceeded, it can be upgraded to the old age. The parameter set is-XX:MaxTenuringThreshold.

The following is the method of calculation. The number of people of each age adds up. If the number of objects is more than half of the survival area, the threshold needs to be updated (newly calculated age and MaxTenuringThreshold).

Usually the promotion threshold is 15, but the CMS is 6

Uint ageTable::compute_tenuring_threshold (size_t survivor_capacity) {/ / survivor_capacity is the size of survivor space size_t desired_survivor_size = (size_t) (double) survivor_capacity) * TargetSurvivorRatio) / 100); size_t total = 0; uint age = 1; while (age)

< table_size) { //sizes数组是每个年龄段对象大小 total += sizes[age]; if (total >

Desired_survivor_size) {break;} age++;} uint result = age < MaxTenuringThreshold? Age: MaxTenuringThreshold;...} 1.4 the type of area gc that is mainly used for gc

Partial Gc

Young Gc: collect the new generation of

Old Gc: collect only the old ones

Mixed Gc: the new era and part of the old age

Full Gc: the new generation and the old will collect

Young Gc

Every time they collect the new generation and promote those who have survived for a long time.

Full Gc

If you find that the object to be promoted in the survival area has more memory space than in the old days, then do full Gc. Some virtual machines use young gc to clean up some of them to reduce the time consumption of full gc.

1.5 Space allocation guarantee?

Before jdk1.6, we need to determine whether the remaining space of the old age is completely larger than that of the new generation, and if so, we can carry out minorgc to ensure that there will be no problems. If it doesn't work, it will check-XX:handlePromotionFailure, that is, whether the average size of the promoted object is less than the remaining space in the old age. If so, then directly minor gc or full gc.

After jdk1.6, check directly the average size of the promotion of the new generation. If it is smaller than the old age, then it will be promoted directly.

two。 The object is dead?

2.1 citation counting method

In fact, every time it is referenced, the count is + 1. If the count is not 0, then it will not be recycled.

But the reason for not using it is circular reference dependency. If two objects refer to each other, the count will never be 0.

2.2 Reachability analysis

Gc roots as a starting point goes all the way to the following reference chain

Objects of gc Roots

Objects referenced by the virtual machine stack (the local variable table of the stack)

Objects referenced by the local method stack

Objects referenced by constants in the method area (objects referenced by constant pools)

Objects referenced by static properties in the method area

Objects held by synchronous locks

Java virtual machine internal references, such as basic types of Integer

2.3 talk about citation again

Strong reference: the garbage collector will not recycle him

Soft references: insufficient memory space will be recycled

Weak reference: gc is recycled

Virtual references: can be recycled at any time and need to refer to the queue

What is the difference between virtual reference, soft reference and weak reference?

The falsely referenced object is sent to the reference queue before gc, and the program does the corresponding activity (dying processing) before the object is collected.

Soft references are used the most, which can improve the efficiency of gc, maintain system security and prevent memory overflow.

2.4 unreachable objects may not be recycled

The object is marked once before recycling to see if the finalize method is executed. If not, these objects will be recycled first.

If so, mark it a second time and let the object perform finalize before recycling.

2.5 how can I tell if a constant is an abandoned constant?

If the constant pool object is not referenced by any object, it will be recycled

Before jdk1.7, the running constant pool contains a string constant pool, which needs to be copied to return a new reference (one for the heap and one for the constant pool).

When jdk1.7, the string pool is no longer running in the constant pool. If you call intern, the current object will be put into the constant pool and a reference will be returned (only the constant pool has one). If it already exists, the address of the object instance is returned.

After jdk1.8, the runtime constant pool has been moved to metaspace

2.6 what if it is useless to judge a class?

All instances of the class have been recycled

The class loader reclaims the

Class information is not referenced

A large amount of reflection and dynamic proxy generation class information will put a lot of pressure on the method area.

3. Why does the garbage collection algorithm hotspot distinguish between the old and the new generation?

The reason is that different living objects need different garbage collection algorithms.

If the new generation uses tagging, the problem is that a large number of objects are cleared at a time, which takes a long time to move and consumes a lot of finishing. But tag replication is fast because there are few surviving objects.

But in the old days, it would be good to use markup, because there is more survival and less movement, and replication is the opposite.

Can not be uniformly designed as weak generation hypothesis and strong generation hypothesis

Intergenerational collection hypothesis?

If the old age and the new generation quote each other, the age of the new generation will be lengthened. But in order to know when the new generation will be gc, you can add a memory set to the new generation (divide the old age into many squares, representing who quoted me) and avoid scanning the whole old age.

4. Garbage collector 4.1Serial collector

A single-threaded collector blocks other threads (STW) each time, and a garbage thread collects it separately

The new generation is mark replication, and the old age is mark arrangement.

It is simple and efficient, and there is no concurrency problem without exchanging with other threads.

But STW can lead to slow response

4.2ParNew collector

Multithreaded version of Serial, but still STW

The new generation is mark replication, and the old age is mark arrangement.

4.3Parallel Scavenge collector

The new generation is mark replication, and the old age is mark arrangement.

Unlike ParNew, it is completely concerned with the utilization of cpu, that is, the throughput of processing tasks, regardless of how long STW stops.

4.4SerialOld

The old version of Serial, used with Parallel Scavenge before 1.5, has other uses as a backup solution for CMS.

4.5Parallel Old collector

The old days of Parallel Scavenge collectors also focused on throughput.

4.6CMS collector

Focus on minimum response time

Garbage collector and user thread work at the same time

The initial tag records the objects directly connected to the gc root

Concurrent tags traverse the entire chain, but can run concurrently with user threads

Retag fixes the reference chain of updated objects, which is shorter than concurrent tags

Concurrent cleanup

problem?

Memory fragments are sensitive to cpu resources.

4.7G1 collector

At the same time, it can meet the needs of fast response and deal with many problems.

Characteristics

Parallelism and concurrency, using multiple cpu to execute gc threads to shorten stw, and can also execute concurrently with java threads

Generational collection

Spatial integration: using tag replication most of the time

Predictable pause: fast response time, stw time can be set

For inter-generational references between partitions, young uses rset (non-collection area points to collection area) record here. The old area points to me, and the old era uses card tables to divide many regions, so minor gc does not need to traverse all other areas to see if the objects in the current area have been referenced.

The first question about the nature of supplementary string pools is what do you do when String a = "a"?

First find out whether the constant pool exists an if it exists, then directly return the reference address of the constant pool, if it does not exist, create one in the constant pool and then return the reference address

What happened to the second question new String ("a")?

First see if an exists in the constant pool. If it does not exist to create one in the constant pool and create a separate an object in the heap to return a reference (instead of returning a constant pool), it is equivalent to creating it twice.

If the second creation discovery already exists, create the object directly in the heap.

The third question is the principle of intern.

Check whether the constant pool has this string. If not, create and return an address reference to the constant pool object.

If so, directly return the address reference of the constant pool object

String s1=new String ("a")

String s2=s1.intern ()

It is obvious that S1 is not equal to S2 if the above questions are clearly known. S1 refers to the heap, while S2 refers to the constant pool

The fourth question

String s3=new String ("1") + new String ("1")

String s5=s3.intern ()

String S4 = "11"

Are they equal in that place? Of course it's equal, S3 will put 1 in the constant pool, but it won't put 11 in the constant pool because it hasn't been compiled yet. The object is not stored in the constant pool until intern is called, and the object stored at this time is the one pointed to by S3. So S4 also points to S3. It would be different if S0 = "11". S3.intern will only return the object reference address of the constant pool, not S3, because S3 cannot repeat intern 11. Jdk1.6 is wrong anyway. Intern makes a copy instead of storing the object in the constant pool (because the string constant pool is in the method area, and jdk1.7 it is stacked, so references to S3 can be well preserved).

The correct analysis of the following code should be three true, but in test, 11 will be cached first leading to false, true,false problems.

String S8 = "good"; System.out.println (S6 = = S7); System.out.println (S7 = = S8); System.out.println (S6 = = S8);} finalize principle

But finalize is a daemon thread, which prevents some finalize from blocking the entire queue and affecting the efficiency of recycling.

The last tag is to mark the object in F-queue (if there is no reference) and then release

Finalize is actually implemented on the Finalizer thread. Then the reference queue points to the two-way linked list. Once gc is encountered, ReferenceHandler will be called to handle the finalize calls of these nodes. After the call, the nodes will be disconnected and the nodes will be reclaimed.

Slow execution due to locking of finalize

Public class GCTest {static GCTest test; public void isAlive () {System.out.println ("I'm still alive");} @ Override protected void finalize () throws Throwable {System.out.println ("I'm dying"); test=this;} public static void main (String [] args) throws InterruptedException {test= new GCTest (); test=null; System.gc (); Thread.sleep If (testworthy null) {test.isAlive ();} else {System.out.println (dead);} test=null; System.gc (); if (testworthy null) {test.isAlive ();} else {System.out.println (dead) Thank you for your reading. The above is the content of "how to understand Java jvm garbage collection". After the study of this article, I believe you have a deeper understanding of how to understand Java jvm garbage collection, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report