public class MemoryManager { //10-50 private static int _gcLowWaterThreshold = 10; public static void main(String[] args) { show(); byte [] b = new byte[1024*1024*10]; show(); Arrays.fill(b, (byte)4); show(); byte [] c = new byte[1024*1024*10]; show(); Arrays.fill(c, (byte)4); show(); ArrayList<byte []> list = new ArrayList<byte[]>(); try { for (int i = 0; i < 100; i++) { byte [] d = new byte[1024*1024*10]; show(); Arrays.fill(d, (byte)4); show(); list.add(d); } }catch(Error e) { } list.clear(); show(); byte [] e = new byte[1024*1024*10]; show(); Arrays.fill(e, (byte)4); show(); byte [] f = new byte[1024*1024*10]; show(); Arrays.fill(f, (byte)4); show(); } private static void show() { long threshold = ((Runtime.getRuntime().totalMemory() / 100) * _gcLowWaterThreshold); long free = Runtime.getRuntime().freeMemory(); if(threshold > free) { System.out.println("警告:内存不足 threshold:"+threshold+" free:"+free); } else { System.out.println(" threshold:"+threshold+" free:"+free); } } }
java内存控制
最新推荐文章于 2022-03-01 20:02:53 发布
本文通过Java代码示例展示了如何监控应用程序的内存使用情况。通过创建不同大小的字节数组并填充数据,演示了在分配大量内存时如何检查当前可用内存及阈值,从而预防内存溢出错误。
2581

被折叠的 条评论
为什么被折叠?



