This is an excerpt from the book "Head First Servlets and JSP". What I don't understand is why the init()
method alone runs in thread A
, and the service()
methods that come after run in a different thread, B
.
Does this mean every request from the browser to the servlet gets two threads? Or is init()
common for all servlet instances that a container might create? That would be wrong because it is not a static method?
init. Called by the servlet container to indicate to a servlet that the servlet is being placed into service. The servlet container calls the init method exactly once after instantiating the servlet. The init method must complete successfully before the servlet can receive any requests.
A Java servlet container / web server is typically multithreaded. That means, that multiple requests to the same servlet may be executed at the same time.
The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. It simply creates or loads some data that will be used throughout the life of the servlet.
difference work of between init() and constructor? The constructor is called by the container simply to create a POJO (plain old java object). init method is the method which is invoked when servlet in called and it adds values to the servlet context so its a very much difference between constructor and init method...
The servlet is initialized just once by init()
, but for every new request a new thread is created or allocated from a pool to invoke that servlet instance on the appropriate method.
The HttpRequest
and HttpResponse
objects will be new for each new request, and the thread, but not the servlet instance.
This description applies to single servlet instance. Intuitively you can think of it as processing requests in other threads not to block the main thread. If the request is time-costly, there is no point in freezing the application to serve it, so every request leads to fork.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With