java定时清理垃圾的servlet实现

MyTask 垃圾回收类  调用system.gc
import java.util.TimerTask;

public class MyTask extends TimerTask {
	public void run(){
		
		long beginTime = System.currentTimeMillis();
		System.out.println("===========垃圾收集开始时间: " + beginTime);
	    System.gc();
		long endTime = System.currentTimeMillis();
		System.out.println("===========垃圾收集结束时间: " + endTime);	
		System.out.println("===========垃圾收集所用时间: " + (endTime - beginTime));
		System.runFinalization();
	}
}


FixedTimeGC 类 实现定时回收垃圾
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

public class FixedTimeGC extends HttpServlet {


	public void destroy() {
		super.destroy(); 

	}

	public void init() throws ServletException {
		System.out.println( "=======FixedTimeGC init  ======"); 
		TimerTask myTask = new MyTask();
		Timer timer = new Timer(true); 
	    timer.schedule(myTask, 0, (long)20*60*1000);
	}
	
}



web.xml加入
<servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>FixedTimeGC</servlet-name>
    <servlet-class>com.XXX.utilBean.FixedTimeGC</servlet-class>
  	<load-on-startup>5</load-on-startup>
  </servlet>


你可能感兴趣的:(servlet)