HttpSessionListener实现session定时扫描仪

package cn.lfd.web.listener;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/*
 * session定时扫描仪
 */
public class SessionScanerListener implements HttpSessionListener,ServletContextListener {
	private List<HttpSession> list = Collections.synchronizedList(new LinkedList<HttpSession>());//定义好装HttpSession的集合
	private Object lock = new Object();//锁
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		Timer timer = new Timer();
		timer.schedule(new MyTask(list,lock), 0, 1000*60);//计时器 一分钟扫描一下session
	}
	
	@Override
	public void sessionCreated(HttpSessionEvent se) {
		HttpSession session = se.getSession();
		synchronized (lock) {
			list.add(session);//session一被创建就加到集合中
		}
		
		System.out.println("创建");
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		System.out.println("摧毁");

	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		
	}
}
class MyTask extends TimerTask{//要定时执行的任务
	private List<HttpSession> list;
	private Object lock;
	
	MyTask(List<HttpSession> list,Object lock) {
		this.list = list;
		this.lock = lock;
	}
	@Override
	public void run() {
		synchronized (lock) {//使list集合在添加的时候不会执行删除,解决并发问题
			ListIterator<HttpSession> it = list.listIterator();
			while(it.hasNext()) {
				HttpSession session = (HttpSession) it.next();
				if(System.currentTimeMillis()-session.getLastAccessedTime()>=1000*60) {//判断session多久没有使用
					session.invalidate();//一分钟没有使用的session自动摧毁,减轻系统压力
					it.remove();
				}
			}
		}
	}
}


 

你可能感兴趣的:(java,session,servlet,监听器)