I try to make an API aysnchronous as:
Future<Integer> fASync(int x) {
return new FutureTask(() -> {
try {
Thread.sleep(new Random().nextInt(1, 3) * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return x * x;
});
}
..then I try to use it:
Future<Integer> asyncCall = fASync(x);
asyncCall .get();
But this never completes and call just blocks.
Is this not correct way of making your API asynchronous?
You have declared a
FutureTaskbut haven't actually run it so a call toasyncCall.get()will block forever.Here is your example with extra logging and adding a step to execute the task in a new
ExecutorService.If you enable the
exec.execute(task);line it will print these messages and completetask.get(), instead of printing the first line only and no response fromtask.get():