Search code examples
multithreadingspring-bootspring-mvcthreadpoolresttemplate

How does resttemplate.exchange() execute on a different thread?


It is my understanding that call to exchange method of resttemplate executes on a different thread. Basically all client libraries execute on a different thread.

Let's say my servlet container is tomcat. When a request is made to the endpoint exposed, tomcat thread recieves the request and the request comes to service layer from controller layer on the same thread. In the service layer, I have a call to 3rd party service using resttemplate. When exchange method is invoked, internally the operation runs on different thread and gets the result of the operation.

I have a question regarding this:

Where does the resttemplate get the thread from basically from which thread pool to execute on a different thread ?

I would like to know if executing resttemplate on a different thread has got to do anything with tomcat thread pool.

Can anybody shed some lights on this?


Solution

  • When a request is made to the endpoint exposed, tomcat thread recieves the request and the request comes to service layer from controller layer on the same thread.

    This happens only if tomcat and java applications are in same JVM (like in embedded tomcat). Otherwise, by default, Java threads are created and destroyed without being pooled. Of course, you can create a java thread pool too.

    Every time a third-party API is called via RestTemplate it will create new Httpconnection and will close it once it is done. You can create RestTemplate's own connection pool using HttpComponentsClientHttpRequestFactory like so:

    new org.springframework.web.client.RestTemplate(new HttpComponentsClientHttpRequestFactory())