13

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

Community
  • 1
  • 1
user1508454
  • 301
  • 1
  • 4
  • 16

1 Answers1

32

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.

Woodchuck
  • 3,869
  • 2
  • 39
  • 70
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • @Tomasz.can you post here a short example by which you can justify lets say you have a simple servlet and with 2 different browsers you are making a request and by deliberate by one thread you change the value. this thing I want to see..!!Thanks in advance – user1508454 Jul 14 '12 at 16:50
  • Great man , could you please post how would you protect the counter now , and by synchronized will it make impact on performance , could you also please explain a little bit about Atomic Integer – user1508454 Jul 14 '12 at 16:54
  • counter will be shared object, so every member who uses this servlet will have the same `counter` object – Elbek Jul 15 '12 at 04:13