0

Here is the bean

@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());
    } 
}

Another bean calls it:

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

customThreadPool.submit or just listOfThings.parallelStream() causes java.io.FileNotFoundException at readResource It can't find file!

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)

but stream (no concurrency)

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

works...

Un-reproducible in unit-tests, reproducible when application is started as jar.

How can I overcome it?

Capacytron
  • 3,425
  • 6
  • 47
  • 80
  • I assume it's thread save, since you're performing read-only operations. I've checked this code and got no exceptions. I think, you need to check whether this file is in classpath of jar. – geobreze Aug 01 '21 at 20:53
  • 1
    You may be suffering from contextClassLoader. There is an example; https://stackoverflow.com/questions/49110537/parallel-stream-doesnt-set-thread-contextclassloader-after-tomcat-upgrade – Kemal Kaplan Aug 01 '21 at 21:10

0 Answers0