解决out of momery 问题

     程序员开发难免会遇到头疼的 out of momery 异常,该异常关键是不可捕获,哪个线程抛出该异常,那么该线程除了最后访问finally代码块外,只有退出。
     可是退出一般不是程序员所看到的,也就是抛出该异常之后如何处理结下来的工作,并不仅仅就是退出完事了,当然可以把代码写到finally里,但finally 一般都是清理资源。
     经测试发现抛出OOM异常之后,其会被Thread类的disPatchUncaughtExceptionHandler()方法捕获,从而终结该线程。
     那么如何才能正确处理Out of momery异常呢?下面的代码结构为解决OOM提供了很好的帮助。
package exception;

import java.lang.Thread.UncaughtExceptionHandler;

public class TestOutOfMomeryException {
	public static void main(String[] args) {

		Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() {

			@Override
			public void uncaughtException(Thread t, Throwable e) {
				new Thread(new Runnable() {

					@Override
					public void run() {
						TestOutOfMomeryException.main(null);
					}
				}).start();
			}
		});
		

		do {
			try {
				
				throw new OutOfMemoryError();
				
				
				
				
			} catch (Exception e) {
				System.err.println("catch");
			} finally {
				System.err.println(" ====== error ======");
				printf();
			}

		} while (true);
	}

	private static void printf() {
		System.err.println("i can");
	}
}


可是适当更改,更好的处理OOM问题,可以采用增量控制的方式解决OOM问题

猜你喜欢

转载自fay19880111-yeah-net.iteye.com/blog/1447963