Let's say I have a stream of objects loaded from a database (using Spring Data JPA as follow)
public interface MyJpaRepository extends JpaRepository<Foo, String> {
Stream<Foo> findAll();
}
And let's say there's millions of Foo objects stored in my database using way more GB than my max heap memory size.
I'm expecting consuming the stream as follow would let the JVM handle properly its heap memory by garbage collecting processed objects as more are loaded from the database:
try (Stream<Foo> fooStream =
myJpaRepository.findAll()) {
fooStream.forEach(entity -> logger.info("Hello !"));
}
But in facts, this exact code throws an out of memory exception.
- How does the garbage collector acts in this case ?
- How consuming this stream using a forEach requires the JVM to entirely load the data from the stream in memory (as per my understanding) ?
Thank you