1 // Copyright 2022, The Android Open Source Project 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 //! takes a JavaVM to a static reference. 16 //! 17 //! JavaVM is shared as multiple JavaVM within a single process is not allowed 18 //! per [JNI spec](https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/invocation.html) 19 //! The unique JavaVM need to be shared over (potentially) different threads. 20 21 use jni::JavaVM; 22 use std::sync::Once; 23 24 static mut JVM: Option<JavaVM> = None; 25 static INIT: Once = Once::new(); 26 /// set_once sets the unique JavaVM that can be then accessed using get_static_ref() 27 /// 28 /// The function shall only be called once. set_once(jvm: JavaVM)29pub(crate) fn set_once(jvm: JavaVM) { 30 // Safety: follows [this pattern](https://doc.rust-lang.org/std/sync/struct.Once.html). 31 // Modification to static mut is nested inside call_once. 32 unsafe { 33 INIT.call_once(|| { 34 JVM = Some(jvm); 35 }); 36 } 37 } 38 /// Gets a 'static reference to the unique JavaVM. Returns None if set_once() was never called. get_static_ref() -> Option<&'static JavaVM>39pub(crate) fn get_static_ref() -> Option<&'static JavaVM> { 40 // Safety: follows [this pattern](https://doc.rust-lang.org/std/sync/struct.Once.html). 41 // Modification to static mut is nested inside call_once. 42 unsafe { JVM.as_ref() } 43 } 44