Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CompletableFuture VS @Async

I am not good at English.

I use asynchronous methods.

Option 1

public CompletableFuture<Integer> getDiscountPriceAsync(Integer price) {
        return CompletableFuture.supplyAsync(() -> {
            log.info("supplyAsync");
            return (int)(price * 0.9);
        }, threadPoolTaskExecutor);
    }

Option 2

@Async
public CompletableFuture<Integer> getDiscountPriceAsync(Integer price) {
        return CompletableFuture.supplyAsync(() -> {
            log.info("supplyAsync");
            return (int)(price * 0.9);
        }, threadPoolTaskExecutor);
    }

I wonder what the difference is between using @Async and not using it.

I think the first Option1 provides enough asynchronous methods.
However, is it correct to use it like Option2?

like image 990
Eddy Kim Avatar asked Sep 01 '26 11:09

Eddy Kim


1 Answers

Option 2 is asynchronous done twice.

If you annotated a method withe @Async it will be executed by Spring asynchronously. So you don't need to use the ThreadPoolExecutor by yourself.

Instead you could write:

@Async
public CompletableFuture<Integer> getDiscountPriceAsync(Integer price) {
    log.info("supplyAsync");

    return new AsyncResult<Integer>((int)(price * 0.9)); 
}

Read more about Async with Spring here: https://www.baeldung.com/spring-async

like image 195
Simon Martinelli Avatar answered Sep 03 '26 00:09

Simon Martinelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!