java内存控制

本文通过Java代码示例展示了如何监控应用程序的内存使用情况。通过创建不同大小的字节数组并填充数据,演示了在分配大量内存时如何检查当前可用内存及阈值,从而预防内存溢出错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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); } } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值