很经典的一段代码:
list线程安全
线程锁
定时器
package com.gyarmy.servletListener; 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 Test2 implements HttpSessionListener,ServletContextListener{ private List<HttpSession> list = Collections.synchronizedList(new LinkedList<HttpSession>()); private Object lock = new Object(); @Override public void sessionCreated(HttpSessionEvent se) { // TODO Auto-generated method stub HttpSession session = se.getSession(); synchronized (lock) { list.add(session); } System.out.println("sessionCreated"); } @Override public void sessionDestroyed(HttpSessionEvent se) { // TODO Auto-generated method stub System.out.println("sessionDestroyed"); } @Override public void contextDestroyed(ServletContextEvent sce) { // TODO Auto-generated method stub } @Override public void contextInitialized(ServletContextEvent sce) { // TODO Auto-generated method stub Timer time = new Timer(); time.schedule(new MyTimeTask(list,lock), 0, 1000*60*5); } } class MyTimeTask extends TimerTask{ private List<HttpSession> list; private Object lock; public MyTimeTask(List<HttpSession> list,Object lock) { this.list = list; this.lock = lock; } @Override public void run() { // TODO Auto-generated method stub synchronized (lock) { //删除session ListIterator<HttpSession> listIterator = list.listIterator(); while(listIterator.hasNext()) { HttpSession session = listIterator.next(); if(System.currentTimeMillis()-session.getLastAccessedTime()>1000*60*5) { //删除这个session session.invalidate(); listIterator.remove(); } } } } }
0则评论给“session扫描器”