[gdal-dev] Java bindings to gdal/ogr - looking for more developer documentation

Tom Moore tmoore at spatial.ca
Fri May 30 14:39:55 PDT 2025


Hi Even

I just wanted to update you and provide a record for posterity with the results of me playing around with gdal/java and resource management.

It appears to me that Dataset objects should not be closed from Java client code.  If you do then often there will be an access violation (native null pointer) that will crash the JVM.  From the dump file the following stack trace shows the Java code being executed when the exception occurs:

Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j  org.gdal.gdal.gdalJNI.delete_Dataset(J)V+0
j  org.gdal.gdal.Dataset.delete()V+25
j  org.gdal.gdal.Dataset.finalize()V+1
j  java.lang.System$2.invokeFinalize(Ljava/lang/Object;)V+1 java.base at 21.0.6
j  java.lang.ref.Finalizer.runFinalizer(Ljdk/internal/access/JavaLangAccess;)V+115 java.base at 21.0.6
j  java.lang.ref.Finalizer$FinalizerThread.run()V+29 java.base at 21.0.6

So it looks like the swig bindings implement a finalizer to dispose of the native object when the reference is no longer reachable (nice!).  However it looks like there might not be any protection to prevent bad things from happening when the Delete method is called more than once.  It appears that in this case that when the finalizer calls Delete on the Dataset the jvm crashes because the Dataset has already been closed manually and the resources have already been released.

If I am correct in this conclusions then this is not a problem.  If correct I suggest that either the docs be updated to indicate do not manually call Delete on the Dataset object, or change the Delete method code to gracefully handle multiple calls (better choice).

By the way, something to note for the future is that finalizers have been deprecated since Java 9 (2017).  This is described in https://openjdk.org/jeps/421.  Although deprecated, finalizers are still allowed in modern jdk's and probably will be for a while yet. At some future time they will be removed.  The suggested replacement for finalizers are cleaners, but they are only available in Java 9+.  When finalizers are removed there will need to be a new set of bindings that use cleaners.  You can probably ignore this problem for a few more years, but at some point you will need to provide two sets of Java bindings (one required for Java 8 and earlier, and one required for some future Java and later).

Cheers,
Tom


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/gdal-dev/attachments/20250530/d01ca434/attachment.htm>


More information about the gdal-dev mailing list