public void sessionDestroyed(HttpSessionEvent event) {
Integer num = (Integer) ctx.getAttribute("numSessions");
if (num == null) num = 0; // 錯誤:未登錄用戶退出時 num 為 null 設為 0,再 -1 變 -1
else num = num - 1;
ctx.setAttribute("numSessions", num);
}
用戶未登錄 (無 Session) 直接訪問退出頁面或超時,觸發 sessionDestroyed,但 numSessions 可能為 null 或 0,直接遞減導致負數。
public void sessionDestroyed(HttpSessionEvent event) {
ServletContext ctx = event.getSession().getServletContext();
Integer num = (Integer) ctx.getAttribute("numSessions");
if (num != null && num > 0) {
ctx.setAttribute("numSessions", num - 1);
} // else 不處理,保持 0 或 null
}
AtomicInteger 避免併發競態。sessionCreated 中 incrementAndGet(),sessionDestroyed 中 decrementAndGet() 並配合 max(0, ...)。