开发者

How many objects are garbage collected?

开发者 https://www.devze.com 2023-01-11 08:14 出处:网络
In the below example program how many object will be garbage collected before executing line Thread.sleep(1000)?

In the below example program how many object will be garbage collected before executing line Thread.sleep(1000)?

public class GCExample {

public static void main(String[] args) throws InterruptedException {
    GCExample gc = new GCExample();
    gc.doSomeThing();
    Thread.sleep(1000);
}
public void doSomeThing(){
    Object[] obj = new Object[2];
    for(int i=0;i<obj.length;i++){
        obj[i开发者_StackOverflow中文版] = new Object();
    }
}

}


Given the non-deterministic nature of GC, I'd say about the same number as fit the length of a piece of string.


Before Thread.sleep, there is no way to know how many items will be garbage collected. It might be zero, or it might be your entire object array, which would mean that you'd collect three objects (from this code, though there may be others from other code in your application).

However, it would be zero or three, since when obj is unrooted, both of it's elements (the 2 new Object instances) will be unrooted as well, so they'll all get collected in the same pass.

Most likely, however, you won't see any collection in there, and won't have any objects get collected.


The only way to know for sure is to measure it. You can use a java.lang.ref.Reference.

My best guess is that there won't be any garbage collection, but this might vary from JVM to JVM.

0

精彩评论

暂无评论...
验证码 换一张
取 消