dmsc/java/jvm.rs
1//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
2//!
3//! This file is part of DMSC.
4//! The DMSC project belongs to the Dunimd Team.
5//!
6//! Licensed under the Apache License, Version 2.0 (the "License");
7//! You may not use this file except in compliance with the License.
8//! You may obtain a copy of the License at
9//!
10//! http://www.apache.org/licenses/LICENSE-2.0
11//!
12//! Unless required by applicable law or agreed to in writing, software
13//! distributed under the License is distributed on an "AS IS" BASIS,
14//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15//! See the License for the specific language governing permissions and
16//! limitations under the License.
17
18//! # JVM Lifecycle Management
19//!
20//! Provides utilities for managing the Java Virtual Machine lifecycle
21//! and obtaining JNI environment pointers.
22
23use jni::JNIEnv;
24use jni::JavaVM;
25use jni::AttachGuard;
26use std::sync::{Arc, OnceLock};
27
28static JVM_INSTANCE: OnceLock<Arc<JavaVM>> = OnceLock::new();
29
30/// DMSC Java context for managing JVM interactions
31pub struct DMSCJavaContext {
32 jvm: Arc<JavaVM>,
33}
34
35impl DMSCJavaContext {
36 /// Initialize the Java context from an existing JNIEnv
37 pub fn init(env: JNIEnv) -> Self {
38 let jvm = env.get_java_vm().expect("Failed to get JavaVM");
39 let jvm_arc = Arc::new(jvm);
40 let _ = JVM_INSTANCE.set(jvm_arc.clone());
41 Self { jvm: jvm_arc }
42 }
43
44 /// Get the current JNIEnv
45 pub fn get_env(&self) -> AttachGuard<'_> {
46 self.jvm
47 .attach_current_thread()
48 .expect("Failed to attach current thread to JVM")
49 }
50
51 /// Get the global JVM instance
52 pub fn get_jvm() -> Option<Arc<JavaVM>> {
53 JVM_INSTANCE.get().cloned()
54 }
55}
56
57/// Get the current JNIEnv from the global JVM instance
58pub fn get_env() -> Option<AttachGuard<'static>> {
59 JVM_INSTANCE.get().and_then(|jvm| {
60 jvm.attach_current_thread().ok()
61 })
62}