Reputation: 410
What is the best way/pattern for counting the number of active users using a particular java EE JSF web app?
The two ways I know is HttpSessionListener and using JMX web beans, if there is a third better way I am open to suggestions. I am just trying to figure out the most elegant solution.
Help is much appreciated
Upvotes: 1
Views: 4223
Reputation: 49372
If you want to track the number of active users at the same time in simple Java web app built without using any frameworks , then the standard way to do that is to implement HttpSessionListener
. Code below is just a reference to the way you can implement it .
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class ActiveUserCounter implements HttpSessionListener {
private static AtomicInteger activeSessions = new AtomicInteger();
public void sessionCreated(HttpSessionEvent se) {
activeSessions.incrementAndGet();
}
public void sessionDestroyed(HttpSessionEvent se) {
if(activeSessions.get() > 0)
activeSessions.decrementAndGet();
}
public static int getActiveSessions() {
return activeSessions.get();
}
}
Define the listener class in your web.xml .
Upvotes: 4