自定义session扫描器

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;

public class SessionScanner implements HttpSessionListener, ServletContextListener {
	private List<HttpSession> list = Collections.synchronizedList(new LinkedList<HttpSession>());
	private Object lock = new Object();

	public void sessionCreated(HttpSessionEvent se) {
		HttpSession session = se.getSession();
		System.out.println(session + "被创建了");
		synchronized (lock) {
			list.add(session);
		}
	}

	public void sessionDestroyed(HttpSessionEvent se) {
		HttpSession session = se.getSession();
		System.out.println(session + "被销毁了");
	}

	public void contextInitialized(ServletContextEvent sce) {
		Timer timer = new Timer();
		timer.schedule(new MyTimerTask(list, lock), 0, 1 * 60 * 1000);
	}

	public void contextDestroyed(ServletContextEvent sce) {

	}

}

class MyTimerTask extends TimerTask {
	public List list;
	private Object lock;

	public MyTimerTask(List list, Object lock) {
		this.list = list;
		this.lock = lock;
	}

	public void run() {
		synchronized (lock) {
			ListIterator it = list.listIterator();
			while (it.hasNext()) {
				HttpSession session = (HttpSession) it.next();
				if ((System.currentTimeMillis() - session.getLastAccessedTime()) > 1 * 60 * 1000) {
					session.invalidate();
					it.remove();
				}
			}
		}
	}
}

你可能感兴趣的:(session)