Search code examples
javacallable

I need not wait until executing async method call()


I need to do some async method. And not wait until it executing. I try with Future but it not help.

Future<Boolean> future = executorService.submit(new MyCallable());
LOGGER.info("onFailedLogonLimitAttempt: before");
                        if (future.get().booleanValue()) {
                          // some code here
                        }
                        LOGGER.info("onFailedLogonLimitAttempt: after");

public class MyCallable implements Callable<Boolean> {

        // The call() method is called in order to execute the asynchronous task.
        @Override
        public Boolean call() throws Exception {
            try {
                LOGGER.info("MyCallable: start");
                Thread.sleep(10000L);
                LOGGER.info("MyCallable: alarm_cleanup_stop 10 seconds");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return true;
        }
    }

But here logs:

2022-03-24 17:28:55.436 INFO  [SomeClass:http-nio-172.19.5.163-8091-exec-10] onFailedLogonLimitAttempt: before
2022-03-24 17:28:55.436 INFO  [SomeClass:pool-24-thread-1] MyCallable: start
...
...
...
2022-03-24 17:29:05.437 INFO  [SomeClass:pool-24-thread-1] MyCallable: alarm_cleanup_stop 10 seconds
2022-03-24 17:29:05.441 INFO  [SomeClass:http-nio-172.19.5.163-8091-exec-10] onFailedLogonLimitAttempt: after

As you can see the log print "onFailedLogonLimitAttempt: after" is call AFTER 10 seconds. But I need log to print imedaitly after "onFailedLogonLimitAttempt: before". To not wait unit async method call is finish.


Solution

  • The main thread is blocked on the call to future.get() until the task completes. Remove this call and your second log statement will print immediately.

    That addresses what you asked exactly. But I doubt it is what you want.

    The purpose of submitting an asynchronous task is to permit the main thread to carry on immediately with other work. If the main thread requires the result of the task to proceed, the task is not a candidate for performing asynchronously.

    Instead, add the processing of the result to the asynchronous task itself. Then the main thread does not have to wait for the result.