How to use Future and Callable in my own thread pool implementation

764 views Asked by At

I am trying to implement my own thread pool in Java (for didactic purposes).

In my thread pool class, I have this method:

public Future submit (Task task) { //(Task implements Callable<String>)
    FutureTask<String> futureTask = new FutureTask<String>(task);
    taskQueue.put(task); //It is a BlockingQueue
    return futureTask;
}

I am wrapping my Task into a FutureTask, put it in a synchronized queue and immediately return the FutureTask.

When I am trying to add tasks to the pool, I do:

   Future<String> futureTask = threadPool.submit(new Task(/*arguments*/));
   //In theory, I could do something else here
   String taskRes = futureTask.get();

I use the above code with some threads, but futureTask.get() never returns.

My threads do something like this:

public void run() {
  Task task = taskQueue.take();
  task.call();
}

Is there something logically wrong on how I used Future and Callable?

I mean a Task is wrapped into a FutureTask in one thread, but it is called in another one. For some reasons futureTask.get() can not get the return value of task.call().

0

There are 0 answers