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

What are the GC algorithm and four citations?

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the relevant knowledge of "what are the GC algorithms and four citations?" in the operation of actual cases, many people will encounter such a dilemma, and then let the editor lead you to learn how to deal with these situations! I hope you can read it carefully and be able to achieve something!

GC algorithm

Common GC algorithms include:

Citation counting method

Label elimination method

Replication algorithm

Label compression method

Generation algorithm

Partition algorithm

Citation counting method

The principle of implementation:

For an object A

Add 1 to the reference counter of any object that refers to AMague A.

When the reference expires, the reference counter is subtracted by 1

As long as object A's reference counter has a value of 0, object A will no longer be used, waiting to be recycled.

Disadvantages:

Unable to handle circular references, such as A reference Bline B reference A, but there are no other object references, so neither A nor B has a reference count of 0, so it cannot be recycled.

The reference counter requires that each reference is generated and eliminated, accompanied by an addition operation and a subtraction operation, which will have a certain impact on system performance.

Due to the above shortcomings of the citation counting method, Java is not used as a GC algorithm.

Label elimination method

Label cleanup divides garbage collection into two phases:

Marking phase: all accessible objects starting from the root node are marked through the root node, and what is not marked is the junk object.

Cleanup phase: clears all untagged objects

Marking phase:

After clearing:

The obvious disadvantage is that the recycled space is discontinuous and the work efficiency is lower than the continuous memory space.

Replication algorithm

Core ideas:

The memory space is divided into two equal blocks

Use only one piece at a time

Move the surviving objects to another block when reclaiming, and then clear all objects in the memory block that is in use

The role of swapping two memory blocks

The advantage is that the recovered memory space is not fragmented, while the disadvantage is that if there are a large number of objects, it takes a lot of time to copy, and the memory is only half of the original memory.

For example, in the following figure, An and B have the same memory space. During garbage collection, A copies the surviving objects to B, and B keeps continuous after replication:

When the copy is complete, An is emptied and B is set to the currently used space.

In Java's new generation serial garbage collector, the replication algorithm is used, and the new generation is divided into eden area, from area and to area. Where from and to are two spaces with the same memory, also known as survivor, that is, survivor space. During garbage collection, the surviving objects in the eden area and the from area are copied to the to area, and then the from area and the eden area are emptied, and then the roles of the from and to areas will be exchanged, that is, the next garbage collection will be copied from the original to area (the new from area) to the original from area (the new to area).

Label compression method

Tag compression is an old algorithm, which makes some optimizations on the basis of tag cleanup. Like tag cleanup, all reachable objects need to be marked once, starting from the root node. Then compress all living objects to one end of memory, and then clean up all the space outside the boundary, as shown below:

The advantage of the tag compression method is that it can avoid fragmentation and does not need two identical pieces of memory space.

Generation algorithm

Generation algorithm is not a specific garbage collection algorithm. Generation algorithm is actually an algorithm that uses different collection algorithms to improve efficiency according to the characteristics of each memory space. For example:

In the new generation: a large number of new objects will be recycled quickly, so the new generation is more suitable to use replication algorithm.

In the old days: the use of label compression or label removal

Partition algorithm

The partition algorithm divides the entire heap space into continuous different cells, each of which is used independently and recycled independently, as shown in the figure:

3 four kinds of citations

Four levels of references are provided in Java:

Strong citation

Soft reference

Weak reference

Virtual reference

Let's take a look at it separately.

Strong citation

Strong references are commonly used reference types in code. Strongly referenced objects are reachable and will not be recycled, such as:

StringBuffer str = new StringBuffer ("a")

If the above code runs in the method body, then the local variable str will be assigned on the stack, and the object StringBuffer instance will be assigned on the heap. Str points to the heap space where the StringBuffer instance resides, which can be manipulated through str, and str is a strong reference to the StringBuffer instance.

For example, the following code was executed:

StringBuffer str1 = str

Then str1 also points to the object that str points to, that is, they all point to the same StringBuffer instance, and the value of str1==str is true because both point to the same heap space address.

The characteristics of strong quotation are as follows:

You can access the target object directly

Objects pointed to by strong references will not be recycled by the system, and JVM would rather throw OOM than recycle objects pointed to by strong references.

Strong references can cause memory leaks

Soft reference

A soft reference is a reference type that is weaker than a strong reference. If an object only holds a soft reference, it will be recycled when the heap space is insufficient. The soft reference can be implemented using the SoftReference class, such as the following code:

Public static void main (String [] args) {Byte [] b = new Byte [1024 / 1024 / 8]; SoftReference softReference = new SoftReference (b); b = null; System.out.println (softReference.get ()); System.gc (); System.out.println ("After GC"); System.out.println (softReference.get ()); b = new Byte [1024 / 1024 / 8]; System.gc () System.out.println (softReference.get ());}

On OpenJDK 11.0.10, add the output of-Xmx40m as follows:

[Ljava.lang.Byte;@1fbc7afbAfter GC [Ljava.lang.Byte;@1fbc7afbnull

As you can see, when garbage collection, soft reference objects may not be recycled, but when memory is tight, soft reference objects will be recycled.

Weak reference

Weak references are weaker reference types than soft references. During garbage collection, objects will be reclaimed whenever weak references are found, regardless of system space usage. However, because the threads of the garbage collector usually have a low priority, weak reference objects may not be found quickly, in which case weak reference objects can exist for a long time. Examples of weak references are as follows:

Public static void main (String [] args) {Byte [] b = new Byte [1024 / 1024 / 8]; WeakReference softReference = new WeakReference (b); b = null; System.out.println (softReference.get ()); System.gc (); System.out.println ("After GC"); System.out.println (softReference.get ());}

Output (- Xmx40m):

[Ljava.lang.Byte;@1fbc7afbAfter GCnull

You can see that weakly referenced objects are recycled immediately after GC.

A common use scenario for soft references and weak references is to save optional cached data. When the system is out of memory, the memory data will be reclaimed, which will not lead to OOM, and when the memory is sufficient, the cached data can exist for a long time, thus speeding up the system.

Virtual reference

A virtual reference is the weakest of all reference types. An object with a virtual reference is almost the same as no reference and can be reclaimed by the garbage collector at any time. In addition, attempts to obtain strong references using the get () method of virtual references always fail, and virtual references need to be used with reference queues to track the garbage collection process.

Public static void main (String [] args) throws Exception {ReferenceQueue queue = new ReferenceQueue (); PhantomReference reference = new PhantomReference (new String ("test"), queue); System.out.println (reference.get ());}

Output result:

This is the end of null's "what are the GC algorithms and four citations?" Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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