一个同步 锁的案例

package cn.web.listener.exapmle;


import java.util.Collections;
import java.util.Iterator;
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 contextInitialized(ServletContextEvent sce) {

Timer timer = new Timer();
timer.schedule(new MyTask(list,lock), 0, 30*1000);
}

public void sessionCreated(HttpSessionEvent se) {
HttpSession session = se.getSession();
System.out.println(session + "被创建了!!");
synchronized (lock) {  //锁旗标
list.add(session);
}
}
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println(se.getSession() + "被销毁了");
}


public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
}


class MyTask extends TimerTask{


private List list;
private Object lock;
public MyTask(List list,Object lock){
this.list = list;
this.lock = lock;
}
@Override
public void run() {
System.out.println("定时器执行!!");
synchronized (this.lock) {
ListIterator it = list.listIterator();
while(it.hasNext()){
HttpSession session = (HttpSession) it.next();
if((System.currentTimeMillis()-session.getLastAccessedTime())>30*1000){
session.invalidate();
//list.remove(session);  //并发修改异常
it.remove();
}
}
}
}
}


/*class MyList{

Object arr[] = new Object[10];
public void add(Object obj){  //session
if(arr[0]==null){

arr[0] = obj;
}

}
}*/

你可能感兴趣的:(一个同步 锁的案例)