1

I have a scenario and cant find reasonable answer. So posting the question directly !

Scenario -

  1. I make a ajax request and send a file to be uploaded to the server.

  2. On server(tomcat), I download the file and start processing it.

I run the download-file method on main thread and process-file method on new thread since it takes too long for processing and I dont want user to wait so long.

My Issue :

The Ajax response will catch the response in call back method for download-file method.

My process-file method also return the status response which I require to display on front-end when the processing is complete.

But I cannot because Runnable Interface has return type void for its run method.

Question -

  1. How can I get result from process-file method and send in as response to front-end
  2. If I am able to acheive above, how can I catch the response on front end javascript since main thread response will be caught in ajax success method already.
Sham
  • 71
  • 1
  • 1
  • 5
  • Could you please provide a [mcve]. – GhostCat May 17 '17 at 08:00
  • @GhostCat -- Hey thanks for interest ! I am having CSV with 10000 entries, I am required to store each entry in database. These take too much time and I dont want user to wait so long. Will these help??? – Sham May 17 '17 at 09:09
  • No. I mean: a piece of code that shows what you are doing ... – GhostCat May 17 '17 at 09:14

1 Answers1

0

First: You can get result from process-file method by using Callable along with ExecutorService. Here is an example. And return to the front end is explaining below.

Second: As you do not want to wait user for process-file method so that you already return from main thread and you can not get second return by one single request. The following process make you to understand for better and easier solution for this situation.

  1. Assign a id (e.g. UUID) for the process-file method. Pass it to the process-file method and return the id from main thread to front-end if successfully downloaded.
  2. Then after processing your file, store in DB/wherever you want or put result in a Map<id, result> where id will be the key.
  3. In front end you get the id for the process-file method. You can do call ajax request for certain interval to get the result of this id to a different endpoint (e.g. /file/status/{id}).
  4. In that endpoint for retrieving result, you can get result from Map by id which is key of the Map or if you store in DB then you can easily get by the id and return it to front end.
  5. In case you can not get result in Map/DB (in case of the file-processing not finished yet) you can send exception to frontend so that you can send request again after next interval.
Community
  • 1
  • 1
Zico
  • 2,349
  • 2
  • 22
  • 25