Skip to content

Commit b8f04aa

Browse files
authored
Android: Module implements Closeable (#19124)
Add Closeable interface so Module can be used with try-with-resources. close() delegates to destroy(). Also make destroy() idempotent by checking mHybridData.isValid() before calling resetNative(), satisfying the Closeable contract. This commit was authored with the help of Claude.
1 parent e1cd352 commit b8f04aa

1 file changed

Lines changed: 10 additions & 2 deletions

File tree

  • extension/android/executorch_android/src/main/java/org/pytorch/executorch

extension/android/executorch_android/src/main/java/org/pytorch/executorch/Module.java

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import com.facebook.jni.annotations.DoNotStrip;
1313
import com.facebook.soloader.nativeloader.NativeLoader;
1414
import com.facebook.soloader.nativeloader.SystemDelegate;
15+
import java.io.Closeable;
1516
import java.util.HashMap;
1617
import java.util.Map;
1718
import java.util.concurrent.locks.Lock;
@@ -24,7 +25,7 @@
2425
* <p>Warning: These APIs are experimental and subject to change without notice
2526
*/
2627
@Experimental
27-
public class Module {
28+
public class Module implements Closeable {
2829

2930
static {
3031
if (!NativeLoader.isInitialized()) {
@@ -274,12 +275,19 @@ public boolean etdump() {
274275
public void destroy() {
275276
if (mLock.tryLock()) {
276277
try {
277-
mHybridData.resetNative();
278+
if (mHybridData.isValid()) {
279+
mHybridData.resetNative();
280+
}
278281
} finally {
279282
mLock.unlock();
280283
}
281284
} else {
282285
throw new IllegalStateException("Cannot destroy module while method is executing");
283286
}
284287
}
288+
289+
@Override
290+
public void close() {
291+
destroy();
292+
}
285293
}

0 commit comments

Comments
 (0)