1

I want to use a common thread pool among various reader objects. Each reader will read asynchronously using a thread from the pool. Here is how I define my executor :

public static ExecutorService executor = Executors.newFixedThreadPool();

I want to use it in TableReader objects. For example, there is a function readRows which will look like this :

executor.submit(new AsyncRowReader(...));

However, I am not sure how to handle the shutdown() step. The TableReader is part of a jar which can be used like this :

TableReader r = new TableReader(...);
while (not done) {
  r.readRow(...);
}

There could be multiple TableReader objects from a single application. I can shutdown the executor service once all of these are done. How can I detect that there no more tasks running? Is there a different type of thread pool I can use?

ToyElephant
  • 205
  • 1
  • 12
  • 4
    I think you misunderstand what shutdown does. You can `shutdown()` immediately after you have submitted your last worker and everything will still finish. You can `shutdownNow()` if you want to interrupt (via `Thread#interrupt()`) everything that's at this moment working and discarding everything that's still in queue. – zapl May 19 '16 at 17:55
  • 1
    @ToyElephant: Look at : http://stackoverflow.com/questions/7939257/wait-until-all-threads-finish-their-work-in-java/36797569#36797569 – Ravindra babu May 19 '16 at 20:11
  • @zapi : What if I don't know when my last request is filed? The application can open many reader objects. Reader objects don't have any relationship between them. I don't want the application to have to deal with this. – ToyElephant May 19 '16 at 23:50

1 Answers1

1

Sounds like you need an ExecutorCompletionService:

ExecutorCompletionService completionService = new ExecutorCompletionService(executor);

while (completionService.poll() != null) {
    System.out.println("Still working...");
}

executor.shutdown();
Chris Mowforth
  • 6,689
  • 2
  • 26
  • 36