Search code examples
javaspringspring-annotations

@Async with outstream and thread.sleep method


A simple question on @Async annotation.

For example: A method is @Async annotated and it contains thread.sleep for few seconds. And after the sleep, their is a outStream.println. Then what is the result.

I have used ThreadPoolTaskExecutor as executor

I just want to know as i have tried above with a sleep of 5 seconds, but getting outStream.println in fraction of second. So I just want to understand if this is how Async annotation works i.e., if it has given the instant response and thread.sleep is executed by other thread.


Solution

  • Assuming your method is like this

    @Async
    public void foo() {
        sleep(5000L);
        System.out.println("hello world");
    }
    

    This won't tell you anything as the 5sec wait is in another thread anyway. However if you have something like this

    public void bar() {
        myService.foo();
        System.out.println("hello world");
    }
    

    Then if you get Hello World in "a fraction of second", it means that the invocation of foo has been indeed done asynchronously.

    When you invoke a method with @Async the method invocation is wrapped in a Callable and that instance is passed to the executor service using the submit method.

    If the executor cannot process the method execution, you'll get a TaskRejectedException. For instance, if your ThreadPoolTaskExecutor has a pool size of 2 threads and a queue size of 0, the third invocation of the foo method will fail with a TaskRejectedException if the pool threads are still busy processing the two first invocations.