< prev index next >

src/java.base/share/classes/java/util/zip/ZStreamRef.java

Print this page

        

@@ -23,24 +23,44 @@
  * questions.
  */
 
 package java.util.zip;
 
+import java.util.function.LongConsumer;
+import java.util.function.LongSupplier;
+import java.lang.ref.Cleaner.Cleanable;
+import jdk.internal.ref.CleanerFactory;
+
 /**
- * A reference to the native zlib's z_stream structure.
+ * A reference to the native zlib's z_stream structure. It also
+ * serves as the "cleaner" to clean up the native resource when
+ * the deflater or infalter is ended, closed or cleaned.
  */
+class ZStreamRef implements Runnable {
 
-class ZStreamRef {
-
-    private volatile long address;
-    ZStreamRef (long address) {
-        this.address = address;
+    private LongConsumer end;
+    private long address;
+    private final Cleanable cleanable;
+
+    ZStreamRef (Object owner, LongSupplier addr, LongConsumer end) {
+        this.cleanable = CleanerFactory.cleaner().register(owner, this);
+        this.end = end;
+        this.address = addr.getAsLong();
     }
 
     long address() {
+        assert Thread.holdsLock(this);
         return address;
     }
 
-    void clear() {
+    void clean() {
+        cleanable.clean();
+    }
+
+    public synchronized void run() {
+        long addr = address;
         address = 0;
+        if (addr != 0) {
+            end.accept(addr);
+        }
     }
 }
< prev index next >