1

What I know

A web container creates a new thread per request.

What I don't know

Are new servlet objects created per request?

Why I am asking this is to get an idea on how thread synchronization issues can happen if the same servlet object is used for multiple requests.If the web container creates a new servlet object for each new reqest, then I don't see an issue. But if it uses the same servlet object to serve multiple requests, synchronization issues can happen.

How is this handled in a typical java web container?

DesirePRG
  • 6,122
  • 15
  • 69
  • 114

3 Answers3

2

A web container creates a new thread per request.

No. It reuses a thread from a thread pool.

Are new servlet objects created per request?

No. A servlet is a singleton. Only one instance is created per web app. Your servlet must be thread-safe, since it's called concurrently by several threads. But that' usually easy, because a servlet is typically stateless.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

Are new servlet objects created per request ?

By default, Servlet container creates a single servlet instance and will be used to serve all of the requests in a separate thread. So ensure that your servlet class is thread safe (i.e., your servlet class should not hold any stateful data as instance variables, etc..).

Adding to that, Servlet containers create the servlet instance either during the container start-up or upon the first request received. You can force the container to create the servlet instance by specifying the load-on-startup in web.xml or @WebServlet(urlPatterns="/xyz", loadOnStartup=1)).

It is generally better to load the servlets (unless you have any special requirements) using load-on-startup so that the first request will not hit with the performance.

Vasu
  • 21,832
  • 11
  • 51
  • 67
0

In general sense servlets are Singletons, however if you map the same servlet class to different URL mappings using different names, you will have that many instances of same servlet.

Mostly servlets are stateless, if you do make them statefull, then be very careful about shared mutability . Earlier servlet API used to have SingleThreadModel Interface to impose single thread access at one point of time, that way you could serve only one request at a time, However I see this interface is deprecated in recent APIs as it doesn't solve the concurrency issues fully, like static variables etc.

TruckDriver
  • 1,383
  • 13
  • 28