SpringBoot 2.4.2 ResourceLoader 线程安全吗?

时间:2021-08-01 19:53:34

标签: java spring-boot java.util.concurrent

这是豆子

@Service
@RequiredArgsConstructor
public class BeanWithResourceLoader{
    private final ResourceLoader resourceLoader;

    @SneakyThrows
    private String readResource() {
        return IOUtils.toString(
          resourceLoader.getResource(
            "classpath:/some_resource.json").getInputStream(), 
            StandardCharsets.UTF_8.name());
    } 
}

另一个bean调用它:

        var result =
                customThreadPool.submit(
                () -> listOfThings.parallelStream().map(aThing ->beanWithResourceLoader.readResource())
   .collect(Collectors.toList()))
   .get();

customThreadPool.submit 或只是 listOfThings.parallelStream() 导致 java.io.FileNotFoundException 在 readResource 找不到文件!

Caused by: java.io.FileNotFoundException: class path resource [some_resource.json] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:180)

但是stream(无并发)

listOfThings.stream().map(aThing ->beanWithResourceLoader.readResource())
   .collect(Collectors.toList())

作品...

在单元测试中不可重现,当应用程序作为 jar 启动时可重现。

我该如何克服它?

0 个答案:

没有答案