java中的垃圾收集器_Java中的垃圾收集

java中的垃圾收集器

Garbage collection in java is one of the advance topic. Java GC knowledge helps us in fine tuning our application runtime performance.

Java中的垃圾回收是高级主题之一。 Java GC知识有助于我们微调应用程序的运行时性能。

Java中的垃圾收集 (Garbage Collection in Java)

  • In Java, the programmers don’t need to take care of destroying the objects that are out of use. The Garbage Collector takes care of it.

    在Java中,程序员不需要照顾破坏不使用的对象。 垃圾收集器会处理它。
  • Garbage Collector is a Daemon thread that keeps running in the background. Basically, it frees up the heap memory by destroying the unreachable objects.

    垃圾收集器是一个后台驻留程序的守护进程线程 。 基本上,它通过销毁无法访问的对象来释放堆内存
  • Unreachable objects are the ones that are no longer referenced by any part of the program.

    无法访问的对象是程序的任何部分不再引用的对象。
  • We can choose the garbage collector for our java program through JVM options, we will look into these in later section of this tutorial.

    我们可以通过JVM选项为我们的Java程序选择垃圾收集器,我们将在本教程的后面部分中对此进行研究。

自动垃圾收集如何工作? (How Automatic Garbage Collection works?)

Automatic Garbage collection is a process of looking at the Heap memory, identifying(also known as “marking”) the unreachable objects, and destroying them with compaction.

自动垃圾收集是查看堆内存,识别(也称为“标记”)不可达对象并通过压缩将其破坏的过程。

An issue with this approach is that, as the number of objects increases, the Garbage Collection time keeps on increasing, as it needs to go through the entire list of objects, looking for the unreachable object.

这种方法的问题在于,随着对象数量的增加,垃圾收集时间会不断增加,因为它需要遍历对象的整个列表,以寻找不可达的对象。

However, the empirical analysis of applications shows that most of the objects are short-lived.

但是,对应用程序的经验分析表明,大多数对象都是短暂的。

This behavior was used to improve the performance of JVM, and the adopted methodology is commonly called Generational Garbage Collection. In this method, the Heap space is divided into generations like Young Generation, Old or Tenured Generation, and Permanent Generation.

此行为用于提高JVM的性能,并且采用的方法通常称为Generational Garbage Collection。 在这种方法中,堆空间被分为几代,如年轻一代,老一代或终身一代以及永久一代。

The Young generation heap space is the new where all the new Objects are created. Once it gets filled up, minor garbage collection (also known as, Minor GC) takes place. Which means, all the dead objects from this generation are destroyed This process is quick because as we can see from the graph, most of them would be dead. The surviving objects in young generation are aged and eventually moves to the older generations.

Young一代堆空间是创建所有新对象的新空间。 一旦被填满,就会进行次要垃圾收集(也称为Minor GC)。 这意味着,这一代中的所有死亡对象都被销毁了。此过程之所以Swift,是因为从图中可以看出,大多数对象都是死亡的。 年轻一代中幸存的物体已经老化,并最终移交给了老一代。

The Old Generation is used to store long surviving objects. Typically, a threshold is set for young generation object and when that age is met, the object gets moved to the old generation. Eventually, the old generation needs to be collected. This event is called a Major GC (major garbage collection). Often it is much slower because it involves all live objects.
Also, there is Full GC, which means cleaning the entire Heap – both Young and older generation spaces.

老一代用于存储尚存的物体。 通常,为年轻一代对象设置一个阈值,并且当达到该年龄时,该对象将移至老一代。 最终,需要收集旧的一代。 此事件称为主要GC(主要垃圾回收)。 通常,它要慢得多,因为它涉及所有活动对象。
此外,还有完整的GC,这意味着可以清洁整个堆堆-年轻一代和老一代空间。

Lastly, up to Java 7, there was a Permanent Generation (or Perm Gen), which contained metadata required by the JVM to describe the classes and methods used in the application. It was removed in Java 8.

最后,直到Java 7,都有一个永久代(或Perm Gen),其中包含JVM所需的元数据,用于描述应用程序中使用的类和方法。 在Java 8中已将其删除。

Java垃圾收集器 (Java Garbage Collectors)

The JVM actually provides four different garbage collectors, all of them generational. Each one has their own advantages and disadvantages. The choice of which garbage collector to use lies with us and there can be dramatic differences in the throughput and application pauses.

JVM实际上提供了四个不同的垃圾收集器,它们都是世代相传的。 每个人都有自己的优点和缺点。 使用哪种垃圾收集器的选择由我们决定,吞吐量和应用程序暂停可能会有很大差异。

All these, split the managed heap into different segments, using the age-old assumptions that most objects in the heap are short-lived and should be recycled quickly.

所有这些都使用古老的假设将托管堆分成不同的段,这些假设是堆中的大多数对象都是短暂的,应该Swift回收。

So, the four types of garbage collectors are:

因此,四种类型的垃圾收集器是:

串行GC (Serial GC)

This is the simplest garbage collector, designed for single threaded systems and small heap size. It freezes all applications while working. Can be turned on using -XX:+UseSerialGC JVM option.

这是最简单的垃圾收集器,设计用于单线程系统和较小的堆大小。 它会在工作时冻结所有应用程序。 可以使用-XX:+UseSerialGC JVM选项打开。

平行/通量GC (Parallel/Throughput GC)

This is JVM’s default collector in JDK 8. As the name suggests, it uses multiple threads to scan through the heap space and perform compaction. A drawback of this collector is that it pauses the application threads while performing minor or full GC.
It is best suited if applications that can handle such pauses, and try to optimize CPU overhead caused by the collector.

这是JVM在JDK 8中的默认收集器。顾名思义,它使用多个线程来扫描堆空间并执行压缩。 该收集器的一个缺点是在执行次要或完全GC时会暂停应用程序线程。
如果应用程序可以处理此类暂停,并尝试优化由收集器引起的CPU开销,则是最适合的。

CMS收集器 (The CMS collector)

The CMS collector (“concurrent-mark-sweep”) algorithm uses multiple threads (“concurrent”) to scan through the heap (“mark”) for unused objects that can be recycled (“sweep”).

CMS收集器(“ concurrent-mark-sweep”)算法使用多个线程(“ concurrent”)在堆(“ mark”)中扫描可回收(“ sweep”)未使用的对象。

This collector goes in Stop-The-World(STW) mode in two cases:
-While initializing the initial marking of roots, ie. objects in the old generation that are reachable from thread entry points or static variables
-When the application has changed the state of the heap while the algorithm was running concurrently and forcing it to go back and do some final touches to make sure it has the right objects marked.

在两种情况下,此收集器进入“世界停止”(STW)模式:
-在初始化根的初始标记时,即 线程入口点或静态变量可访问的旧对象
-当应用程序在算法同时运行时更改了堆的状态,并迫使其返回并进行最后的修改时,请确保已标记了正确的对象。

This collector may face promotion failures. If some objects from young generation are to be moved to the old generation, and the collector did not have enough time to make space in the old generation space, a promotion failure will occur.
In order to prevent this, we may provide more of the heap size to the old generation or provide more background threads to the collector.

该收集器可能会面临升级失败。 如果要将年轻一代的某些对象移到老一代,并且收集器没有足够的时间在老一代空间中腾出空间,则会发生升级失败。
为了防止这种情况,我们可能会为旧一代提供更多的堆大小,或者为收集器提供更多的后台线程。

G1收集器 (G1 collector)

Last but not the least is the Garbage-First collector, designed for heap sizes greater than 4GB. It divides the heap size into regions spanning from 1MB to 32Mb, based on the heap size.

最后但并非最不重要的是Garbage-First收集器,其设计用于大于4GB的堆大小。 它将根据堆大小将堆大小分为1MB到32Mb的区域。

There is a concurrent global marking phase to determine the liveliness of objects throughout the heap. After the marking phase is complete, G1 knows which regions are mostly empty. It collects unreachable objects from these regions first, which usually yields a large amount of free space. So G1 collects these regions(containing garbage) first, and hence the name Garbage-First. G1 also uses a pause prediction model in order to meet a user-defined pause time target. It selects the number of regions to collect based on the specified pause time target.

有一个并发的全局标记阶段来确定整个堆中对象的活动性。 标记阶段完成后,G1知道哪些区域大部分为空。 它首先从这些区域收集无法到达的对象,这通常会产生大量的可用空间。 因此,G1首先收集这些区域(包含垃圾),因此名称为Garbage-First。 为了满足用户定义的暂停时间目标,G1还使用了暂停预测模型。 它根据指定的暂停时间目标选择要收集的区域数。

The G1 garbage collection cycle includes the phases as shown in the figure:

G1垃圾回收周期包括以下各阶段:

  1. Young-only phase: This phase includes only the young generation objects and promotes them to the old generation. The transition between the young-only phase and the space-reclamation phase starts when the old generation is occupied up to a certain threshold, ie. the Initiating Heap Occupancy threshold. At this time, G1 schedules an Initial Mark young-only collection instead of a regular young-only collection.

    仅限年轻阶段:此阶段仅包含年轻一代对象,并将其提升为老一代。 当老一代被占用到某个阈值时,即仅年轻阶段和空间回收阶段之间的过渡开始。 启动堆占用率阈值。 这时,G1安排了一个Initial Mark仅限年轻人的收藏,而不是常规的仅限年轻人的收藏。
    1. Initial Marking: This type of collection starts the marking process in addition to a regular young-only collection. Concurrent marking determines all currently live objects in the old generation regions to be kept for the following space-reclamation phase. While marking hasn’t completely finished, regular young-only collections may occur. Marking finishes with two special stop-the-world pauses: Remark and Cleanup.

      初始标记:除了常规的仅年轻标记的集合之外,这种类型的集合还开始标记过程。 并发标记确定了在下一个空间回收阶段中要保留的旧一代区域中的所有当前活动对象。 虽然标记还没有完全完成,但是可能会定期出现仅年轻的收藏。 标记结束时有两个特殊的停顿世界:“注释”和“清理”。
    2. Remark: This pause finalizes the marking itself, and performs global reference processing and class unloading. Between Remark and Cleanup G1 calculates a summary of the liveness information concurrently, which will be finalized and used in the Cleanup pause to update internal data structures.

      备注:此暂停将最终完成标记本身,并执行全局引用处理和类卸载。 在“备注”和“清除”之间,G1同时计算活动信息的摘要,该摘要将最终确定并在“清除暂停”中用于更新内部数据结构。
    3. Cleanup: This pause also takes the completely empty regions, and determines whether a space-reclamation phase will actually follow. If a space-reclamation phase follows, the young-only phase completes with a single young-only collection.

      清理:此暂停还将占用完全空白的区域,并确定是否将实际进行空间回收阶段。 如果进行空间回收阶段,则仅年轻阶段将以单个仅年轻集合完成。
  2. Space-reclamation phase: This phase consists of multiple mixed collections — in addition to young generation regions, also evacuates live objects of old generation regions. The space-reclamation phase ends when G1 determines that evacuating more old generation regions wouldn’t yield enough free space worth the effort.

    填海阶段:该阶段包括多个混合馆藏 -除了年轻一代地区,还撤离了旧一代地区的有生命物体。 当G1确定撤离更多的旧发电区不会产生值得努力的足够的自由空间时,太空回收阶段结束。

G1 can be enabled using the –XX:+UseG1GC flag.

可以使用–XX:+UseG1GC标志启用G1。

This strategy reduced the chances of the heap being depleted before the background threads have finished scanning for unreachable objects. Also, it compacts the heap on-the-go, which the CMS collector can do only in STW mode.

此策略减少了在后台线程完成对不可达对象的扫描之前耗尽堆的机会。 此外,它还可以在移动时压缩堆,CMS收集器只能在STW模式下执行此操作。

In Java 8 a beautiful optimization is provided with G1 collector, called string deduplication. As we know the character arrays that represent our strings occupies much of our heap space. A new optimization has been made that enables the G1 collector to identify strings which are duplicated more than once across our heap and modify them to point to the same internal char[] array, to avoid multiple copies of the same string residing in the heap unnecessarily. We can use the -XX:+UseStringDeduplication JVM argument to enable this optimization.

在Java 8中,G1收集器提供了一个漂亮的优化,称为字符串重复数据删除 。 众所周知,代表字符串的字符数组占用了我们很多的堆空间。 进行了新的优化,使G1收集器可以识别在我们的堆中重复多次的字符串,并对其进行修改以指向同一内部char []数组,以避免不必要地将同一字符串的多个副本驻留在堆中。 我们可以使用-XX:+UseStringDeduplication JVM参数来启用此优化。

G1 is the default garbage collector in JDK 9.

G1是JDK 9中的默认垃圾收集器。

Java 8 PermGen和元空间 (Java 8 PermGen and Metaspace)

As mentioned earlier, the Permanent Generation space was removed since Java 8. So now, the JDK 8 HotSpot JVM uses the native memory for the representation of class metadata which is called Metaspace.

如前所述,自Java 8开始就删除了永久生成空间。因此,现在,JDK 8 HotSpot JVM使用本机内存来表示类元数据,即元空间。

Most of the allocations for the class metadata are made out of the native memory. Also, there is a new flag MaxMetaspaceSize, to limit the amount of memory used for class metadata. If we do not specify the value for this, the Metaspace re-sizes at runtime as per the demand of the running application.

类元数据的大多数分配都是在本机内存中进行的。 另外,还有一个新的标志MaxMetaspaceSize,以限制用于类元数据的内存量。 如果我们没有为此指定值,则Metaspace将在运行时根据正在运行的应用程序的需求重新调整大小。

Metaspace garbage collection is triggered when the class metadata usage reaches MaxMetaspaceSize limit. Excessive Metaspace garbage collection may be a symptom of classes, classloaders memory leak or inadequate sizing for our application.

当类元数据使用量达到MaxMetaspaceSize限制时,将触发元空间垃圾回收。 过多的Metaspace垃圾回收可能是类的症状,类加载器内存泄漏或应用程序大小不足。

That’s it for the Garbage Collection in java. I hope you got the understanding about different garbage collectors we have in java.

Java垃圾收集就这样了。 希望您对Java中的不同垃圾收集器有所了解。

References: Oracle Documentation, G1 GC.

参考: Oracle文档G1 GC

翻译自: https://www.journaldev.com/16659/garbage-collection-in-java

java中的垃圾收集器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值