本文介绍了为什么强制垃圾收集会增加分配给java进程的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这段代码:

  public static void main(String [] args)抛出异常{
了Thread.sleep(5000);
System.out.println(Creating array ...);
Integer [] integers = new Integer [Integer.MAX_VALUE / 32];
Thread.sleep(5000);
System.out.println(销毁阵列);
整数= null;
//System.gc();
//System.runFinalization();
Thread.sleep(60000);
}

当我运行此代码后,我在大约5秒后会看到268 MB的ram被分配给Activity Monitor中的java进程。



当我在控制台中看到销毁阵列后,取消注释注释行(System.gc和以下行)时,分配的内存增加到278 MB。



我可以理解内存没有被释放,因为System.gc()只是对JVM的一个暗示,但为什么10MB会增加?此时加载到内存中的是什么?

解决方案

分配的内存并不一定意味着对象占用的内存。它可以是空堆空间。



Java GC正在复制/压缩收集器,为了复制工作,他们需要一些TO空间作为非垃圾的复制目的地。 / p>

通过强制垃圾收集,你干扰了GC的启发式,例如具有暂停时间目标或吞吐量目标。为了弥补它,可能决定给自己更多的喘息空间 - 在配置的最大堆大小的范围内 - 仍然达到这些目标。



我不知道它是否适用于所有GC算法,但使用 -XX:+ PrintAdaptiveSizePolicy 进行记录可能会提供一些见解。


So I have this code:

public static void main(String[] args) throws Exception {
    Thread.sleep(5000);
    System.out.println("Creating array...");
    Integer[] integers = new Integer[Integer.MAX_VALUE/32];
    Thread.sleep(5000);
    System.out.println("Destroying array");
    integers = null;
    //System.gc ();
    //System.runFinalization ();
    Thread.sleep(60000);
}

When I run this code I after about 5 seconds I will see 268 MB of ram is allocated to java process in Activity Monitor.

When I uncomment the commented lines (System.gc and the following line) after I see "Destroying array" in console, the memory allocated increases to 278 MB.

I can understand that the memory is not freed up because System.gc() is only a hint to the JVM, but why the 10MB increase? What has been loaded at this point to the memory?

解决方案

Allocated memory does not necessarily mean memory occupied by objects. It can be empty heap space.

Java GCs are copying/compacting collectors, for copying to work they need some TO-space as copy destination for the non-garbage.

And by forcing a garbage collection you are interfering with the GC's heuristics, e.g. with its pause time goals or its throughput goals. To compensate it may decide to give itself more breathing room - within the bounds of the configured maximum heap size - to still meet those goals.

I don't know if it applies to all GC algorithms, but logging with -XX:+PrintAdaptiveSizePolicy might provide some insight.

这篇关于为什么强制垃圾收集会增加分配给java进程的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 06:28