Hey Carl,

On Tue, Mar 10, 2015 at 11:25 AM, Carl Dreher <focus...@arn.net> wrote:

> If I write a servlet such as the above, is there ever only once instance
>> of it running?
>>
>
>  Don't confuse objects with threads.  There is one instance of a
>>> particular servlet, but many threads may be executing in it concurrently,
>>> with each thread processing a separate request.
>>>
>>
> I understand that each request is handled by a separate thread.  But does
> each thread have its own copy of the servlet code?  Or does each thread
> request the use of the servlet, wait until it is available, use it, and
> then release it back to be used by the next thread, sort of like a database
> connection? I'm pretty sure it is the former, but just wanted to check.


Chuck pointed you to the Servlet API specification. Read upon how Servlets
work, e.g.
https://jcp.org/aboutJava/communityprocess/final/jsr340/index.html

Your servlet will likely extend from HttpServlet (see JavaDocs here -
https://tomcat.apache.org/tomcat-8.0-doc/servletapi/javax/servlet/http/HttpServlet.html
)

There is exactly one (object) instance of your servlet in your application
context. Tomcat is a multi-threaded server (out-of-box), so you need to be
careful with writing your servlet code, make sure it is thread-safe (e.g.
synchronize access to shared resources, use local variables, etc). Your
servlet constructor and servlet init method are going to be called only
once when the servlet is initialized. Subsequently, service methods are
going to be called and executed concurrently by multiple threads, e.g.
doGet(), doPost(), etc...

So, to answer your question - the threads are not waiting for other threads
to finish, unless you introduced synchronization somewhere in your servlet
code. Synchronization will slow things down, but it might be necessary to
make things thread-safe. Avoid synchronization if you can :)))

Hope that helps!

Cheers!
Neven

Reply via email to