关于java内存不足异常的处理.

有时java程序在内存达到一定程序时.程序将抛出内存不足的问题.

如果有socket连接.socket连接也会断开.但程序却不会退出.现在要处理这异常.

处理方法如下:

1.写一个异常处理类

public class NoMemoryDeal implements UncaughtExceptionHandler { public NoMemoryDeal() { super(); } public void uncaughtException(Thread t, Throwable e) { e.printStackTrace(); e.getLocalizedMessage(); if(e instanceof java.lang.OutOfMemoryError) { KLinkLog.writeLog(KLinkLog.ERROR, "OutOfMemoryError, app exit!"); //退出程序 System.exit(0); } else { KLinkLog.writeLog(KLinkLog.ERROR,"PID:"+t.getId()+" msg:"+ e.getMessage()); } } }

2.在程序入口处设置

Thread.setDefaultUncaughtExceptionHandler(new NoMemoryDeal());

如果只想在本线程设置则

Thread.currentThread().setUncaughtExceptionHandler(new NoMemoryDeal());

 

这样.如果程序发生了内存不足时.可以自己进行处理.比如写日志等等...

你可能感兴趣的:(关于java内存不足异常的处理.)