我想知道为什么创建大表后总的可用内存没有变化.但是当我使用垃圾收集器时,总的可用内存增加了.
import java.util.Random;
public class Main{
public static void main(String[] args) throws Exception
{
C c = new C();
System.out.println("Free memory: "+Runtime.getRuntime().freeMemory());
c.CreateTable();
System.out.println("Free memory: "+Runtime.getRuntime().freeMemory());
System.gc();
System.out.println("Free memory: "+Runtime.getRuntime().freeMemory());
}
}
class C{
public void createTable()
{
int[] ar = new int[70000];
Random r = new Random();
for(int i = 0; i
{
ar[i]=r.nextInt(99);
}
}
}
解决方法:
这是因为JVM在TLAB(线程本地分配缓冲区)中创建了int [] ar.让我用以下示例进行说明:
1)假设系统中的总内存为100个单位.
2)即使运行了一行代码,当前线程也已经创建了一个TLAB beofre.
3)TLAB的内存(例如10个单位)已经从总内存中扣除(即Runtime.freeMemory显示90个单位)
4)int [] ar在TLAB内部创建,因为TLAB具有可用空间.
5)创建int [] ar后,运行Runtime.freeMemory显示90个单位(因为它是在TLAB中创建的).
6)现在执行GC,您将再次看到100个单位
标签:memory,java,garbage-collection
来源: https://codeday.me/bug/20191119/2032586.html