0

I have been working on spring framework controller / service / repository annotations and each class is a singleton. Whenever a request comes to server , server has to spawn a new thread for the corresponding controller class ( is a singleton ) so that each thread will have its own stack to execute the same method of class in different stacks.

When i see controller class it neither implement Runnable class nor extending thread.

I would like to know the code behind this. How exactly a server spawns a thread for singleton controller class.

Will it be done by reflection or Anonymous Thread or any other method. Please post example code.

GrandPa
  • 484
  • 9
  • 28
  • 1
    The first actor that gets hold of an HTTP request (after the web server) is the servlet container (Tomcat, Resin, Jetty, etc.). To handle concurrent loads, these containers like to put individual requests on separate threads. Since thread creation could be costly, all of them maintain a thread-pool and map each request to a free thread from the pool. By the time a request is handed over to a handler such as a servlet or a filter, it has already been put on a thread. So, handler frameworks like Spring MVC do not need to worry about spawning threads for incoming requests. – manish Aug 24 '16 at 05:25

1 Answers1

2

The server doesn't need to spawn a new thread for every new request, it would be too wasteful and not scalable. It usually has a fixed pool of threads that sit and wait for new requests. Whenever such request arrives, the server just delegates its processing to one of the idle threads. A part of the processing is calling a method on your (already existing, singleton) object.

So, there's no need for a Controller or Service to be Runnable. One of the working threads just awakes, calls a method on your class (its stack is temporarily growing during the calling) and goes back to the pool of available threads to wait for the next request (this time, the stack resets back to the state of idle waiting).

This post on threads reusing might be of interest to you.

Community
  • 1
  • 1
Andrew Lygin
  • 6,077
  • 1
  • 32
  • 37