-
Notifications
You must be signed in to change notification settings - Fork 508
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(bindings/java): explicit async runtime (#4376)
* feat: explicit async runtime Signed-off-by: tison <[email protected]> * add executor param everywhere Signed-off-by: tison <[email protected]> * pipe Signed-off-by: tison <[email protected]> * fixup Signed-off-by: tison <[email protected]> * add test Signed-off-by: tison <[email protected]> * license header Signed-off-by: tison <[email protected]> * tidy Signed-off-by: tison <[email protected]> * docs and errors Signed-off-by: tison <[email protected]> --------- Signed-off-by: tison <[email protected]>
- Loading branch information
Showing
9 changed files
with
430 additions
and
168 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,4 @@ | ||
.mvn/wrapper/maven-wrapper.jar | ||
Cargo.lock | ||
|
||
*.log |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
// Licensed to the Apache Software Foundation (ASF) under one | ||
// or more contributor license agreements. See the NOTICE file | ||
// distributed with this work for additional information | ||
// regarding copyright ownership. The ASF licenses this file | ||
// to you under the Apache License, Version 2.0 (the | ||
// "License"); you may not use this file except in compliance | ||
// with the License. You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, | ||
// software distributed under the License is distributed on an | ||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
// KIND, either express or implied. See the License for the | ||
// specific language governing permissions and limitations | ||
// under the License. | ||
|
||
use std::cell::RefCell; | ||
use std::ffi::c_void; | ||
use std::future::Future; | ||
|
||
use jni::objects::{JClass, JObject}; | ||
use jni::sys::jlong; | ||
use jni::{JNIEnv, JavaVM}; | ||
use once_cell::sync::OnceCell; | ||
use tokio::task::JoinHandle; | ||
|
||
use crate::Result; | ||
|
||
static mut RUNTIME: OnceCell<Executor> = OnceCell::new(); | ||
thread_local! { | ||
static ENV: RefCell<Option<*mut jni::sys::JNIEnv>> = RefCell::new(None); | ||
} | ||
|
||
/// # Safety | ||
/// | ||
/// This function could be only called by java vm when unload this lib. | ||
#[no_mangle] | ||
pub unsafe extern "system" fn JNI_OnUnload(_: JavaVM, _: *mut c_void) { | ||
let _ = RUNTIME.take(); | ||
} | ||
|
||
/// # Safety | ||
/// | ||
/// This function could be only called when the lib is loaded and within an executor thread. | ||
pub(crate) unsafe fn get_current_env<'local>() -> JNIEnv<'local> { | ||
let env = ENV | ||
.with(|cell| *cell.borrow_mut()) | ||
.expect("env must be available"); | ||
JNIEnv::from_raw(env).expect("env must be valid") | ||
} | ||
|
||
pub enum Executor { | ||
Tokio(tokio::runtime::Runtime), | ||
} | ||
|
||
impl Executor { | ||
pub fn enter_with<F, R>(&self, f: F) -> R | ||
where | ||
F: FnOnce() -> R, | ||
{ | ||
match self { | ||
Executor::Tokio(e) => { | ||
let _guard = e.enter(); | ||
f() | ||
} | ||
} | ||
} | ||
|
||
pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output> | ||
where | ||
F: Future + Send + 'static, | ||
F::Output: Send + 'static, | ||
{ | ||
match self { | ||
Executor::Tokio(e) => e.spawn(future), | ||
} | ||
} | ||
} | ||
|
||
#[no_mangle] | ||
pub extern "system" fn Java_org_apache_opendal_AsyncExecutor_makeTokioExecutor( | ||
mut env: JNIEnv, | ||
_: JClass, | ||
cores: usize, | ||
) -> jlong { | ||
make_tokio_executor(&mut env, cores) | ||
.map(|executor| Box::into_raw(Box::new(executor)) as jlong) | ||
.unwrap_or_else(|e| { | ||
e.throw(&mut env); | ||
0 | ||
}) | ||
} | ||
|
||
/// # Safety | ||
/// | ||
/// This function should not be called before the AsyncExecutor is ready. | ||
#[no_mangle] | ||
pub unsafe extern "system" fn Java_org_apache_opendal_AsyncExecutor_disposeInternal( | ||
_: JNIEnv, | ||
_: JObject, | ||
executor: *mut Executor, | ||
) { | ||
drop(Box::from_raw(executor)); | ||
} | ||
|
||
pub(crate) fn make_tokio_executor(env: &mut JNIEnv, cores: usize) -> Result<Executor> { | ||
let vm = env.get_java_vm().expect("JavaVM must be available"); | ||
let executor = tokio::runtime::Builder::new_multi_thread() | ||
.worker_threads(cores) | ||
.on_thread_start(move || { | ||
ENV.with(|cell| { | ||
let env = vm | ||
.attach_current_thread_as_daemon() | ||
.expect("attach thread must succeed"); | ||
*cell.borrow_mut() = Some(env.get_raw()); | ||
}) | ||
}) | ||
.enable_all() | ||
.build() | ||
.map_err(|e| { | ||
opendal::Error::new( | ||
opendal::ErrorKind::Unexpected, | ||
"Failed to create tokio runtime.", | ||
) | ||
.set_source(e) | ||
})?; | ||
Ok(Executor::Tokio(executor)) | ||
} | ||
|
||
/// # Safety | ||
/// | ||
/// This function could be only when the lib is loaded. | ||
pub(crate) unsafe fn executor_or_default<'a>( | ||
env: &mut JNIEnv<'a>, | ||
executor: *const Executor, | ||
) -> &'a Executor { | ||
if executor.is_null() { | ||
default_executor(env) | ||
} else { | ||
&*executor | ||
} | ||
} | ||
|
||
/// # Safety | ||
/// | ||
/// This function could be only when the lib is loaded. | ||
unsafe fn default_executor<'a>(env: &mut JNIEnv<'a>) -> &'a Executor { | ||
RUNTIME | ||
.get_or_try_init(|| make_tokio_executor(env, num_cpus::get())) | ||
.expect("default executor must be able to initialize") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
40 changes: 40 additions & 0 deletions
40
bindings/java/src/main/java/org/apache/opendal/AsyncExecutor.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
/* | ||
* Licensed to the Apache Software Foundation (ASF) under one | ||
* or more contributor license agreements. See the NOTICE file | ||
* distributed with this work for additional information | ||
* regarding copyright ownership. The ASF licenses this file | ||
* to you under the Apache License, Version 2.0 (the | ||
* "License"); you may not use this file except in compliance | ||
* with the License. You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, | ||
* software distributed under the License is distributed on an | ||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
* KIND, either express or implied. See the License for the | ||
* specific language governing permissions and limitations | ||
* under the License. | ||
*/ | ||
|
||
package org.apache.opendal; | ||
|
||
/** | ||
* AsyncExecutor represents an underneath OpenDAL executor that runs async tasks spawned in the Rust world. | ||
* | ||
* <p>If the executor is passed to construct operators, the executor must outlive the operators.</p> | ||
*/ | ||
public class AsyncExecutor extends NativeObject { | ||
public static AsyncExecutor createTokioExecutor(int cores) { | ||
return new AsyncExecutor(makeTokioExecutor(cores)); | ||
} | ||
|
||
private AsyncExecutor(long nativeHandle) { | ||
super(nativeHandle); | ||
} | ||
|
||
@Override | ||
protected native void disposeInternal(long handle); | ||
|
||
private static native long makeTokioExecutor(int cores); | ||
} |
Oops, something went wrong.