Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the init() method of a servlet run in a different thread?

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?

enter image description here

like image 453
subject-q Avatar asked Apr 02 '19 05:04

subject-q


People also ask

Why is init () method is used in servlets?

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.

Is Java servlet multi threaded?

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.

What is true Init method?

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.

What is the difference between constructor and init?

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...


Video Answer


2 Answers

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.

like image 130
Vishwa Ratna Avatar answered Oct 19 '22 13:10

Vishwa Ratna


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.

like image 35
Andronicus Avatar answered Oct 19 '22 12:10

Andronicus