Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding thread safety of servlet [duplicate]

Possible Duplicate:
How do servlets work? Instantiation, session variables and multithreading

Is servlet is thread safe ..? For ex If I open 5 different browsers and sending request to one servlet in the container , is it still thread safe , I means the service() method specially

like image 492
user1508454 Avatar asked Jul 14 '12 16:07

user1508454


1 Answers

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.

like image 102
Tomasz Nurkiewicz Avatar answered Oct 11 '22 18:10

Tomasz Nurkiewicz