利用 Runtime 监控 Java 系统资源(二)

2014-11-24 10:18:49 · 作者: · 浏览: 4
ge = garbage.substring(garbage.length());
pretendedMemory.add(builder.toString());
}
int deleteCount = new Random().nextInt(15000);
for (int i = -1; ++i != deleteCount; )
pretendedMemory.removeFirst();

System.out.println("-----------");
}
}
}
).start();
}

private Runtime context;
private double maxFreeMemory;

private long lastFreeMemory;
private long lastTotalMemory;
private long lastMaxMemory;

private double lastMemoryRate;

public PerformanceMonitor(Runtime context)
{
this.context = context;
}

public void checkAll()
{
this.monitorMemory();
this.monitorCpu();
}
/**
* 本方法比较当前空余内存与历史记录最大空余内存的关系。若空余内存过小,则执行垃圾回收。
*/
public void monitorMemory()
{
// 求空余内存,并计算空余内存比起最大空余内存的比例
long freeMemory = this.context.freeMemory();
if (freeMemory > this.maxFreeMemory)
this.maxFreeMemory = Long.valueOf(freeMemory).doubleva lue();
double memoryRate = freeMemory / this.maxFreeMemory;
System.out.println("There are " + memoryRate * 100 + "% free memory.");

// 如果内存空余率在变小,则一切正常;否则需要报告内存变化情况
if (memoryRate >= this.lastMemoryRate) this.reportMemoryChange();

// 如果内存空余率很低,则执行内存回收
if (freeMemory / this.maxFreeMemory < 0.3)
{
System.out.print("System will start memory Garbage Collection.");
System.out.println(" Now we have " + freeMemory / 1000 + " KB free memory.");
this.context.gc();
System.out.println("After the Garbage Collection, we have "
+ this.context.freeMemory() / 1000 + " KB free memory.");
}

// 记录内存信息
this.recordMemoryInfo(memoryRate);
}

/**
* 报告内存变化情况
*/
private void reportMemoryChange()
{
System.out.print("Last freeMemory = " + this.lastFreeMemory / 1000 + " KB,");
System.out.println(" now it is " + this.context.freeMemory() / 1000 + " KB.");
System.out.print("Last totalMemory = " + this.lastTotalMemory / 1000 + " KB,");
System.out.println(" now it is " + this.context.totalMemory() / 1000 + " KB.");
System.out.print("Last maxMemory = " + this.lastMaxMemory / 1000 + " KB,");
System.out.println(" now it is " + this.context.maxMemory() / 1000 + " KB.");
}

/**
* 记录本次内存信息。
*/
private void recordMemoryInfo(double memoryRate)
{
this.lastFreeMemory = this.context.freeMemory();
this.lastMaxMemory = this.context.maxMemory();
this.lastTotalMemory = this.context.totalMemory();
this.lastMemoryRate = memoryRate;
}

/**
* 监测 CPU 的方法。
*/
public void monitorCpu()
{
int cpuCount = this.context.availableProcessors();
if (cpuCount > 1) System.out.println("CPU have " + cpuCount + " processors.");
}
}
我运行这段程序,得到结果报告。通过观察结果报告,我得到了一些新结论。
首先, maxMemory 在一台机器只运行一个爪哇(Java)虚拟机的前提下,一般来说并不会变动。
其次,新生代内存会很快地自动回收,这体现在 freeMemory 总是不断少量自动增加上。
最后,爪哇(Java)虚拟机会在内存不足时,自己申请新的内存。这个内存空间也能够根据报告大概看