I checked my java code and coverity analysis found this resource leak error.
@Before
public void init() {
(1) Event alloc_fn: A new resource is returned from allocation method "deleteFrom". (The virtual call resolves to "org.jooq.impl.DefaultDSLContext.deleteFrom".)
(2) Event leaked_resource: Failing to save or close resource created by "dslContext.deleteFrom(com.nurego.bizops.metering.common.jooq.nongen.tables.MyTable.MYTABLE)" leaks it.
dslContext.deleteFrom(MyTable.MYTABLE).execute();
}
dslContext.close()
is already used in predestroy method.
Should I do smth like this?
DeleteUsingStep<MyTableRecord> step = dslContext.deleteFrom(MyTable.MYTABLE);
step.execute();
step.close();
Or is there a better solution?
There was a subtle change in contract between Java 7 and 8 regarding AutoCloseable
, see the Javadoc:
A resource that must be closed when it is no longer needed.
Note the word "must".
An object that may hold resources (such as file or socket handles) until it is closed. The close() method of an AutoCloseable object is called automatically when exiting a try-with-resources block for which the object has been declared in the resource specification header. This construction ensures prompt release, avoiding resource exhaustion exceptions and errors that may otherwise occur.
API Note:
It is possible, and in fact common, for a base class to implement AutoCloseable even though not all of its subclasses or instances will hold releasable resources. For code that must operate in complete generality, or when it is known that the AutoCloseable instance requires resource release, it is recommended to use try-with-resources constructions. However, when using facilities such as Stream that support both I/O-based and non-I/O-based forms, try-with-resources blocks are in general unnecessary when using non-I/O-based forms.
This was done (probably) to allow for Stream
to extend AutoCloseable
for convenience of using streams with try-with-resources
, despite the fact that almost all streams are not resourceful.
Unfortunately, this makes most static analysis tools useless when it comes to auto closeable detection. They might have hard-coded an exception for streams, but not for DSLContext
.
You can safely ignore these errors when using jOOQ's DSLContext
.
This has been a frequent issue for new jOOQ users, and could be considered an API design flaw. jOOQ 3.14 will remove the AutoCloseable
type from the DSLContext
super types and provide a dedicated CloseableDSLContext
instead, which is returned only from relevant methods:
https://github.com/jOOQ/jOOQ/issues/10512