0
votes

I am getting started on the executor service and i was wondering how i would call a function when a task is done.I have seen this function http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html#isDone--

but i am not sure how i would wire it to call the function endoftheroad() in my code

This is my code

//import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//import java.util.concurrent.Future;
//import java.util.concurrent.TimeUnit;
import java.util.*;

public class Pooler {

        public static int add(int x, int y){
        int c = x + y;
        return c;
        }
        public static int endoftheroad(){
        int the_end = 0;
        return the_end;
        }

    public static void main(String args[]) {
       ExecutorService service = Executors.newFixedThreadPool(10);
       for (int i =0; i<100; i++){
       Random randomno = new Random();
       int value = randomno.nextInt();
       service.submit(new Task(add(value,value)));
       }
    }

}


final class Task implements Runnable{
    private int taskId;

    public Task(int id){
        this.taskId = id;
    }

    @Override
    public void run() {
        System.out.println("Task ID : " + this.taskId +" performed by " 
                           + Thread.currentThread().getName());
    }

}
3

3 Answers

0
votes

You have a problem in your cost that

a) the add is performed in the current thread. Nothing, except the print out is performed in the executors thread.

b) the end of the road function doesn't do anything, so it doesn't matter if it is called or not.

c) You ignore the Future returned making using it difficult.

To answer your question, you can use a CompleableFuture in Java 8. However a much simpler solution is;

  • move all the code in the loop inside the run().
  • call the function to run after this code at the end of the run() method.
0
votes

It's very simple, your current task submits a new task to the executor once it is done:

public void run() {
  doSomeStuff();
  executor.submit(new FinishHimTask());
}

However you should keep in mind that if the submitted task is a very small one, it might be much more performant to just execute it in the current thread, as creating and adding a new task to the Executor takes some time as well.

0
votes

Take a look at ListenableFuture in Google's guava library if your code needs to run under Java 7. The ListenableFuture classes provide exactly what you need if using guava is an option for you. There is a tutorial at https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained.

If you have Java 8, CompletableFuture from the JDK is another option.