蛋神2:关于java内存不足异常的处理.

来源:百度文库 编辑:九乡新闻网 时间:2024/04/28 05:07:09

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

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

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

处理方法如下:

1.写一个异常处理类

Java代码
  1. public class NoMemoryDeal implements UncaughtExceptionHandler  
  2. {  
  3.     public NoMemoryDeal() {  
  4.         super();  
  5.     }  
  6.   
  7.     public void uncaughtException(Thread t, Throwable e)  
  8.     {  
  9.         e.printStackTrace();  
  10.         e.getLocalizedMessage();  
  11.         if(e instanceof java.lang.OutOfMemoryError)  
  12.         {  
  13.             KLinkLog.writeLog(KLinkLog.ERROR, "OutOfMemoryError, app exit!");  
  14.             //退出程序  
  15.             System.exit(0);  
  16.         }  
  17.         else  
  18.         {  
  19.             KLinkLog.writeLog(KLinkLog.ERROR,"PID:"+t.getId()+" msg:"+ e.getMessage());  
  20.         }  
  21.   
  22.     }  
  23.   
  24. }  

2.在程序入口处设置

Thread.setDefaultUncaughtExceptionHandler(new NoMemoryDeal());

如果只想在本线程设置则

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

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