@Async基本使用

本文详细介绍了如何在Java中使用@Async注解进行方法异步执行,包括Future结果的获取、自定义Executor的配置、以及void返回类型下异常的处理策略。
摘要由CSDN通过智能技术生成

异步

  • 开注解@EnableAsync
  • 在要异步执行的方法上加@Async,必须返回void

获取结果

异步方法返回Future<>

public void testAsyncAnnotationForMethodsWithReturnType()
  throws InterruptedException, ExecutionException {
    Future<String> future = asyncAnnotationExample.asyncMethodWithReturnType();

    while (true) {
        if (future.isDone()) {
            System.out.println("Result from asynchronous process - " + future.get());
            break;
        }
        System.out.println("Continue doing something else. ");
        Thread.sleep(1000);
    }
}

@Service
public class AsyncServiceImpl implements AsyncService {
    @Async
    @Override
    public Future<Boolean> generateReport(String msg) throws InterruptedException {
        Thread.sleep(5000);
        System.out.println("异步任务执行完成" + msg);
        return new AsyncResult<>(true);
    }
}

自定义Executor

设置bean

@Bean
    public Executor asyncExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(2); //设置线程池的基本大小为2,即使线程池中的线程空闲,线程池也会保持至少有这么多的线程
        threadPoolTaskExecutor.setMaxPoolSize(2); //设置线程池的最大大小为2,这表示即使排队任务的数量增加,线程池也只能增加到这个数量的线程
        threadPoolTaskExecutor.setQueueCapacity(500); //设置线程池的队列容量为500。如果所有的线程都在忙,新来的任务会被放在队列里面,等待有线程空闲出来
        threadPoolTaskExecutor.initialize(); //初始化线程池
        return threadPoolTaskExecutor;
    }

注入使用

@Async("asyncExecutor")
public void asyncMethodWithConfiguredExecutor() {
    System.out.println("Execute method with configured executor - "
      + Thread.currentThread().getName());
}

全局默认Executor

@Configuration
public class AsyncConfiguration implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        //创建操作
    }
}

异常处理

当方法返回类型是Future时,异常处理很容易。*Future.get()*方法将抛出异常。

但如果返回类型为void,**异常将不会传播到调用线程。**因此,我们需要添加额外的配置来处理异常。

我们将通过实现AsyncUncaughtExceptionHandler接口来创建自定义异步异常处理程序。当存在任何未捕获的异步异常时,将调用handleUncaughtException ()方法

public class CustomAsyncExceptionHandler
  implements AsyncUncaughtExceptionHandler {

    @Override
    public void handleUncaughtException(
      Throwable throwable, Method method, Object... obj) {
 
        System.out.println("Exception message - " + throwable.getMessage());
        System.out.println("Method name - " + method.getName());
        for (Object param : obj) {
            System.out.println("Parameter value - " + param);
        }
    }   
}

将自定义处理程序设定为异常处理程序时,实现AsyncConfigurer接口中的下一个方法

@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
    return new CustomAsyncExceptionHandler();
}
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值