3

I'm trying to calculate some metrics, once all the threads in the myclass are done, the job is done for the thread once i reach the timeout scenario, which i able to hit for every thread. Now in the main () method in the Group class how can i wait for all the myclass threads to complete ?

I dont want to use any sleep() scenario

Group Class

  class myGroup {

  public void run(int numThreads) {
      executor = Executors.newFixedThreadPool(numThreads);
      executor.submit(new myclass(threadNumber));

  }

  public static void main(String[] args) {

       run(noOfthreads);

       // Collect metrics once all the myclass threads are done.
   }

 }

myclass

  class myclass implements Runnable {

     try{
     }
     catch(SomeTimeoutException cte){

      // Job Done for thread
     }


  }
amateur
  • 941
  • 4
  • 22
  • 33

1 Answers1

3

Could do something like this:

List<myclass> tasks = makeAListOfMyClassTasks();
// this will kick off all your tasks at once:
List<Future<myclass>> futures = executor.invokeAll(tasks);
// this will wait until all your tasks are done, dead, or the specified time has passed
executor.awaitTermination(10, TimeUnit.MINUTES); // change this to your liking

// check each Future to see what the status of a specific task is and do something with it
for (Future<myclass> future : futures) {
    if (future.isCancelled()) {
        // do something
    } else if (future.isDone()) {
        myclass task = future.get(); // this will block if it's not done yet
        task.whatever();
    }
}

@beatngu13 also pointed out this nifty class ExecutorCompletionService; so you could do something like this:

List<myclass> tasks = makeAListOfMyClassTasks();
CompletionService<Result> ecs = new ExecutorCompletionService<Result>(exectuor);
for (myclass t : tasks) {
    // this kicks off the task and returns a Future, which you could gather
    ecs.submit(t);
}
for (int i = 0; i < tasks.length(); i ++) {
    myclass task = ecs.take().get(); // this will block until the next task is done/dead
    // ... do something with task
}

Info on futures: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html

This has examples for ExecutorService: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html

This related thread is pretty relevant: ExecutorService, how to wait for all tasks to finish

Hope this helps.

Community
  • 1
  • 1
yoshi
  • 171
  • 5
  • +1 from me if you add [ExecutorCompletionService](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorCompletionService.html). – beatngu13 Aug 11 '16 at 10:12
  • @beatngu13 Ooo, fancy. I'll add a blurb but feel free to edit it too. – yoshi Aug 11 '16 at 17:09