Mr.Q
Mr.Q

Reputation: 4524

how to use Servlet in multithread environment

hi iam new to servlet and i want to write a servlet code ina multi threaded environmet ( i mean for each request a new service class is genrated to serve that specific request) i dont know if it is a good approach in servlet programming, i found some technical considrations for writing thread safe Servlets in HERE BUT I dont like it (cause as i said before i guess it is better to have a separate thread for each servlet that is serviceing specific client).

i wrote a similar code using Sockets. in that case i used socket connections as a parameter to be sent to each serving thread (here is the code bellow), but in Servlet case i dont know what to use to identify client (assign cookies, use session id ...)?

                clientSocket = serverSocket.accept();
                Service serv=new Service(clientSocket);
                (new Thread(serv)).start();

Upvotes: 0

Views: 1353

Answers (1)

JB Nizet
JB Nizet

Reputation: 691755

That is automatic. The servlet container takes care of multithreading for you. You just write and deploy a webapp, and concurrent requests to this webapp will be served concurrently by the container.

So for example, if two requests come to the server at the same time, the container will assign the hendling of these two requests to 2 threads of its thread pool, and your servlet will be called concurrently by these two threads.

All you have to care about is to makeyour servlet code thread-safe. And the best way to do it is to let it stateless: not use any instance variable in your servlet, except variables initialized in the init() method and never modified after.

Upvotes: 3

Related Questions