From fd109358a15d90f5fbdf9bd3a1547a8be8386704 Mon Sep 17 00:00:00 2001 From: Luke Howard Date: Fri, 8 Nov 2024 10:53:04 +1100 Subject: [PATCH] JavaKit: always use ambient javaEnvironment on Android This is not a real fix, I suspect the real fix is to remove javaEnvironment as an instance variable on all platforms and always use the ambient environment (as the JNI specification clearly states the environment cannot be shared between threads). Works around: #157 --- Sources/JavaKit/JavaObjectHolder.swift | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Sources/JavaKit/JavaObjectHolder.swift b/Sources/JavaKit/JavaObjectHolder.swift index 173991c9..75adbfed 100644 --- a/Sources/JavaKit/JavaObjectHolder.swift +++ b/Sources/JavaKit/JavaObjectHolder.swift @@ -19,13 +19,21 @@ import JavaRuntime /// while this instance is live. public class JavaObjectHolder { public private(set) var object: jobject? +#if canImport(Android) + public var environment: JNIEnvironment { + try! JavaVirtualMachine.shared().environment() + } +#else public let environment: JNIEnvironment +#endif /// Take a reference to a Java object and promote it to a global reference /// so that the Java virtual machine will not garbage-collect it. public init(object: jobject, environment: JNIEnvironment) { self.object = environment.interface.NewGlobalRef(environment, object) +#if !canImport(Android) self.environment = environment +#endif } /// Forget this Java object, meaning that it is no longer used from anywhere