Java内存行为:与Thread.sleep不同 [英] Java Memory Behavior : Different with Thread.sleep

查看:146
本文介绍了Java内存行为:与Thread.sleep不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用visualvm进行一些内存分析. 我编写了一个基本代码,该代码运行无限循环以将对象添加到List.

I am trying to do some memory analysis using visualvm. I have written a basic code that runs an infinite loop to add objects to List.

package home.always.learning.java;  

import java.util.ArrayList;  
import java.util.List;  

public class Heaper {  

    private static List<PersonDetails> listObj = new ArrayList<PersonDetails>();  

    private static final String nameConst = "Tarun Trehan";  

    public static void main(String[] args)throws Exception{  
        personListCreation();  
    }  

    public static void personListCreation() throws Exception  
    {  
        int i = 0;  
        while(true)  
        {  
            System.out.println("Looping to create person list...");  
            i++;  
            listObj.add(new PersonDetails(nameConst+i));  
            //Thread.sleep(1000L);  
        }  
    }  
}  

正如预期的那样,内存会猛增,并在附加的visualvm第一快照中可见,即 Memory_Shoots.JPG .

As expected, memory shoots up and is visible in visualvm 1st snapshot attached i.e. Memory_Shoots.JPG.

但是,如果我从代码中删除以下注释并让程序休眠1秒钟;结果是不同的:

However, if i remove the following comment from the code and allow the program to sleep for 1 second; the result is different:

Thread.sleep(1000L);

内存增加,然后稳定下来,然后继续.请参考所附的第二张快照,即 Memory_Stabilizes.JPG

The memory increases but then stabilizes and it goes on. Please refer 2nd snapshot attached i.e. Memory_Stabilizes.JPG

我无法理解这种行为? 您能提供您的意见吗?

I am unable to understand this behavior? Can you please provide your inputs.

推荐答案

查看代码的略微修改的版本(固定的迭代次数,启动后添加5秒的暂停时间以允许我的IDE连接到visualvm,并删除了系统.out.print来提高速度,等等),看来您的罪魁祸首是垃圾收集:

Looking at a slightly modified version of the code (fixed number of iterations, added a 5s pause after start to allow my IDE to connect to visualvm, removed the system.out.print for speed, etc) it seems your culprit is garbage collection:

睡眠100L:(跑5:18)

With 100L sleep: (ran for 5:18)

睡眠10秒钟 :(运行5:01)

With 10L sleep: (ran for 5:01)

具有2升睡眠:(跑4:57)

With 2L sleep: (ran for 4:57)

睡眠1L:(跑6:36)

With 1L sleep: (ran for 6:36)

睡眠时间为0时 :(跑0:23)

With 0L sleep: (ran for 0:23)

因此,基本上我们发现,已用堆将缓慢上升,直到Eden空间被填充(导致分配失败),然后将eden的旧成员(几乎所有成员,查看空间使用情况)移至幸存者0 /1,其中一些到了老一代.睡眠与不睡眠之间的差异很可能是次要收藏和主要收藏的相对频率之间的差异.

So basically what we find is that the used heap will rise slowly until the Eden space is filled (causing an allocation failure), moving the older members of eden (almost all of them, looking at the space usage) to survivor 0/1, and some of those to the old gen. The difference between sleep and no sleep may very well be a difference between the relative frequencies of minor collections and major collections.

这篇关于Java内存行为:与Thread.sleep不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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