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 std::sync::{Arc, Once};
22 
23 use jni::JavaVM;
24 use uwb_core::error::Result;
25 
26 static mut JVM: Option<Arc<JavaVM>> = None;
27 static INIT: Once = Once::new();
28 /// Sets the unique JavaVM that can be then accessed using [`get_static_ref`].
29 ///
30 /// The function shall only be called once.
set_once(jvm: JavaVM) -> Result<()>31 pub(crate) fn set_once(jvm: JavaVM) -> Result<()> {
32     // Safety: follows [this pattern](https://doc.rust-lang.org/std/sync/struct.Once.html).
33     // Modification to static mut is nested inside call_once.
34     unsafe {
35         INIT.call_once(|| {
36             JVM = Some(Arc::new(jvm));
37         });
38     }
39     Ok(())
40 }
41 /// Gets a `'static` reference to the unique JavaVM. Returns `None` if [`set_once`] was never called.
get_static_ref() -> Option<&'static Arc<JavaVM>>42 pub(crate) fn get_static_ref() -> Option<&'static Arc<JavaVM>> {
43     // Safety: follows [this pattern](https://doc.rust-lang.org/std/sync/struct.Once.html).
44     // Modification to static mut is nested inside call_once.
45     unsafe { JVM.as_ref() }
46 }
47