首页 > 解决方案 > Class的Spring clear属性值有@Async方法

问题描述

我尝试在 Spring Boot 2.4.4 中使用 @Async

process1我在类 AsyncService 中实现了一个异步方法。

AsyncService 的 Bean 在AsyncConfig类中定义(范围原型),随机数是传递给构造函数的参数。

AsyncService问题是,当我向类的构造函数注入两个实例时AsyncTest,它们没有为属性设置值AsyncService.prop111

//@Service
public class AsyncService {
    static final Logger logger = LoggerFactory.getLogger(AsyncService.class);
    public final long prop111;

    public AsyncService(long prop111) { this.prop111 = prop111; }

    @Async
    public CompletableFuture<String> process1(int param) throws InterruptedException {
        logger.info("start process1: [{} {}]", Thread.currentThread().getId(), Thread.currentThread().getName());
        Thread.sleep(3000L);
        return CompletableFuture.completedFuture("process1 result");
    }
}
@Service
@EnableAsync
public class AsyncConfig {
    @Bean("serviceAsync")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public AsyncService get() {
        return new AsyncService(ThreadLocalRandom.current().nextInt(100,200));
    }
}
@Service
public class AsyncTest {
    static final Logger logger = LoggerFactory.getLogger(AsyncTest.class);
    static AsyncService asyncService11;
    static AsyncService asyncService22;

    public AsyncTest(AsyncService asyncService11,
                     AsyncService asyncService22) {
        AsyncTest.asyncService11 = asyncService11;
        AsyncTest.asyncService22 = asyncService22;
        // it can not set prop1111
        logger.info("prop111 {} {} ", asyncService11.prop111, asyncService22.prop111);
    }

    public static void testAsync() throws InterruptedException, ExecutionException {
        // it print 0, 0. prop111 is not init.
        logger.info("prop111 {} {} ", asyncService11.prop111, asyncService22.prop111);

        List<CompletableFuture<String>> futureList = IntStream.range(0, 10)
            .mapToObj(asyncService11::process1)
            .collect(Collectors.toList());

        CompletableFuture<String>[] futureArray = futureList.toArray(new CompletableFuture[0]);
        futureList.toArray(futureArray);

        // waiting for all thread complete
        CompletableFuture.allOf(futureArray).join();

        logger.info("Elapsed time: ");
    }
}
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {
            AsyncTest.testAsync();
        };
    }

}

标签: javaspringspring-bootasynchronous

解决方案


推荐阅读