static
fields in a class will live until the class itself is unloaded and garbage collected. So, static
fields in a serlvet will not only live across all the sessions but across the whole application, in this case, until the web application is undeployed.
In fact, it is not wise to have any field in a servlet unless this field cannot be modified after being initialized or if it is injected by the container like an EJB or a CDI bean. This is because a single Servlet instance will be used to attend several requests made to the server, so even if you have a non-static
field in your servlet and you update it through requests, its value can be modified by two or several requests happening at the same time. Try to keep the variables to the shortest possible scope, for example, inside a method only.
More info:
From comments, looks like your real problem is about a design to support synchronization across several threads. A better option would be creating an object instance that will be shared among your threads, then use a final
non-static
field to handle the synchronization:
class MyClass {
final Object lock = new Object();
//other fields in the class...
}
class Multijobs {
class Job implements Runnable {
MyClass myClass;
public Job(MyClass myClass) {
this.myClass = myClass;
}
@Override
public void run() {
//handle the job here...
//using the synchronization point
synchronize(myClass.lock) {
}
}
}
static final int NUM_THREADS = 10;
public void executeSeveralJobs() {
ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS);
MyClass myClass = new MyClass();
executorService.execute(new Job(myClass));
executorService.execute(new Job(myClass));
//initialize the jobs and add them to the ExecutorService
//...
executorService.shutdown();
//...
}
}