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