3 Replies Latest reply on Jun 15, 2018 11:13 AM by Helen Chen

    how to use ExecutorService in webapp

    Helen Chen Novice

      Hi there,

       

      I have a restful webapp. request can contain large set of data. so inside the restful webservice logic, I want to split the processing into 2 parts. the 1st part will receive data, validate data and save data to database. the 2nd part is really going through the data and apply business logic to it. The 2nd part can take a while to finish. The 1st part does not need to wait for 2nd part output.

       

      so I'm thinking to make 2nd part as Runnable, and to use ExecutorService, like

      `Executors.newCachedThreadPool()`

       

      so I think I can have a singleton to hold this ExecutorService instance, when the 1st part finish, it can submit the job to the ExecutorService, and ExecutorService will execute the 2nd part. This way the ExecutorService will holds a thread pool, the thread can also be reused. So basically I use ExecutorService for background processing

       

      But I'm not sure about a few questions:

      1. is this the right way to use ExecutorService? Is there any better way to do it?

      Since I'm already inside a webapp server (I'm using Wildfly), can I also use ExecutorService like this? Somehow I feel ExecutorService is usually used either on server side or in a standalone application.

       

      2. how and when do I initial the shutdown for the ExecutorService?

      Since I'm making it as Singleton, I expect this ExecutorService instance keeps running until the application is undeployed or the server is shutdown. So when and how the shutdownNow() can be triggered? also when the server is shutdown, even the tasks inside ExecutorService is not done, I guess I have no control on it. Is there anything I can do to at least log something?

       

      Thanks, Helen