Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return future object from callable interface (internal working of executorService.submit)

I am trying to understand how future object is created when running the executorService.submit(Callable);

For example lets say I create a thread pool in which I pass my implementation of callable

class FactorialCalculator implements Callable<Long> { 
  private int number; 
  public FactorialCalculator(int number) { 
    this.number = number; 
  } 
  @Override 
  public Long call() throws Exception { 
        return (number*number); 
  }
}

I want to return the future object so I can get the return value from call function. My custom thread pool looks like this

class MyThreadPool implements java.util.concurrent.Executor 
{
    private final java.util.concurrent.BlockingQueue<Callable> queue;

    public MyThreadPool(int numThreads) {
        queue = new java.util.concurrent.LinkedBlockingQueue<>();
        for (int i=0 ; i<numThreads ; i++) {
            new Thread(new Runnable(){
                @Override
                public void run() {
                    while(true) {
                        queue.take().call();
                    }
                }
            }).start();
        }
    }

    @Override
    public void submit(Callable command) {
        queue.put(command);
    }
}

Now if I do

MyThreadPool mypool = new MyThreadPool(10);
mypool.submit(new FactorialCalculator(10));

I want to submit method to return future so I can check the return value if the thread has finished execution. How do I return future object.

like image 477
krs8888 Avatar asked Sep 06 '25 18:09

krs8888


1 Answers

The simplest way would be to wrap your callable in a FutureTask:

@Override
public <T> Future<T> submit(Callable<T> callable) {
    FutureTask<T> future = new FutureTask(callable);
    queue.put(future);
    return future;
}

Of course, the even easier solution would be to use Executors.newFixedThreadPool instead of reimplementing it on your own.

like image 135
Andrew Rueckert Avatar answered Sep 10 '25 09:09

Andrew Rueckert