-
Notifications
You must be signed in to change notification settings - Fork 478
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(bindings/java): explicit async runtime #4376
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
f68c5b3
feat: explicit async runtime
tisonkun 2133c43
add executor param everywhere
tisonkun 4f675f5
pipe
tisonkun 81e99f9
fixup
tisonkun 3473db1
add test
tisonkun be98f5a
license header
tisonkun e7ace59
tidy
tisonkun fb60d6f
docs and errors
tisonkun File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The blocking layer should be able to decouple from Tokio also. Perhaps using executor-trait and support passing a different executor. |
||
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.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It should possibly support other runtimes. This encapsulation is lightweight and we leave the room for enhancement instead of hard code using Tokio.