Regarding thread safety of servlet [duplicate]

Your question boils down to: is calling a method from multiple threads on the same object thread safe. And the answer is: it depends. If your object (let it be servlet) is stateless or has only final fields, this is completely thread safe. Local variables and parameters are local to the thread (reside on stack, not on heap).

Also each service() call receives a distinct instance of ServletRequest and ServletResponse. However, here is an example of an unsafe servlet:

public class UnsafeServlet implements Servlet {

    private int counter;

    public void init(ServletConfig config) throws ServletException {
    }

    public void service(ServletRequest request, ServletResponse response)
        ++counter;
    }

    public void destroy() {
    }

}

Since multiple threads can access the counter variable, it has to be secured somehow: either by using synchronized (volatile is not enough):

synchronized(this) {
    ++counter;
}

or AtomicInteger:

private AtomicInteger counter = new AtomicInteger();

//...
counter.incrementAndGet();

In this particular case AtomicInteger is much better since it is lock-free using CAS CPU operations while synchronized is a mutex.

Leave a Comment