Globally Control thread pools in ExecutorService

时间:2015-07-28 16:11:05

标签: java multithreading web-services

I have many I/O intensive jobs that are triggerred via Jersey webservice calls like this:

https://localhost/rest/execute/job/job1

I want to globally control the number of threads these jobs are using. How do I do this? I have thought of following two options, please suggest if I am in right direction or if there is a better solution.

Approach 1:

Create a wrapper class over ThreadPoolExecutor that provides threads to various services to submit runnables.

class GlobalThreadPool {

int corePoolSize    = 1;
int maximumPoolSize = 4;
BlockingQueue<Runnable> q =  BlockingQueue<Runnable>(10);

private ExecutorService pool = ThreadPoolExecutor(corePoolSize, maximumPoolSize, ..., q);

public Future<?> run (Runnable task) { pool.submit(task); }

}

Then use this class as ServletContextListener to start and shutdown with webservice.

  • (+) REST resource gets an instance of this class from ServletContext and submits the requested job.
  • (-)If a submitted task wants to use additional thread, it won't be able to do that as the run() method won't have access to service context.

Approach 2:

Create a Singleton of GlobalThreadPool. Then we Will not start it via web services listener. However, whenever a job needs it, it will instantiate the class and submit the runnable.

  • (+) any job has access to the pool irrespective of whether it has access to ServletContext
  • (-) shutting down the ExecutorService is not tied with webservice

Do you see any particular problem in any of these approaches that I might be missing? Is there any better (read standard) approach to do these things?

0 个答案:

没有答案