From ee1906bf6d80f08262f4f1949150aa2588129b25 Mon Sep 17 00:00:00 2001 From: tison Date: Sun, 28 May 2023 16:41:53 +0800 Subject: [PATCH] refactor(bindings/java): narrow unsafe boundary Signed-off-by: tison --- bindings/java/src/lib.rs | 7 +++++++ bindings/java/src/operator.rs | 19 +++++++------------ 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/bindings/java/src/lib.rs b/bindings/java/src/lib.rs index 8a94719200bc..1a9d20634efa 100644 --- a/bindings/java/src/lib.rs +++ b/bindings/java/src/lib.rs @@ -83,6 +83,13 @@ unsafe fn get_current_env<'local>() -> JNIEnv<'local> { JNIEnv::from_raw(env).unwrap() } +/// # Safety +/// +/// This function could be only when the lib is loaded. +unsafe fn get_global_runtime<'local>() -> &'local Runtime { + RUNTIME.get_unchecked() +} + fn jmap_to_hashmap(env: &mut JNIEnv, params: &JObject) -> Result> { let map = JMap::from_env(env, params)?; let mut iter = map.iter(env)?; diff --git a/bindings/java/src/operator.rs b/bindings/java/src/operator.rs index 3beb845c35d4..07f2e92de23e 100644 --- a/bindings/java/src/operator.rs +++ b/bindings/java/src/operator.rs @@ -24,13 +24,13 @@ use jni::objects::JValueOwned; use jni::objects::{JByteArray, JClass}; use jni::sys::jlong; use jni::JNIEnv; + use opendal::Operator; use opendal::Scheme; -use crate::get_current_env; use crate::jmap_to_hashmap; use crate::Result; -use crate::RUNTIME; +use crate::{get_current_env, get_global_runtime}; #[no_mangle] pub extern "system" fn Java_org_apache_opendal_Operator_constructor( @@ -93,8 +93,7 @@ fn intern_write( let path = env.get_string(&path)?.to_str()?.to_string(); let content = env.convert_byte_array(content)?; - let runtime = unsafe { RUNTIME.get_unchecked() }; - runtime.spawn(async move { + unsafe { get_global_runtime() }.spawn(async move { let result = do_write(op, path, content).await; complete_future(id, result.map(|_| JValueOwned::Void)) }); @@ -135,8 +134,7 @@ fn intern_append( let path = env.get_string(&path)?.to_str()?.to_string(); let content = env.convert_byte_array(content)?; - let runtime = unsafe { RUNTIME.get_unchecked() }; - runtime.spawn(async move { + unsafe { get_global_runtime() }.spawn(async move { let result = do_append(op, path, content).await; complete_future(id, result.map(|_| JValueOwned::Void)) }); @@ -170,8 +168,7 @@ fn intern_stat(env: &mut JNIEnv, op: *mut Operator, path: JString) -> Result Result Result