简体   繁体   中英

How server spawns new thread for a singleton object in spring framework

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM