Can I risk leaking a JDBC connection when streaming JOOQ results outside of a try-with-resources block?

I have a JOOQ request in which I want to avoid materializing all records at once. (However, I am fine with the joint materialization of all bean objects created from them.)

I have the following easy way to load data:

public List<CustomerInfo> getCustomers() { return dslContext .selectFrom(CUSTOMER) // <-- note the missing .fetch() .stream() .map(CustomerInfo::new) .collect(Collectors.toList()); } 

Could this lead to a JDBC connection leak under any circumstances? (e.g. exception in CustomerInfo::new )

+6
source share
1 answer

I tried my luck to find a way to register a reliable thread "termination", which is triggered at full flow rate or in any exception, but this is not possible, unfortunately: Register Stream "completion" hook

So, really, the code you showed is incorrect. The right way to work with lazy threads (or Cursor ) is to use the try-with-resources statement. The following two equivalents:

 // Using a Stream try (Stream<CustomerRecord> stream = dslContext.selectFrom(CUSTOMER).stream()) { return stream.map(CustomerInfo::new).collect(Collectors.toList()); } // Using a Cursor try (Cursor<CustomerRecord> cursor = dslContext.selectFrom(CUSTOMER).fetchLazy()) { return cursor.stream().map(CustomerInfo::new).collect(Collectors.toList()); } 

Also note the ResultQuery.stream() javadoc:

This is essentially the same as fetchLazy (), but instead of returning a cursor, a Java 8 stream is returned. Clients must ensure that the stream closes correctly. in a try-with-resources statement

+4
source

All Articles