为什么短期和长期的对象在垃圾收集方面有所不同? [英] Why make short and long-lived objects a difference in garbage collection?

查看:112
本文介绍了为什么短期和长期的对象在垃圾收集方面有所不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常读到Sun JVM中的短期对象(相对较新的对象)可以比长寿命对象(相对较旧的对象)更有效地进行垃圾收集。


  • 为什么会这样?

  • 是Sun JVM特有的还是一般垃圾收集原理的结果? li>

解决方案

大多数Java应用程序都创建Java对象,你在一个方法中创建一些对象,然后一旦你退出该方法,所有的对象都会死掉。大多数应用都以这种方式行事,大多数人倾向于用这种方式编写他们的应用。 Java堆大致分为三部分,永久的,旧的(长寿的)一代和年轻的(短命的)一代。年轻的gen被进一步分解为S1,S2和伊甸园。这些只是堆。



大多数对象都是在年轻的gen中创建的。这里的想法是,由于物体的死亡率很高,我们很快创建它们,使用它们然后丢弃它们。速度是至关重要的。在创建对象时,年轻的gen会填满,直到发生小的GC。在一个小型GC中,所有活着的对象都从伊甸园复制过来,然后说S2到S1。然后,'指针'停留在伊甸园和S2。

每个副本都会使对象老化。默认情况下,如果一个对象存活32个副本, 32个小型GC,那么GC认为它将会持续很长时间。所以,它所做的就是把它转移到老一代。老根只是一个大空间。当旧的gen填满时,一个完整的GC或主要的GC发生在旧的gen中。由于没有其他空间可以复制,GC必须紧凑。这比慢速GC要慢很多,这就是为什么我们避免频繁这样做的原因。



您可以使用
$ b来调整持久性参数$ b

  java -XX:MaxTenuringThreshold = 16 

如果你知道你有很多长寿命的物体。您可以使用

  java -XX打印各种年龄段的应用程序:-PrintTenuringDistribution 


I've often read that in the Sun JVM short-lived objects ("relatively new objects") can be garbage collected more efficiently than long-lived objects ("relatively old objects")

  • Why is that so?
  • Is that specific to the Sun JVM or does this result from a general garbage collection principle?

解决方案

Most Java apps create Java objects and then discard them rather quickly eg. you create some objects in a method then once you exit the method all the object dies. Most apps behave this way and most people tend to code their apps this way. The Java heap is roughly broken up into 3 parts, permanent, old (long lived) generation, and young (short lived) generation. Young gen is further broken up into S1, S2 and eden. These are just heaps.

Most objects are created in the young gen. The idea here is that, since the mortality rate of objects is high, we quickly create them, use them and then discard them. Speed is of essence. As you create objects, the young gen fills up, until a minor GC occurs. In a minor GC, all objects that are alive are copied over from eden and say S2 to S1. Then, the 'pointer' is rested on eden and S2.

Every copy ages the object. By default, if an object survives 32 copies viz. 32 minor GC, then the GC figures that it is going to be around for a lot longer. So, what it does is to tenure it, by moving it to the old generation. Old gen is just one big space. When the old gen fills up, a full GC, or major GC, happens in the old gen. Because there is no other space to copy to, the GC has to compact. This is a lot slower than minor GC, that's why we avoid doing that more frequently.

You can tune the tenuring parameter with

java -XX:MaxTenuringThreshold=16 

if you know that you have lots of long lived objects. You can print the various age bucket of your app with

java -XX:-PrintTenuringDistribution

这篇关于为什么短期和长期的对象在垃圾收集方面有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆