Servlet Multi-Threading, the place of the worker thread created - multithreading

Servlet creates one new thread to process the request per request, so where is the
thread created? Is it created by the servlet container like tomcat?

Servlet creates one new thread to process the request
No. The servlet doesn't create any thread. The container (Tomcat, for example) is the one creating threads. And it doesn't create a new thread per request. It has a pool of available threads, gets one from the pool to handle a request, handles it, and then puts the thread back to the pool of available threads.

Related

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?
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())

Is every method of ServerEndpoint executed by different thread?

I use GF 4 as JavaEE server.
This is how I understand servlet processing: There is a pool of threads and when request comes one thread from this pool is taken to process the request. After that the thread is put back to pool.
Based on the information above I suppose (I am not sure) that websockets (server end points) are processed this way: There is pool of threads, when
Client creates new websocket a thread is taken from pool to create new instance of ServerEndpoint and to execute #OnOpen method. After that thread is put back to pool.
Client sends message over websocket to server. Thread is taken from pool to execute #OnMessage method. After that thread is put back to pool.
Client closes the websocket - thread is taken from pool to execute #OnClose method. After that thread is put back to pool.
It all means that every method of ServerEndpoint can be executed by different threads. Is my understanding right?
Yes.
The ServerEndpoint instance lives as long as the associated WebSocket session is available as Session argument during #OnOpen. During that WebSocket session, many HTTP and WebSocket requests may be fired. Each such request accounts as an individual thread.
In other words, if your ServerEndpoint class needs to deal with instance variables in multiple methods for some reason, it must be implemented in a thread safe manner. Depending on the concrete functional requirement, you'd probably better use Session#getUserProperties() instead to carry around state associated with the WS session (think of it as session attributes).
Noted should be that this all is regardless of the container and WS implementation used.

Safe to spawn a new thread inside request thread in spring

I have a spring controller. The request thread from the controller is passed to the #Service annotated Service class. Now I want to do some background work and the request thread must some how trigger the background thread and continue with it's own work and should not wait for the background thread to complete.
My first question : is this safe to do this.?
Second question : how to do this.?
Is this safe
Not really. If you have many concurrent users, you'll spawn a thread for everyone of them, and the high number of threads could bring your server to its knees. The app server uses a pool of threads, precisely to avoid this problem.
How to do this
I would do this by using the asynchronous capabilities of Spring. Call a service method annotated with #Async, and the service method will be executed by another thread, from a configurable pool.

MDB with container managed transaction & worker thread

I have an MDB which uses container managed transaction (my container is IBM Websphere 7).
Websphere is using a global (JTA) transaction.
If my MDB thread starts a worker thread, and that thread begins a transaction, will that new thread be within the same transaction as the MDB?
I want the MDB thread to commit its transaction and acknowledge the MQ message as soon as my worker thread is successfully started. I do not want my MDB to rollback if the worker thread rolls back.
Edit: The code in the thread has this - it is not using annotations:
txn = (UserTransaction)ctx.lookup("java:comp/UserTransaction");
txn.begin();
So if look at txn.getStatus() it will be something other than STATUS_NO_TRANSACTION. Therefore I need to get the transaction manager appropriate for Websphere 7 and call "suspend()" before the txn.begin()? Is the correct approach to prevent problems?
Put the code which should not be in the same transaction as the onMessage() method into a separate method and set the transaction attribute for that method to REQUIRES_NEW. This will create a new transaction when the method is called and the success or failure of this new transaction won't affect the preexisting one.
By the way, you aren't supposed to do explicit thread management in JavaEE applications.
From the EJB 3.0 spec:
The enterprise bean must not attempt to manage threads. The enterprise
bean must not attempt to start, stop, suspend, or resume a thread, or
to change a thread’s priority or name. The enterprise bean must not
attempt to manage thread groups.
You could look at using the timer service to effectively create a separate thread while leaving thread management to the server.
If you are using ejb 3.1 an option would be to do the worker work in a method annotated with
#Asynchronous
This will give you a new transaction and the work will be performed in a separate thread.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/asyncMethodOfEJB/AsyncMethodEJB.html
Read more about default transaction mode: Default EJB transaction mode for asynchronous methods?

Custom threads in serlvets and servlet lifecycle

Say I start a thread(not daemon) of my own in a servlet(can be a controller in springMVC app or a struts action controller):
Let us assume that the action is done with it's processing and wants to push the response out. Will this happen even though the thread I started is still running? Basically what I want to know is will the container wait till the thread is done with it's work to push the response out?
Assuming in the above, the container does not wait for the thread to push response out, will it wait till the background thread is done to reap the servlet thread spawned to handle this particular request or it will reap this thread only when the custom thread is done with it's work?
A custom thread spawned by a servlet thread is no different than any other thread: it's an independant, parallel flow of execution. The servlet thread doesn't care about the custom spawned thread: it continues its execution.
So the response will be sent to the browser as if no custom thread had been spawned, and whether the custom spawned thread is still running or not is irrelevant.
Once the servlet thread has finished serving the request and sending the response, it goes back to the pool and can start serving another request. Once again, whether a custom thread has been spawned, and whether this custom thread is still running, are irrelevant.

Resources