This is an automated email from the ASF dual-hosted git repository.

Xuanwo pushed a commit to branch 
xuanwo/fix-java-output-stream-leak-and-jni-local-refs
in repository https://gitbox.apache.org/repos/asf/opendal.git

commit 4fff6277bd7b2c682c9c88318525ab103d3669a4
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 23 10:37:13 2026 +0100

    fix(bindings/java): release native writer and JNI local refs
    
    OperatorOutputStream.close() ran flush() then writer.close() without
    ensuring the writer was released when flush() failed. A failed flush
    leaked the native blocking::Writer and left the stream usable, so later
    writes kept going into a broken writer. Always close the writer, and when
    both flush() and close() fail, attach the secondary close error as
    suppressed so the original flush error is preserved.
    
    The JNI list conversions accumulated local references: jni 0.22 JObject
    values do not delete local references on drop, so each listed entry pinned
    a dozen or more references for the whole native call. Scope the per-entry
    allocations with Env::with_local_frame in intern_list, make_entries,
    jmap_to_hashmap and hashmap_to_jmap.
---
 bindings/java/src/async_operator.rs                | 10 +++-
 bindings/java/src/convert.rs                       | 38 ++++++++----
 .../org/apache/opendal/OperatorOutputStream.java   | 31 +++++++++-
 bindings/java/src/operator.rs                      | 10 +++-
 .../org/apache/opendal/test/JniLocalRefTest.java   | 70 ++++++++++++++++++++++
 .../test/OperatorInputOutputStreamTest.java        | 30 ++++++++++
 6 files changed, 174 insertions(+), 15 deletions(-)

diff --git a/bindings/java/src/async_operator.rs 
b/bindings/java/src/async_operator.rs
index 68b9c568b6..59268faa5d 100644
--- a/bindings/java/src/async_operator.rs
+++ b/bindings/java/src/async_operator.rs
@@ -518,8 +518,14 @@ fn make_entries<'local>(env: &mut Env<'local>, entries: 
Vec<Entry>) -> Result<JO
     )?;
 
     for (idx, entry) in entries.into_iter().enumerate() {
-        let entry = make_entry(env, entry)?;
-        jarray.set_element(env, idx, &entry)?;
+        // `make_entry` creates a dozen or more local references. Release them 
at
+        // the end of each iteration so a large listing cannot exhaust the JNI
+        // local reference table.
+        env.with_local_frame(16, |env| -> Result<()> {
+            let entry = make_entry(env, entry)?;
+            jarray.set_element(env, idx, &entry)?;
+            Ok(())
+        })?;
     }
 
     Ok(jarray.into())
diff --git a/bindings/java/src/convert.rs b/bindings/java/src/convert.rs
index 0649b3f610..a0f04c990f 100644
--- a/bindings/java/src/convert.rs
+++ b/bindings/java/src/convert.rs
@@ -39,13 +39,25 @@ pub(crate) fn jmap_to_hashmap(env: &mut Env, params: 
&JObject) -> Result<HashMap
     let mut iter = map.iter(env)?;
 
     let mut result: HashMap<String, String> = HashMap::new();
-    while let Some(entry) = iter.next(env)? {
-        let k = entry.key(env)?;
-        let v = entry.value(env)?;
-        // SAFETY: a `java.util.Map<String, String>` only yields String keys 
and values.
-        let k = unsafe { JString::from_raw(env, k.into_raw()) };
-        let v = unsafe { JString::from_raw(env, v.into_raw()) };
-        result.insert(k.mutf8_chars(env)?.into(), v.mutf8_chars(env)?.into());
+    loop {
+        // Each iteration creates several local references. Release them per
+        // iteration so a large map does not exhaust the JNI local reference
+        // table.
+        let has_next = env.with_local_frame(8, |env| -> Result<bool> {
+            let Some(entry) = iter.next(env)? else {
+                return Ok(false);
+            };
+            let k = entry.key(env)?;
+            let v = entry.value(env)?;
+            // SAFETY: a `java.util.Map<String, String>` only yields String 
keys and values.
+            let k = unsafe { JString::from_raw(env, k.into_raw()) };
+            let v = unsafe { JString::from_raw(env, v.into_raw()) };
+            result.insert(k.mutf8_chars(env)?.into(), 
v.mutf8_chars(env)?.into());
+            Ok(true)
+        })?;
+        if !has_next {
+            break;
+        }
     }
 
     Ok(result)
@@ -58,9 +70,15 @@ pub(crate) fn hashmap_to_jmap<'a, K: AsRef<str>, V: 
AsRef<str>>(
     let map_object = env.new_object(jni_str!("java/util/HashMap"), 
jni_sig!("()V"), &[])?;
     let jmap = env.new_cast_local_ref::<JMap>(&map_object)?;
     for (k, v) in map {
-        let key = env.new_string(k.as_ref())?;
-        let value = env.new_string(v.as_ref())?;
-        jmap.put(env, &key, &value)?;
+        // The key and value strings are only needed until `put` returns. Scope
+        // them per entry so a large map does not exhaust the JNI local
+        // reference table.
+        env.with_local_frame(4, |env| -> Result<()> {
+            let key = env.new_string(k.as_ref())?;
+            let value = env.new_string(v.as_ref())?;
+            jmap.put(env, &key, &value)?;
+            Ok(())
+        })?;
     }
     Ok(map_object)
 }
diff --git 
a/bindings/java/src/main/java/org/apache/opendal/OperatorOutputStream.java 
b/bindings/java/src/main/java/org/apache/opendal/OperatorOutputStream.java
index 20afd04172..141222e5a2 100644
--- a/bindings/java/src/main/java/org/apache/opendal/OperatorOutputStream.java
+++ b/bindings/java/src/main/java/org/apache/opendal/OperatorOutputStream.java
@@ -112,10 +112,39 @@ public class OperatorOutputStream extends OutputStream {
 
     @Override
     public synchronized void close() {
-        if (!writer.isDisposed()) {
+        if (writer.isDisposed()) {
+            return;
+        }
+        Throwable primary = null;
+        try {
             flush();
+        } catch (Throwable t) {
+            primary = t;
+        }
+        // Always release the native writer, even when `flush()` failed. 
Otherwise
+        // the native handle leaks and the stream keeps accepting writes.
+        try {
             writer.close();
+        } catch (Throwable secondary) {
+            if (primary != null) {
+                primary.addSuppressed(secondary);
+            } else {
+                primary = secondary;
+            }
+        }
+        if (primary != null) {
+            rethrow(primary);
+        }
+    }
+
+    private static void rethrow(Throwable t) {
+        if (t instanceof RuntimeException) {
+            throw (RuntimeException) t;
+        }
+        if (t instanceof Error) {
+            throw (Error) t;
         }
+        throw new RuntimeException(t);
     }
 
     private void ensureOpen() {
diff --git a/bindings/java/src/operator.rs b/bindings/java/src/operator.rs
index 8cc47c20b4..e28c799e0e 100644
--- a/bindings/java/src/operator.rs
+++ b/bindings/java/src/operator.rs
@@ -335,8 +335,14 @@ fn intern_list<'local>(
     )?;
 
     for (idx, entry) in entries.into_iter().enumerate() {
-        let entry = make_entry(env, entry)?;
-        jarray.set_element(env, idx, &entry)?;
+        // `make_entry` creates a dozen or more local references. Release them 
at
+        // the end of each iteration so a large listing cannot exhaust the JNI
+        // local reference table.
+        env.with_local_frame(16, |env| -> Result<()> {
+            let entry = make_entry(env, entry)?;
+            jarray.set_element(env, idx, &entry)?;
+            Ok(())
+        })?;
     }
 
     Ok(jarray)
diff --git 
a/bindings/java/src/test/java/org/apache/opendal/test/JniLocalRefTest.java 
b/bindings/java/src/test/java/org/apache/opendal/test/JniLocalRefTest.java
new file mode 100644
index 0000000000..ebd5a93528
--- /dev/null
+++ b/bindings/java/src/test/java/org/apache/opendal/test/JniLocalRefTest.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.opendal.test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import java.util.HashMap;
+import java.util.Map;
+import org.apache.opendal.AsyncOperator;
+import org.apache.opendal.Operator;
+import org.apache.opendal.ServiceConfig;
+import org.apache.opendal.WriteOptions;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Regression tests for JNI local reference accumulation: listing a directory 
with many entries
+ * must not pin one local reference per entry for the whole native call. Run 
the tests with
+ * {@code -Xcheck:jni} to surface a local reference table overflow.
+ */
+public class JniLocalRefTest {
+    private static final int ENTRY_COUNT = 250;
+    private static final int USER_METADATA_COUNT = 5;
+
+    private static WriteOptions writeOptionsWithUserMetadata() {
+        final Map<String, String> userMetadata = new HashMap<>();
+        for (int i = 0; i < USER_METADATA_COUNT; i++) {
+            userMetadata.put("key-" + i, "value-" + i);
+        }
+        return WriteOptions.builder().userMetadata(userMetadata).build();
+    }
+
+    @Test
+    void testBlockingListReleasesLocalReferences() {
+        final WriteOptions options = writeOptionsWithUserMetadata();
+        try (final Operator op = 
Operator.of(ServiceConfig.Memory.builder().build())) {
+            for (int i = 0; i < ENTRY_COUNT; i++) {
+                op.write("blocking/file-" + i, "x", options);
+            }
+            assertThat(op.list("blocking/")).hasSize(ENTRY_COUNT);
+        }
+    }
+
+    @Test
+    void testAsyncListReleasesLocalReferences() {
+        final WriteOptions options = writeOptionsWithUserMetadata();
+        try (final AsyncOperator op =
+                AsyncOperator.of(ServiceConfig.Memory.builder().build())) {
+            for (int i = 0; i < ENTRY_COUNT; i++) {
+                op.write("async/file-" + i, "x", options).join();
+            }
+            assertThat(op.list("async/").join()).hasSize(ENTRY_COUNT);
+        }
+    }
+}
diff --git 
a/bindings/java/src/test/java/org/apache/opendal/test/OperatorInputOutputStreamTest.java
 
b/bindings/java/src/test/java/org/apache/opendal/test/OperatorInputOutputStreamTest.java
index 7d89ee399a..57e5a1825f 100644
--- 
a/bindings/java/src/test/java/org/apache/opendal/test/OperatorInputOutputStreamTest.java
+++ 
b/bindings/java/src/test/java/org/apache/opendal/test/OperatorInputOutputStreamTest.java
@@ -30,6 +30,7 @@ import java.util.Random;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.stream.Stream;
 import org.apache.commons.io.IOUtils;
+import org.apache.opendal.AsyncOperator;
 import org.apache.opendal.OpenDALException;
 import org.apache.opendal.Operator;
 import org.apache.opendal.OperatorInputStream;
@@ -39,6 +40,7 @@ import org.apache.opendal.ReadOptions;
 import org.apache.opendal.ReaderOptions;
 import org.apache.opendal.ServiceConfig;
 import org.apache.opendal.WriteOptions;
+import org.apache.opendal.layer.ThrottleLayer;
 import org.apache.opendal.test.condition.OpenDALExceptionCondition;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.io.TempDir;
@@ -269,6 +271,34 @@ public class OperatorInputOutputStreamTest {
         }
     }
 
+    @Test
+    void testOutputStreamCloseReleasesWriterWhenFlushFails() throws Exception {
+        try (final AsyncOperator op =
+                AsyncOperator.of(ServiceConfig.Memory.builder().build())) {
+            try (final AsyncOperator throttled = op.layer(new 
ThrottleLayer(1024, 4))) {
+                final Operator layeredOp = throttled.blocking();
+                try {
+                    final OperatorOutputStream out = 
layeredOp.createOutputStream("close-flush-failure");
+                    // The 8 buffered bytes exceed the throttle burst of 4, so 
the flush
+                    // performed by close() fails with RateLimited.
+                    out.write(new byte[8]);
+
+                    assertThatThrownBy(out::close)
+                            
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.RateLimited));
+
+                    // The native writer must be released even though flush() 
failed.
+                    assertThatThrownBy(() -> 
out.write(1)).isInstanceOf(IllegalStateException.class);
+
+                    // Closing again is safe and does not touch the released 
writer.
+                    out.close();
+                    out.close();
+                } finally {
+                    layeredOp.close();
+                }
+            }
+        }
+    }
+
     @ParameterizedTest
     @ValueSource(ints = {0, -1})
     void testInvalidOutputBufferSize(int bufferSize) {

Reply via email to