2

So I read this great thread: Difference between each instance of servlet and each thread of servlet in servlets?

And it says "the servletcontainer reuses the same servlet instance for every request. "

So let's say we have a servlet:

public class MyServlet extends HttpServlet {



    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object thisIsThreadSafe;

        thisIsThreadSafe = request.getParameter("foo"); // OK, this is thread safe.
    } 
}

So does the servlet container, when initializing it will call internally:

MyServlet myServlet = new MyServlet(....);

And then when a request matches what is in the web.xml, it will return this instance myServlet.

What I need help understand is, when the call to:

myServlet.doGet(..)

How does multi-threading work when there is only 1 instance? This isn't specific to servlets really, I just can't wrap my head around how this works.

Say there are 10 concurrent users on the website hitting this same servlet at the exact same time, this instance is shared accross all of them, why doesn't it then block and work in a serial manner, how does it do this concurrently?

Community
  • 1
  • 1
codecompleting
  • 8,513
  • 13
  • 56
  • 95
  • Maybe @BalusC can't chime in here as he did a great job with that writeup, I'm just stumbling on this point still. – codecompleting Dec 09 '11 at 14:34
  • Another related answer is this: http://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-session-variables-and-multithreading/3106909#3106909 – BalusC Dec 09 '11 at 14:46

1 Answers1

7

This is not specific to Servlets. This is specific to Java. The Java language and VM supports invoking a single method by multiple threads. Each thread will just have its own share of method-local variables. If you want to restrict this, you've to add a synchronized lock to the method or to let the servlet implement the (deprecated!) SingleThreadModel interface. But that's not necessary if you write servlet methods on a threadsafe manner (i.e. do not assign request/session scoped data as instance variable).

informatik01
  • 15,174
  • 9
  • 67
  • 100
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • I see so the key point to multi-threading is the VM creates a single instance, yet each thread that calls this shared instance makes method-local variables. is there more to it? any links to understand this further? – codecompleting Dec 09 '11 at 14:49
  • 1
    The method local variables are basically stored in the thread, not in the instance. They are trashed when the thread leaves the method. I answered this as "Each thread will just have its own share of method-local variables". Check the "supports" link in my answer. It's quite a read, but that's the best authoritative explanation you can get about the internal workings. – BalusC Dec 09 '11 at 14:51