I have a class, called counter. It looks like this:
public class Counter {
private int count;
public Counter() {
count = 1;
}
public int getCount(){
return count;
}
public void incrementCount(){
count++;
}
I want to share a single instance of this between every user of a tomcat application.
So user 1 and user 2 would both see getCount() as the same value.
Assume for this that there is a technical reason why I can’t store and read from a database.
Any advice?
Thanks.
Just create one and store it in the application scope during server’s startup.
This way it’s available in every servlet as follows:
And in every JSP as follows:
See also:
Unrelated to the concrete problem, your counter is not threadsafe. I’d suggest to use
AtomicIntegerinstead ofint.