站内搜索: 请输入搜索关键词

当前页面: 开发资料首页JSP 专题为什么通过HttpSessionListener统计网站在线人数会出现负值?

为什么通过HttpSessionListener统计网站在线人数会出现负值?

摘要: 为什么通过HttpSessionListener统计网站在线人数会出现负值?


package syidt.strutsweb.cms.sessioncounter;

/**
*

Title: idtcms


*
*

Description:


*
*

Copyright: Copyright (c) 2006


*
*

Company: **软件


*
* @author not attributable
* @version 1.0
*/
public class OnlineCounter {
private static long online = 0;
public static long getOnline() {
return online;
}
public static void raise(){
online++;
}
public static void reduce(){
online--;
}
}

package syidt.strutsweb.cms.sessioncounter;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
*

Title: idtcms


*
*

Description:


*
*

Copyright: Copyright (c) 2006


*
*

Company: **软件


*
* @author not attributable
* @version 1.0
*/

public class OnlineCounterListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent hse) {
OnlineCounter.raise();
}
public void sessionDestroyed(HttpSessionEvent hse) {
OnlineCounter.reduce();
System.out.println("Destory Session");
}
}



syidt.strutsweb.cms.sessioncounter.OnlineCounterListener


如上实现.

但为什么在线人数会显示出负数.并我己设置TOMCAT...


30




运算不够严谨!


试试异步锁


运算不够严谨?

何意?


加锁试试


how to ?



sessionCreated和sessionDestroyed方法加上synchronized

在没家同步以前,如果当前在线人数为count=0,现在有两个人同时进入sessionCreated方法,同时对同一个数值加一,结果只加了一,在线人数变成count=1,本应该是2.
而当两个人不在同一时间离开的时候,对count进行了两次减1,那么count=-1


示例一下?



public class OnlineCounterListener implements HttpSessionListener {
public synchronized void sessionCreated(HttpSessionEvent hse) {
OnlineCounter.raise();
}
public synchronized void sessionDestroyed(HttpSessionEvent hse) {
OnlineCounter.reduce();
System.out.println("Destory Session");
}
}
不会还不明白吧


比如说现在是0,如果两个人或多个同时来修改这个0,他们同时都执行的是0++,结果每个人的执行结果都是1,他们都把1返回了.所以同时来N个人结果都是加了1.
所以要保证在同一时刻只能有一个人访问这个方法.


谢谢.明白了

万分感谢


汗...终于明白了哈...揭贴楼...


↑返回目录
前一篇: TOMCAT问题,在线等,谁解决了立马100分
后一篇: response.sendRedirect("e321a.jsp")