E
E
ericcartman2018-03-26 14:41:06
Java
ericcartman, 2018-03-26 14:41:06

Servlets, multithreading, how does it work?

Good afternoon,
Suppose I wrote a servlet (or made a web service using @RequestMapping in spring) and run it in Tomcat.
Suppose there were 10k users.

  1. Tomkat will create 10k threads? Or put in a queue, starting with the n-th? Is it in the configs?
  2. Let's assume the servlet climbs in a DB. How to do it right? connection pool?
  3. How to cache data, let's say the first servlet in the first request pulled data from the database, I would like to cache some common part for everyone. Do it in ServletContext? If I want to use some kind of cache, well, like memcache, let's say, will it be shared between all instances of the servlet?
  4. when the servlet instance terminates (well, or exits a method marked with @RequestMapping ) is it completely destroyed? And there is no way to pass something to another servlet instance?
  5. The whole lot of threading is driven by the servlet container (tomcat) and it is highly discouraged to create threads in the body of the @RequestMapping method yourself? In what case it is necessary to create flows there?
  6. does all servlet logic happen in synchronous mode? Well, that is, I got to the database with a heavy request, and everything will fall into place? (the server will stop responding to 10001 client requests)? How to destroy it? Do not use apache/tomcat, but jetty / undertow / nginx ?

Thanks a lot! (if there is a sensible article where this is all chewed up, I will be grateful, but plz just not a 1000-string Talmud)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-03-26
@ericcartman

On startup, Tomcat will create a thread pool and a servlet instance. When requests come in, servlet methods will run on threads from the pool. The servlet is not destroyed until the end of the server.
You can create threads yourself, but why? Especially when using Spring, which provides a whole bunch of convenient high-level abstractions for convenient work with asynchronous tasks.
With caching, you need to be extremely careful, since this is exactly the area in which you can run into multithreading problems.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question