简体   繁体   中英

Run multi threads in servlets

I have couple of processes (calling to a 3rd party service and get response, query database and get results, do some IO operations etc) to be executed in my servlets. Moreover, those processes are time consuming and if the 3rd party call which is the first process, response fails, the rest of processes should be terminated too.

I am to run all these processes as multi threads using Executors. As soon as possible, the response of first process is available, the servlet should send response ( redirect to a page ) . When the rest of all process are finished, the output should be sent to the page again (something like push to the browser), or redirect to another page, ( but then want to have the access to the already running rest of threads.

My first attempt was to send ajax requests from the browser and handle all these processes. But it is less secure. So, let me know an approach to run these threads and once first process is done, send the response and later return the rest of outputs.

My recommendation in this situation is to make the entire page asynchronous. Send request, kick off threads and return immediately. The threads can populate a common object contained in session, write to files or a database. Once complete, set a flag to show any subsequent requests from the client (polling requests, etc) that you're finished and the page can be built.

You can present the interim page in various ways ("Check back" message, polling with progress bar, et. al.).

There are two options after knowing which IE version we have to support

  1. Use an AJAX based implementation.

Using AJAX and HTTP POST, trigger your services one by one. Also make sure that promises are maintained in order to keep a clean state of requests. You can also use ajax chaining, if you have to follow order of completion as well. Please note AJAX as such has no security limitations (see here ), it is just an API which uses HTTP methods to call server, in an asynchronous way. So if your server has security, AJAX can/need inherit that security.

  1. Use a websockets based implementation

Since IE8 does not support websockets natively, you can use a custom api such as this . Please note this will have some compatibility issues going forward, but for now there are no visible impacts. Call the servlet which will trigger different threads, and send back the data after completion of threads. If your server has websocket-api.jar in its server lib, then you can code the server side of it very easily. See here

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