Use java.lang.ref.Cleaner instead of Object.finalize() in Java 9 branch

This commit is contained in:
Reinhard Pointner 2017-10-31 18:07:10 +01:00
parent b3ed2c6138
commit 0098840976

View File

@ -9,6 +9,7 @@ import java.io.Closeable;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.RandomAccessFile; import java.io.RandomAccessFile;
import java.lang.ref.Cleaner;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.EnumMap; import java.util.EnumMap;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@ -23,10 +24,12 @@ import com.sun.jna.WString;
public class MediaInfo implements Closeable { public class MediaInfo implements Closeable {
private Pointer handle; private Pointer handle;
private Cleaner.Cleanable cleanable;
public MediaInfo() { public MediaInfo() {
try { try {
handle = MediaInfoLibrary.INSTANCE.New(); handle = MediaInfoLibrary.INSTANCE.New();
cleanable = cleaner.register(this, new Finalizer(handle));
} catch (LinkageError e) { } catch (LinkageError e) {
throw new MediaInfoException(e); throw new MediaInfoException(e);
} }
@ -171,25 +174,7 @@ public class MediaInfo implements Closeable {
@Override @Override
public synchronized void close() { public synchronized void close() {
MediaInfoLibrary.INSTANCE.Close(handle); cleanable.clean();
}
public synchronized void dispose() {
if (handle == null) {
return;
}
// delete handle
MediaInfoLibrary.INSTANCE.Delete(handle);
handle = null;
}
/**
* TODO: use {@link java.lang.ref.Cleaner} instead of Object.finalize() once Java 8 support is dropped
*/
@Override
protected void finalize() {
dispose();
} }
public enum StreamKind { public enum StreamKind {
@ -274,4 +259,24 @@ public class MediaInfo implements Closeable {
} }
} }
/**
* Use {@link Cleaner} instead of Object.finalize()
*/
private static final Cleaner cleaner = Cleaner.create();
private static class Finalizer implements Runnable {
private Pointer handle;
public Finalizer(Pointer handle) {
this.handle = handle;
}
@Override
public void run() {
MediaInfoLibrary.INSTANCE.Close(handle);
MediaInfoLibrary.INSTANCE.Delete(handle);
}
}
} }