Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does each request access the same servlet object?

Does each HTTP request access the same servlet object but in a different thread? or does it create a new thread and new Servlet Instance ?

like image 765
KyelJmD Avatar asked Sep 20 '12 09:09

KyelJmD


People also ask

How does the same servlet handle multiple requests?

A servlet is a singleton, and is shared among all the requests. Each request is served by a thread, and concurrent requests are thus served by concurrent threads, each calling the same servlet concurrently.

Does each request in servlet runs in separate thread?

You might hear people say things like, “Each instance of the servlet...” but that's just wrong.

How many servlet objects are created for multiple requests?

1) How many objects of a servlet is created? Only one object at the time of first request by servlet or web container.

How many servlet instances are created when multiple requests arrive simultaneously?

Regardless of the number of request only one instance of Servlet will be created by the container per servlet per jvm.


2 Answers

The container will use the same servlet instance if your servlet don't implement SingleThreadModel. Otherwise there is no guarantee that the same Servlet object is hit. The container is free to create more servlet instances if it considers necessary. But the requests comes on different threads, not necessarily newly created (as Sanjay mentioned).

From the Servlet 3.0 specification:

For a servlet not hosted in a distributed environment (the default), the servlet container must use only one instance per servlet declaration. However, for a servlet implementing the SingleThreadModel interface, the servlet container may instantiate multiple instances to handle a heavy request load and serialize requests to a particular instance.

...

Generally the Web container handles concurrent requests to the same servlet by concurrent execution of the service method on different threads.

like image 120
dcernahoschi Avatar answered Nov 15 '22 04:11

dcernahoschi


Each HTTP request creates a new thread but accesses the same instance of the Servlet.

EDIT: In case of one server node, you will have the same Servlet instance on that node. In case of load balancing/many servers you will usually have one instance per Java VM.

like image 21
Marko Krajnc Avatar answered Nov 15 '22 04:11

Marko Krajnc