Rust + NDK on Android, Part 9 of 15.This series teaches Android developers how to ship Rust in production apps, no prior Rust required. Hub: Rust on Android: How to Use It, How to Debug It, and Why It's Worth It. Previous: Error Handling and Panics: Keeping Rust Crashes Out of Your Android App. Next: Low-Latency Audio DSP with Rust: AAudio and Oboe from a Rust Core.
Store the JavaVM once in JNI_OnLoad, run a single Tokio runtime for the life of the process, hand any Kotlin object you give to a Rust task as a global reference, attach the Tokio worker to the JVM before it calls back, and wrap the callback API in suspendCancellableCoroutine so Kotlin sees an ordinary suspend function. Every step exists because of one JNI fact: a JNIEnv belongs to exactly one thread, and Rust threads start life with none.
Nearly every async JNI crash I have debugged comes from ignoring that fact: a JNIEnv smuggled onto the wrong thread, or a local reference outliving the call that created it. This post builds the machinery once, end to end, so you can copy the shape instead of rediscovering the crashes. It assumes the toolchain setup from Part 1 and the JNI basics from Part 2.
Key Takeaways
- A
JNIEnvis thread-local and can never be shared between threads; theJavaVMis process-wide and thread-safe, so capture the VM once and derive a fresh env on whichever thread needs one (Android JNI tips).- One Tokio runtime, built lazily, never shut down. On Android, process death is the shutdown.
- Every
jobjectthat crosses into a Rust task needs a global reference, and long-lived Tokio workers should attach to the JVM permanently instead of paying attach and detach churn per callback.suspendCancellableCoroutineturns the Rust callback API into a plain suspend function, andinvokeOnCancellationgives structured concurrency a path back into Rust to abort the task.
Why can’t a Rust thread just call into Kotlin?
Because JNI calls go through a JNIEnv, and the Android JNI tips are blunt about what that is: “The JNIEnv is used for thread-local storage. For this reason, you cannot share a JNIEnv between threads.” The env your extern "system" function receives is valid on that thread, for that call, and nowhere else. A thread spawned by Rust, whether through std::thread or a Tokio worker pool, has no env at all until it asks for one.
The type that does cross threads is the JavaVM: one per process, valid everywhere. The same docs give the recipe: share the JavaVM and use it to discover the current thread’s env. The jni crate encodes this in its types. JNIEnv is neither Send nor Sync, so the compiler stops you from smuggling one across a spawn; JavaVM is both, so a static is exactly where it belongs.
So a background thread that wants to call Kotlin attaches itself with AttachCurrentThread and receives a valid env of its own. Attaching is not free: per the same docs it constructs a java.lang.Thread object, adds it to the main ThreadGroup, and obliges the thread to detach before it exits. The callback code below handles both costs.
Capture the JavaVM in JNI_OnLoad
The crate for this part lives at rust/async-bridge/Cargo.toml:
[package]
name = "async-bridge"
version = "0.1.0"
edition = "2021"
[lib]
name = "async_bridge"
crate-type = ["cdylib"]
[dependencies]
jni = "0.21"
tokio = { version = "1", features = ["rt-multi-thread", "time"] }
log = "0.4"
android_logger = "0.15"
When System.loadLibrary pulls in your .so, the JVM looks for a JNI_OnLoad export and calls it with the one argument we actually want. This is the top of rust/async-bridge/src/lib.rs:
use std::collections::HashMap;
use std::ffi::c_void;
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
use jni::objects::{GlobalRef, JObject, JString, JValue};
use jni::sys::{jint, jlong, JNI_VERSION_1_6};
use jni::{JNIEnv, JavaVM};
use tokio::runtime::Runtime;
use tokio::task::AbortHandle;
static JVM: OnceLock<JavaVM> = OnceLock::new();
static RUNTIME: OnceLock<Runtime> = OnceLock::new();
static TASKS: OnceLock<Mutex<HashMap<i64, AbortHandle>>> = OnceLock::new();
static NEXT_ID: AtomicI64 = AtomicI64::new(1);
#[no_mangle]
pub extern "system" fn JNI_OnLoad(vm: JavaVM, _reserved: *mut c_void) -> jint {
android_logger::init_once(
android_logger::Config::default()
.with_max_level(log::LevelFilter::Info)
.with_tag("async-bridge"),
);
// The JavaVM is process-wide and thread-safe. Stored once here,
// it serves every thread for the lifetime of the process.
let _ = JVM.set(vm);
JNI_VERSION_1_6
}
If you would rather skip JNI_OnLoad, env.get_java_vm() returns the same value inside any JNI call. I prefer JNI_OnLoad: it runs exactly once, before anything can race it.
How do you run a Tokio runtime inside an Android app?
Build it lazily, keep it small, and never tear it down. Tokio’s multi-thread scheduler defaults its worker count to the number of CPU cores (tokio Builder docs), which is a server-shaped default. A phone running IO-bound work next to the JVM’s own pools does not need eight workers; two is plenty here, and naming them pays off because OS thread names show up in profilers. Continuing in rust/async-bridge/src/lib.rs:
fn runtime() -> &'static Runtime {
RUNTIME.get_or_init(|| {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.thread_name("rust-tokio")
.enable_time()
.build()
.expect("failed to build Tokio runtime")
})
}
fn tasks() -> &'static Mutex<HashMap<i64, AbortHandle>> {
TASKS.get_or_init(|| Mutex::new(HashMap::new()))
}
// Stand-in for real async work: a network call, a heavy parse, a sync job.
async fn fetch_greeting(name: String) -> Result<String, String> {
tokio::time::sleep(Duration::from_millis(300)).await;
if name.trim().is_empty() {
Err("name must not be blank".to_owned())
} else {
Ok(format!("Hello from a Tokio task, {name}"))
}
}
You do not shut the runtime down. Android does not give your process a graceful exit; it kills it. A runtime living in a static until process death matches the platform’s memory model. Host-side tests are the exception, and Runtime::shutdown_background exists for them.
JNI callbacks into Kotlin from a Rust Tokio task
Here is the entry point Kotlin calls to start work, and the delivery function the Tokio task uses to come back. Both go in rust/async-bridge/src/lib.rs:
#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_AsyncBridge_startFetch<'local>(
mut env: JNIEnv<'local>,
_this: JObject<'local>,
name: JString<'local>,
callback: JObject<'local>,
) -> jlong {
let name: String = env.get_string(&name).map(Into::into).unwrap_or_default();
// `callback` is a local reference. It dies when this function returns,
// so the task must hold a global reference instead.
let callback: GlobalRef = match env.new_global_ref(&callback) {
Ok(global) => global,
Err(_) => return 0,
};
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
// Holding the lock across spawn + insert means the task cannot
// deregister itself before its abort handle is registered.
let mut map = tasks().lock().expect("tasks mutex poisoned");
let join = runtime().spawn(async move {
let result = fetch_greeting(name).await;
// Deregister first: any cancel arriving from now on is a no-op.
tasks().lock().expect("tasks mutex poisoned").remove(&id);
deliver(&callback, result);
});
map.insert(id, join.abort_handle());
id
}
/// Runs on a Tokio worker thread. Attaches it to the JVM, then calls
/// FetchCallback.onSuccess or FetchCallback.onError on the Kotlin side.
fn deliver(callback: &GlobalRef, result: Result<String, String>) {
let vm = JVM.get().expect("JavaVM must be stored in JNI_OnLoad");
// Permanent attach: the worker stays attached until the thread exits,
// so later callbacks from this thread skip the attach cost entirely.
let mut env = match vm.attach_current_thread_permanently() {
Ok(env) => env,
Err(e) => {
log::error!("failed to attach Tokio worker to the JVM: {e}");
return;
}
};
let (method, text) = match result {
Ok(value) => ("onSuccess", value),
Err(message) => ("onError", message),
};
let payload: JObject = match env.new_string(text) {
Ok(s) => s.into(),
Err(e) => {
log::error!("failed to allocate Java string: {e}");
return;
}
};
if let Err(e) = env.call_method(
callback,
method,
"(Ljava/lang/String;)V",
&[JValue::Object(&payload)],
) {
log::error!("callback into Kotlin failed: {e}");
// If the Kotlin callback threw, clear the pending exception so it
// cannot poison the next JNI call made from this thread.
if env.exception_check().unwrap_or(false) {
let _ = env.exception_describe();
let _ = env.exception_clear();
}
}
}
#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_AsyncBridge_cancelFetch(
_env: JNIEnv,
_this: JObject,
id: jlong,
) {
if let Some(abort) = tasks().lock().expect("tasks mutex poisoned").remove(&id) {
abort.abort();
}
}
The global reference is not optional. Every argument passed to a native method is a local reference, valid only for the duration of that call on that thread, per the Android docs. The task outlives the call by design, so it needs the new_global_ref move covered in depth in Part 7 on JNI memory management. The jni crate closes the loop: when the task drops the GlobalRef, the crate deletes the JNI global reference, attaching the thread first if it must.
Permanent attach beats a guard here. The jni crate offers three flavors. attach_current_thread returns a guard that detaches on drop: correct, but a long-lived worker then repeats the attach dance, and its java.lang.Thread construction, on every callback. attach_current_thread_permanently attaches once and detaches automatically when the thread terminates, satisfying the detach-before-exit rule. The daemon variant, attach_current_thread_as_daemon, only changes JVM shutdown behavior, and Android kills processes instead of shutting the VM down, so it rarely matters in an app. For a fixed Tokio pool, permanent attach is the right default.
Cancellation goes through an id, not a pointer. I could hand Kotlin a raw Box::into_raw pointer to the AbortHandle, but a cancel racing a normal completion would become a double-free question. The Mutex map makes both races boring: cancel after completion finds nothing, and completion after cancel never runs because abort drops the future at its next await point, callback unfired, global reference released.
The matching Kotlin declarations live in app/src/main/java/dev/davthecoder/rustseries/AsyncBridge.kt:
package dev.davthecoder.rustseries
interface FetchCallback {
fun onSuccess(payload: String)
fun onError(message: String)
}
object AsyncBridge {
init {
System.loadLibrary("async_bridge")
}
external fun startFetch(name: String, callback: FetchCallback): Long
external fun cancelFetch(handle: Long)
}
Bridging the callback into Kotlin coroutines
A callback interface is a working API and a miserable one. Kotlin callers want a suspend function, and suspendCancellableCoroutine is the standard adapter for exactly this situation: a one-shot, callback-based API that supports cancellation (kotlinx.coroutines docs). The wrapper goes in app/src/main/java/dev/davthecoder/rustseries/FetchGreeting.kt:
package dev.davthecoder.rustseries
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
class RustFetchException(message: String) : Exception(message)
suspend fun fetchGreeting(name: String): String =
suspendCancellableCoroutine { continuation ->
val handle = AsyncBridge.startFetch(name, object : FetchCallback {
override fun onSuccess(payload: String) {
continuation.resume(payload)
}
override fun onError(message: String) {
continuation.resumeWithException(RustFetchException(message))
}
})
continuation.invokeOnCancellation {
AsyncBridge.cancelFetch(handle)
}
}
onSuccess runs on the Tokio worker. Resuming there is safe because the continuation hands the coroutine back to its dispatcher; code after the suspension point runs wherever the caller’s context says, typically Dispatchers.Main in a ViewModel. You never touch a view from the callback, and you never need to.
A caller’s scope dies, structured concurrency cancels the coroutine, invokeOnCancellation fires and calls cancelFetch, Rust removes the abort handle and aborts the task, and the callback never arrives. If the callback was already in flight, the prompt cancellation guarantee covers you: once the job is cancelled, the coroutine will not resume successfully even if resume was already invoked. Both orderings end quietly. If the Job machinery underneath that sentence feels hazy, my post on Job types in Kotlin coroutines covers it.
Usage is now indistinguishable from any other suspend call. From app/src/main/java/dev/davthecoder/rustseries/GreetingViewModel.kt:
package dev.davthecoder.rustseries
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
class GreetingViewModel : ViewModel() {
fun load() {
viewModelScope.launch {
val message = try {
fetchGreeting("David")
} catch (e: RustFetchException) {
"Rust said no: ${e.message}"
}
// message arrives on the main dispatcher, ready for UI state.
}
}
}
When this ViewModel clears, viewModelScope cancels the coroutine and the whole chain unwinds down into Tokio without another line of code: lifecycle awareness for free, on the Rust side of the border.
The rules that keep you out of a tombstone
- Never cache a
JNIEnv. Not in a static, not in a struct, never across threads. Store theJavaVM, derive an env where you need it. The jni crate’sSendbounds enforce this. - Global-ref every
jobjectthat outlives the call or changes threads. Locals die with the call that made them, whatever the underlying object does. Part 7 on JNI reference types and leaks covers the reference zoo in full. - Attached threads must detach before exiting. Use the guard for short-lived threads and permanent attach for pools, and let the jni crate own the bookkeeping in both cases.
- One runtime, created once, never shut down. Treat it like the process-level resource it is.
- Assume callbacks land on foreign threads. Let coroutine dispatchers do the thread hop; a callback that touches UI state directly is a bug waiting for a slow device to prove it.
One panic note to close the loop with Part 8 on error handling and panics: a panic inside a spawned Tokio task does not cross the JNI boundary, because the runtime catches it and reports it through the JoinHandle, which this design drops. That silence is why the logcat panic hook from Part 8 stays mandatory here, and if your release profile sets panic = "abort", doubly so: the task panic then kills the process directly.
Frequently Asked Questions
Can Tokio share a thread pool with Kotlin coroutines?
No, and you should not try. Tokio workers and coroutine dispatchers are separate pools with separate schedulers, and the bridge between them is a callback plus a continuation, not a shared executor. Keep the Tokio pool small so the two runtimes do not fight over cores Android’s own threads also want.
Does UniFFI handle async Rust for me?
Mostly, yes. UniFFI can expose an async fn as a Kotlin suspend function directly, which removes the callback and continuation plumbing from this post (UniFFI futures docs). Its docs note that cancellation is not built in, so a cancel path like this post’s abort registry remains your job. Part 3 on UniFFI bindings covers where UniFFI fits overall.
The next post takes these threading rules somewhere much less forgiving. Part 10, Low-Latency Audio DSP with Rust: AAudio and Oboe from a Rust Core, puts Rust on the audio thread, where blocking and allocation are banned and even JNI is off the table. If you landed here mid-series, the hub post maps all fifteen parts.
Sources
- Android Developers, “JNI tips”, retrieved 2026-07-23, https://developer.android.com/training/articles/perf-jni
- docs.rs, jni crate 0.21 API documentation, retrieved 2026-07-23, https://docs.rs/jni/0.21.1/jni/
- docs.rs, tokio runtime Builder documentation, retrieved 2026-07-23, https://docs.rs/tokio/latest/tokio/runtime/struct.Builder.html
- kotlinx.coroutines API documentation, suspendCancellableCoroutine, retrieved 2026-07-23, https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/suspend-cancellable-coroutine.html
- Mozilla, UniFFI async/futures documentation, retrieved 2026-07-23, https://mozilla.github.io/uniffi-rs/latest/futures.html
Rust + NDK on Android, Part 9 of 15.This series teaches Android developers how to ship Rust in production apps, no prior Rust required. Hub: Rust on Android: How to Use It, How to Debug It, and Why It's Worth It. Previous: Error Handling and Panics: Keeping Rust Crashes Out of Your Android App. Next: Low-Latency Audio DSP with Rust: AAudio and Oboe from a Rust Core.
Guarda la JavaVM una sola vez en JNI_OnLoad, ejecuta un único runtime de Tokio durante toda la vida del proceso, entrega cualquier objeto de Kotlin que pases a una tarea de Rust como referencia global, haz attach del worker de Tokio a la JVM antes de que devuelva la llamada, y envuelve la API de callbacks en suspendCancellableCoroutine para que Kotlin vea una función suspend normal. Cada paso existe por un hecho de JNI: un JNIEnv pertenece exactamente a un hilo, y los hilos de Rust nacen sin ninguno.
Casi todos los crashes de JNI asíncrono que he depurado vienen de ignorar ese hecho: un JNIEnv colado en el hilo equivocado, o una referencia local que sobrevive a la llamada que la creó. Este post monta la maquinaria una sola vez, de punta a punta, para que copies la forma en lugar de redescubrir los crashes. Da por hechos el montaje de la cadena de herramientas de la Parte 1 y los fundamentos de JNI de la Parte 2.
Ideas clave
- Un
JNIEnves local al hilo y no se puede compartir nunca entre hilos; laJavaVMes de todo el proceso y segura entre hilos, así que captura la VM una vez y deriva un env nuevo en el hilo que lo necesite (consejos de JNI de Android).- Un runtime de Tokio, construido de forma perezosa, que nunca se apaga. En Android, la muerte del proceso es el apagado.
- Todo
jobjectque cruza hacia una tarea de Rust necesita una referencia global, y los workers de Tokio de larga vida deberían hacer attach permanente a la JVM en lugar de pagar el vaivén de attach y detach en cada callback.suspendCancellableCoroutineconvierte la API de callbacks de Rust en una función suspend normal, einvokeOnCancellationda a la concurrencia estructurada un camino de vuelta a Rust para abortar la tarea.
¿Por qué un hilo de Rust no puede llamar a Kotlin sin más?
Porque las llamadas JNI pasan por un JNIEnv, y los consejos de JNI de Android son tajantes sobre qué es eso: «El JNIEnv se usa como almacenamiento local al hilo. Por eso no puedes compartir un JNIEnv entre hilos». El env que recibe tu función extern "system" vale en ese hilo, para esa llamada, y en ningún otro sitio. Un hilo creado por Rust, ya sea con std::thread o con un pool de workers de Tokio, no tiene env alguno hasta que lo pide.
El tipo que sí cruza hilos es la JavaVM: una por proceso, válida en todas partes. La misma documentación da la receta: comparte la JavaVM y úsala para descubrir el env del hilo actual. El crate jni codifica esto en sus tipos. JNIEnv no es ni Send ni Sync, así que el compilador te impide colar uno a través de un spawn; JavaVM es las dos cosas, así que un static es exactamente el sitio donde debe estar.
Así, un hilo en segundo plano que quiere llamar a Kotlin hace attach de sí mismo con AttachCurrentThread y recibe un env válido propio. El attach no es gratis: según la misma documentación, construye un objeto java.lang.Thread, lo añade al ThreadGroup principal y obliga al hilo a hacer detach antes de salir. El código de callback de más abajo asume los dos costes.
Captura la JavaVM en JNI_OnLoad
El crate de esta parte vive en rust/async-bridge/Cargo.toml:
[package]
name = "async-bridge"
version = "0.1.0"
edition = "2021"
[lib]
name = "async_bridge"
crate-type = ["cdylib"]
[dependencies]
jni = "0.21"
tokio = { version = "1", features = ["rt-multi-thread", "time"] }
log = "0.4"
android_logger = "0.15"
Cuando System.loadLibrary carga tu .so, la JVM busca un export JNI_OnLoad y lo llama con el único argumento que de verdad queremos. Esto es el principio de rust/async-bridge/src/lib.rs:
use std::collections::HashMap;
use std::ffi::c_void;
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
use jni::objects::{GlobalRef, JObject, JString, JValue};
use jni::sys::{jint, jlong, JNI_VERSION_1_6};
use jni::{JNIEnv, JavaVM};
use tokio::runtime::Runtime;
use tokio::task::AbortHandle;
static JVM: OnceLock<JavaVM> = OnceLock::new();
static RUNTIME: OnceLock<Runtime> = OnceLock::new();
static TASKS: OnceLock<Mutex<HashMap<i64, AbortHandle>>> = OnceLock::new();
static NEXT_ID: AtomicI64 = AtomicI64::new(1);
#[no_mangle]
pub extern "system" fn JNI_OnLoad(vm: JavaVM, _reserved: *mut c_void) -> jint {
android_logger::init_once(
android_logger::Config::default()
.with_max_level(log::LevelFilter::Info)
.with_tag("async-bridge"),
);
// The JavaVM is process-wide and thread-safe. Stored once here,
// it serves every thread for the lifetime of the process.
let _ = JVM.set(vm);
JNI_VERSION_1_6
}
Si prefieres saltarte JNI_OnLoad, env.get_java_vm() devuelve el mismo valor dentro de cualquier llamada JNI. Yo prefiero JNI_OnLoad: se ejecuta exactamente una vez, antes de que nada pueda competir con él.
¿Cómo ejecutas un runtime de Tokio dentro de una app de Android?
Constrúyelo de forma perezosa, mantenlo pequeño y no lo desmontes nunca. El planificador multihilo de Tokio pone por defecto el número de workers igual al de núcleos de la CPU (documentación del Builder de tokio), un valor pensado para un servidor. Un móvil que hace trabajo limitado por E/S, al lado de los propios pools de la JVM, no necesita ocho workers; aquí sobra con dos, y ponerles nombre compensa porque los nombres de hilo del sistema operativo salen en los perfiladores. Seguimos en rust/async-bridge/src/lib.rs:
fn runtime() -> &'static Runtime {
RUNTIME.get_or_init(|| {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.thread_name("rust-tokio")
.enable_time()
.build()
.expect("failed to build Tokio runtime")
})
}
fn tasks() -> &'static Mutex<HashMap<i64, AbortHandle>> {
TASKS.get_or_init(|| Mutex::new(HashMap::new()))
}
// Stand-in for real async work: a network call, a heavy parse, a sync job.
async fn fetch_greeting(name: String) -> Result<String, String> {
tokio::time::sleep(Duration::from_millis(300)).await;
if name.trim().is_empty() {
Err("name must not be blank".to_owned())
} else {
Ok(format!("Hello from a Tokio task, {name}"))
}
}
No apagas el runtime. Android no da a tu proceso una salida ordenada; lo mata. Un runtime que vive en un static hasta la muerte del proceso coincide con el modelo de memoria de la plataforma. La excepción son los tests en el host, y para ellos existe Runtime::shutdown_background.
Callbacks JNI hacia Kotlin desde una tarea de Tokio en Rust
Aquí está el punto de entrada que Kotlin llama para arrancar el trabajo, y la función de entrega que la tarea de Tokio usa para volver. Las dos van en rust/async-bridge/src/lib.rs:
#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_AsyncBridge_startFetch<'local>(
mut env: JNIEnv<'local>,
_this: JObject<'local>,
name: JString<'local>,
callback: JObject<'local>,
) -> jlong {
let name: String = env.get_string(&name).map(Into::into).unwrap_or_default();
// `callback` is a local reference. It dies when this function returns,
// so the task must hold a global reference instead.
let callback: GlobalRef = match env.new_global_ref(&callback) {
Ok(global) => global,
Err(_) => return 0,
};
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
// Holding the lock across spawn + insert means the task cannot
// deregister itself before its abort handle is registered.
let mut map = tasks().lock().expect("tasks mutex poisoned");
let join = runtime().spawn(async move {
let result = fetch_greeting(name).await;
// Deregister first: any cancel arriving from now on is a no-op.
tasks().lock().expect("tasks mutex poisoned").remove(&id);
deliver(&callback, result);
});
map.insert(id, join.abort_handle());
id
}
/// Runs on a Tokio worker thread. Attaches it to the JVM, then calls
/// FetchCallback.onSuccess or FetchCallback.onError on the Kotlin side.
fn deliver(callback: &GlobalRef, result: Result<String, String>) {
let vm = JVM.get().expect("JavaVM must be stored in JNI_OnLoad");
// Permanent attach: the worker stays attached until the thread exits,
// so later callbacks from this thread skip the attach cost entirely.
let mut env = match vm.attach_current_thread_permanently() {
Ok(env) => env,
Err(e) => {
log::error!("failed to attach Tokio worker to the JVM: {e}");
return;
}
};
let (method, text) = match result {
Ok(value) => ("onSuccess", value),
Err(message) => ("onError", message),
};
let payload: JObject = match env.new_string(text) {
Ok(s) => s.into(),
Err(e) => {
log::error!("failed to allocate Java string: {e}");
return;
}
};
if let Err(e) = env.call_method(
callback,
method,
"(Ljava/lang/String;)V",
&[JValue::Object(&payload)],
) {
log::error!("callback into Kotlin failed: {e}");
// If the Kotlin callback threw, clear the pending exception so it
// cannot poison the next JNI call made from this thread.
if env.exception_check().unwrap_or(false) {
let _ = env.exception_describe();
let _ = env.exception_clear();
}
}
}
#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_AsyncBridge_cancelFetch(
_env: JNIEnv,
_this: JObject,
id: jlong,
) {
if let Some(abort) = tasks().lock().expect("tasks mutex poisoned").remove(&id) {
abort.abort();
}
}
La referencia global no es opcional. Cada argumento que se pasa a un método nativo es una referencia local, válida solo mientras dura esa llamada en ese hilo, según la documentación de Android. La tarea sobrevive a la llamada por diseño, así que necesita el movimiento con new_global_ref que se trata a fondo en la Parte 7 sobre gestión de memoria en JNI. El crate jni cierra el círculo: cuando la tarea hace drop del GlobalRef, el crate borra la referencia global de JNI, y antes hace attach del hilo si hace falta.
Aquí el attach permanente gana a un guard. El crate jni ofrece tres variantes. attach_current_thread devuelve un guard que hace detach al hacer drop: es correcto, pero entonces un worker de larga vida repite el baile del attach, y la construcción de su java.lang.Thread, en cada callback. attach_current_thread_permanently hace attach una vez y detach automático cuando el hilo termina, y así cumple la regla de detach antes de salir. La variante daemon, attach_current_thread_as_daemon, solo cambia el comportamiento al apagar la JVM, y Android mata procesos en lugar de apagar la VM, así que rara vez importa en una app. Para un pool fijo de Tokio, el attach permanente es el valor por defecto correcto.
La cancelación pasa por un id, no por un puntero. Podría entregar a Kotlin un puntero crudo de Box::into_raw hacia el AbortHandle, pero una cancelación que compite con una finalización normal se convertiría en un problema de doble liberación. El mapa con Mutex vuelve aburridas las dos condiciones de carrera: cancelar después de completar no encuentra nada, y completar después de cancelar nunca llega a ejecutarse, porque abort hace drop del future en su siguiente punto de await, sin disparar el callback y soltando la referencia global.
Las declaraciones de Kotlin que encajan viven en app/src/main/java/dev/davthecoder/rustseries/AsyncBridge.kt:
package dev.davthecoder.rustseries
interface FetchCallback {
fun onSuccess(payload: String)
fun onError(message: String)
}
object AsyncBridge {
init {
System.loadLibrary("async_bridge")
}
external fun startFetch(name: String, callback: FetchCallback): Long
external fun cancelFetch(handle: Long)
}
Conectar el callback con las corrutinas de Kotlin
Una interfaz de callback es una API que funciona y, a la vez, una API penosa. Quien llama desde Kotlin quiere una función suspend, y suspendCancellableCoroutine es el adaptador estándar justo para este caso: una API de un solo disparo, basada en callbacks, que admite cancelación (documentación de kotlinx.coroutines). El wrapper va en app/src/main/java/dev/davthecoder/rustseries/FetchGreeting.kt:
package dev.davthecoder.rustseries
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
class RustFetchException(message: String) : Exception(message)
suspend fun fetchGreeting(name: String): String =
suspendCancellableCoroutine { continuation ->
val handle = AsyncBridge.startFetch(name, object : FetchCallback {
override fun onSuccess(payload: String) {
continuation.resume(payload)
}
override fun onError(message: String) {
continuation.resumeWithException(RustFetchException(message))
}
})
continuation.invokeOnCancellation {
AsyncBridge.cancelFetch(handle)
}
}
onSuccess se ejecuta en el worker de Tokio. Reanudar ahí es seguro porque la continuación devuelve la corrutina a su dispatcher; el código posterior al punto de suspensión corre donde diga el contexto de quien llama, normalmente Dispatchers.Main en un ViewModel. Nunca tocas una vista desde el callback, y nunca hace falta.
El scope de quien llama muere, la concurrencia estructurada cancela la corrutina, invokeOnCancellation se dispara y llama a cancelFetch, Rust quita el abort handle y aborta la tarea, y el callback no llega nunca. Si el callback ya iba en vuelo, te cubre la garantía de cancelación inmediata: una vez cancelado el job, la corrutina no se reanudará con éxito aunque resume ya se hubiera invocado. Los dos órdenes acaban en silencio. Si la maquinaria de Job que hay debajo de esa frase te suena borrosa, mi post sobre los tipos de Job en las corrutinas de Kotlin lo cubre.
El uso ya no se distingue de cualquier otra llamada suspend. Desde app/src/main/java/dev/davthecoder/rustseries/GreetingViewModel.kt:
package dev.davthecoder.rustseries
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
class GreetingViewModel : ViewModel() {
fun load() {
viewModelScope.launch {
val message = try {
fetchGreeting("David")
} catch (e: RustFetchException) {
"Rust said no: ${e.message}"
}
// message arrives on the main dispatcher, ready for UI state.
}
}
}
Cuando este ViewModel se limpia, viewModelScope cancela la corrutina y toda la cadena se desenrolla hasta Tokio sin una línea más de código: consciencia del ciclo de vida gratis, en el lado Rust de la frontera.
Las reglas que te libran de un tombstone
- Nunca cachees un
JNIEnv. Ni en un static, ni en un struct, y nunca entre hilos. Guarda laJavaVMy deriva un env donde lo necesites. Los boundsSenddel crate jni lo imponen. - Haz global ref de cada
jobjectque sobreviva a la llamada o cambie de hilo. Las locales mueren con la llamada que las creó, haga lo que haga el objeto de debajo. La Parte 7 sobre tipos de referencia JNI y fugas cubre el zoo entero de referencias. - Los hilos con attach deben hacer detach antes de salir. Usa el guard para hilos de vida corta y el attach permanente para los pools, y deja que el crate jni lleve las cuentas en los dos casos.
- Un runtime, creado una vez, que nunca se apaga. Trátalo como el recurso a nivel de proceso que es.
- Da por hecho que los callbacks aterrizan en hilos ajenos. Deja que los dispatchers de las corrutinas hagan el salto de hilo; un callback que toca el estado de la UI directamente es un bug a la espera de que un dispositivo lento lo demuestre.
Una nota sobre panics para cerrar el círculo con la Parte 8 sobre gestión de errores y panics: un panic dentro de una tarea de Tokio lanzada con spawn no cruza la frontera JNI, porque el runtime lo captura y lo informa a través del JoinHandle, que este diseño descarta. Ese silencio es la razón de que el hook de panic de logcat de la Parte 8 siga siendo obligatorio aquí, y si tu perfil de release pone panic = "abort", el doble: el panic de la tarea mata entonces el proceso directamente.
Preguntas frecuentes
¿Puede Tokio compartir un pool de hilos con las corrutinas de Kotlin?
No, y no deberías intentarlo. Los workers de Tokio y los dispatchers de las corrutinas son pools distintos, con planificadores distintos, y el puente entre ellos es un callback más una continuación, no un executor compartido. Mantén pequeño el pool de Tokio para que los dos runtimes no se peleen por núcleos que también quieren los propios hilos de Android.
¿UniFFI me gestiona el Rust asíncrono?
En gran parte, sí. UniFFI puede exponer un async fn directamente como función suspend de Kotlin, y eso quita de en medio el montaje de callbacks y continuación de este post (documentación de futures de UniFFI). Su documentación avisa de que la cancelación no viene de serie, así que un camino de cancelación como el registro de abort de este post sigue siendo cosa tuya. La Parte 3 sobre bindings de UniFFI cubre dónde encaja UniFFI en conjunto.
El post siguiente lleva estas reglas de hilos a un sitio mucho menos indulgente. La Parte 10, Low-Latency Audio DSP with Rust: AAudio and Oboe from a Rust Core, pone a Rust en el hilo de audio, donde bloquear y reservar memoria están prohibidos e incluso JNI queda fuera de la mesa. Si has aterrizado aquí a mitad de la serie, el post hub traza las quince partes.
Fuentes
- Android Developers, «JNI tips», consultado el 2026-07-23, https://developer.android.com/training/articles/perf-jni
- docs.rs, documentación de la API del crate jni 0.21, consultado el 2026-07-23, https://docs.rs/jni/0.21.1/jni/
- docs.rs, documentación del Builder del runtime de tokio, consultado el 2026-07-23, https://docs.rs/tokio/latest/tokio/runtime/struct.Builder.html
- Documentación de la API de kotlinx.coroutines, suspendCancellableCoroutine, consultado el 2026-07-23, https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/suspend-cancellable-coroutine.html
- Mozilla, documentación de async/futures de UniFFI, consultado el 2026-07-23, https://mozilla.github.io/uniffi-rs/latest/futures.html
Rust + NDK on Android, Part 9 of 15.This series teaches Android developers how to ship Rust in production apps, no prior Rust required. Hub: Rust on Android: How to Use It, How to Debug It, and Why It's Worth It. Previous: Error Handling and Panics: Keeping Rust Crashes Out of Your Android App. Next: Low-Latency Audio DSP with Rust: AAudio and Oboe from a Rust Core.
เก็บ JavaVM ครั้งเดียวใน JNI_OnLoad รัน Tokio runtime เดียวตลอดอายุโปรเซส ส่งอ็อบเจกต์ Kotlin ใดที่ให้กับทาสก์ Rust เป็น global reference ผูกเวิร์กเกอร์ Tokio เข้า JVM ก่อนมันเรียกกลับ และห่อ API แบบ callback ใน suspendCancellableCoroutine เพื่อให้ Kotlin เห็นฟังก์ชัน suspend ธรรมดา ทุกขั้นตอนมีอยู่เพราะข้อเท็จจริง JNI ข้อเดียว: JNIEnv เป็นของเธรดเดียวเท่านั้น และเธรด Rust เริ่มชีวิตโดยไม่มีมัน
แครช JNI แบบ async เกือบทุกครั้งที่ผมดีบักมาจากการเพิกเฉยข้อนั้น: JNIEnv ที่แอบเอาไปเธรดผิด หรือ local reference ที่อยู่เกินคำเรียกที่สร้างมัน บทความนี้สร้างเครื่องจักรครั้งเดียวตั้งแต่ต้นจนจบ เพื่อให้คัดลอกรูปทรงได้ แทนที่จะไปค้นพบแครชใหม่ มันสมมติ การตั้งทูลเชนจากตอนที่ 1 และ พื้นฐาน JNI จากตอนที่ 2
ประเด็นสำคัญ
JNIEnvเป็นของเฉพาะเธรด และแชร์ข้ามเธรดไม่ได้JavaVMเป็นของทั้งโปรเซสและปลอดภัยข้ามเธรด ดังนั้นจับ VM ครั้งเดียว แล้วสร้าง env ใหม่บนเธรดใดที่ต้องการ (Android JNI tips)- Tokio runtime เดียว สร้างแบบขี้เกียจ ไม่เคยปิด บน Android ความตายของโปรเซสคือการปิด
jobjectทุกตัวที่ข้ามเข้าทาสก์ Rust ต้องมี global reference และเวิร์กเกอร์ Tokio อายุยาวควรผูกกับ JVM ถาวร แทนที่จะจ่ายค่า attach และ detach ทุก callbacksuspendCancellableCoroutineเปลี่ยน API แบบ callback ของ Rust เป็นฟังก์ชัน suspend ธรรมดา และinvokeOnCancellationให้ structured concurrency มีทางกลับเข้า Rust เพื่อยกเลิกทาสก์
ทำไมเธรด Rust เรียกเข้า Kotlin ตรงๆ ไม่ได้?
เพราะการเรียก JNI ผ่าน JNIEnv และ Android JNI tips พูดตรงๆ ว่ามันคืออะไร: “JNIEnv ใช้สำหรับที่เก็บข้อมูลเฉพาะเธรด ด้วยเหตุนี้ คุณแชร์ JNIEnv ข้ามเธรดไม่ได้” env ที่ฟังก์ชัน extern "system" ได้รับใช้ได้บนเธรดนั้น สำหรับคำเรียกนั้น และที่อื่นไม่ได้ เธรดที่ Rust สร้าง ไม่ว่าผ่าน std::thread หรือพูลเวิร์กเกอร์ของ Tokio จะไม่มี env จนกว่ามันจะขอ
ชนิดที่ข้ามเธรดได้คือ JavaVM: หนึ่งตัวต่อโปรเซส ใช้ได้ทุกที่ เอกสารชุดเดียวกันให้สูตร: แชร์ JavaVM แล้วใช้มันค้นหา env ของเธรดปัจจุบัน crate jni เข้ารหัสสิ่งนี้ในชนิดของมัน JNIEnv ไม่ใช่ทั้ง Send และ Sync ดังนั้นคอมไพเลอร์หยุดคุณไม่ให้แอบส่งตัวหนึ่งข้าม spawn JavaVM เป็นทั้งสองอย่าง ดังนั้น static คือที่ที่มันควรอยู่
ดังนั้นเธรดเบื้องหลังที่อยากเรียก Kotlin จะผูกตัวเองด้วย AttachCurrentThread แล้วได้ env ที่ใช้ได้ของตัวเอง การ attach ไม่ฟรี: ตามเอกสารเดียวกัน มันสร้างอ็อบเจกต์ java.lang.Thread เพิ่มเข้า ThreadGroup หลัก และบังคับให้เธรด detach ก่อนออก โค้ด callback ด้านล่างจัดการทั้งสองต้นทุน
จับ JavaVM ใน JNI_OnLoad
crate ของตอนนี้อยู่ที่ rust/async-bridge/Cargo.toml:
[package]
name = "async-bridge"
version = "0.1.0"
edition = "2021"
[lib]
name = "async_bridge"
crate-type = ["cdylib"]
[dependencies]
jni = "0.21"
tokio = { version = "1", features = ["rt-multi-thread", "time"] }
log = "0.4"
android_logger = "0.15"
เมื่อ System.loadLibrary ดึง .so ของคุณ JVM มองหา export JNI_OnLoad แล้วเรียกมันด้วยอาร์กิวเมนต์เดียวที่เราต้องการจริง นี่คือส่วนบนของ rust/async-bridge/src/lib.rs:
use std::collections::HashMap;
use std::ffi::c_void;
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
use jni::objects::{GlobalRef, JObject, JString, JValue};
use jni::sys::{jint, jlong, JNI_VERSION_1_6};
use jni::{JNIEnv, JavaVM};
use tokio::runtime::Runtime;
use tokio::task::AbortHandle;
static JVM: OnceLock<JavaVM> = OnceLock::new();
static RUNTIME: OnceLock<Runtime> = OnceLock::new();
static TASKS: OnceLock<Mutex<HashMap<i64, AbortHandle>>> = OnceLock::new();
static NEXT_ID: AtomicI64 = AtomicI64::new(1);
#[no_mangle]
pub extern "system" fn JNI_OnLoad(vm: JavaVM, _reserved: *mut c_void) -> jint {
android_logger::init_once(
android_logger::Config::default()
.with_max_level(log::LevelFilter::Info)
.with_tag("async-bridge"),
);
// The JavaVM is process-wide and thread-safe. Stored once here,
// it serves every thread for the lifetime of the process.
let _ = JVM.set(vm);
JNI_VERSION_1_6
}
ถ้าอยากข้าม JNI_OnLoad env.get_java_vm() คืนค่าเดียวกันภายในคำเรียก JNI ใดๆ ผมชอบ JNI_OnLoad: มันรันครั้งเดียวพอดี ก่อนมีอะไรมาแข่งกับมันได้
จะรัน Tokio runtime ในแอป Android อย่างไร?
สร้างแบบขี้เกียจ ให้มันเล็ก และอย่ารื้อมันลง ตัวจัดตารางแบบหลายเธรดของ Tokio ตั้งจำนวนเวิร์กเกอร์เริ่มต้นเท่าจำนวนคอร์ CPU (tokio Builder docs) ซึ่งเป็นค่าเริ่มต้นรูปเซิร์ฟเวอร์ โทรศัพท์ที่ทำงานผูก I/O ข้างพูลของ JVM เองไม่ต้องการเวิร์กเกอร์แปดตัว สองตัวพอที่นี่ และการตั้งชื่อคุ้ม เพราะชื่อเธรดของ OS โผล่ในโปรไฟเลอร์ ต่อใน rust/async-bridge/src/lib.rs:
fn runtime() -> &'static Runtime {
RUNTIME.get_or_init(|| {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.thread_name("rust-tokio")
.enable_time()
.build()
.expect("failed to build Tokio runtime")
})
}
fn tasks() -> &'static Mutex<HashMap<i64, AbortHandle>> {
TASKS.get_or_init(|| Mutex::new(HashMap::new()))
}
// Stand-in for real async work: a network call, a heavy parse, a sync job.
async fn fetch_greeting(name: String) -> Result<String, String> {
tokio::time::sleep(Duration::from_millis(300)).await;
if name.trim().is_empty() {
Err("name must not be blank".to_owned())
} else {
Ok(format!("Hello from a Tokio task, {name}"))
}
}
คุณไม่ปิด runtime Android ไม่ให้โปรเซสของคุณออกอย่างสุภาพ มันฆ่าโปรเซส runtime ที่อยู่ใน static จนโปรเซสตายตรงกับโมเดลหน่วยความจำของแพลตฟอร์ม เทสต์ฝั่งโฮสต์เป็นข้อยกเว้น และ Runtime::shutdown_background มีไว้สำหรับพวกมัน
callback ของ JNI เข้า Kotlin จากทาสก์ Tokio ของ Rust
นี่คือจุดเข้าที่ Kotlin เรียกเพื่อเริ่มงาน และฟังก์ชันส่งมอบที่ทาสก์ Tokio ใช้กลับมา ทั้งคู่อยู่ใน rust/async-bridge/src/lib.rs:
#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_AsyncBridge_startFetch<'local>(
mut env: JNIEnv<'local>,
_this: JObject<'local>,
name: JString<'local>,
callback: JObject<'local>,
) -> jlong {
let name: String = env.get_string(&name).map(Into::into).unwrap_or_default();
// `callback` is a local reference. It dies when this function returns,
// so the task must hold a global reference instead.
let callback: GlobalRef = match env.new_global_ref(&callback) {
Ok(global) => global,
Err(_) => return 0,
};
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
// Holding the lock across spawn + insert means the task cannot
// deregister itself before its abort handle is registered.
let mut map = tasks().lock().expect("tasks mutex poisoned");
let join = runtime().spawn(async move {
let result = fetch_greeting(name).await;
// Deregister first: any cancel arriving from now on is a no-op.
tasks().lock().expect("tasks mutex poisoned").remove(&id);
deliver(&callback, result);
});
map.insert(id, join.abort_handle());
id
}
/// Runs on a Tokio worker thread. Attaches it to the JVM, then calls
/// FetchCallback.onSuccess or FetchCallback.onError on the Kotlin side.
fn deliver(callback: &GlobalRef, result: Result<String, String>) {
let vm = JVM.get().expect("JavaVM must be stored in JNI_OnLoad");
// Permanent attach: the worker stays attached until the thread exits,
// so later callbacks from this thread skip the attach cost entirely.
let mut env = match vm.attach_current_thread_permanently() {
Ok(env) => env,
Err(e) => {
log::error!("failed to attach Tokio worker to the JVM: {e}");
return;
}
};
let (method, text) = match result {
Ok(value) => ("onSuccess", value),
Err(message) => ("onError", message),
};
let payload: JObject = match env.new_string(text) {
Ok(s) => s.into(),
Err(e) => {
log::error!("failed to allocate Java string: {e}");
return;
}
};
if let Err(e) = env.call_method(
callback,
method,
"(Ljava/lang/String;)V",
&[JValue::Object(&payload)],
) {
log::error!("callback into Kotlin failed: {e}");
// If the Kotlin callback threw, clear the pending exception so it
// cannot poison the next JNI call made from this thread.
if env.exception_check().unwrap_or(false) {
let _ = env.exception_describe();
let _ = env.exception_clear();
}
}
}
#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_AsyncBridge_cancelFetch(
_env: JNIEnv,
_this: JObject,
id: jlong,
) {
if let Some(abort) = tasks().lock().expect("tasks mutex poisoned").remove(&id) {
abort.abort();
}
}
global reference ไม่ใช่ตัวเลือก อาร์กิวเมนต์ทุกตัวที่ส่งเข้าเมธอดเนทีฟเป็น local reference ใช้ได้เฉพาะระหว่างคำเรียกนั้นบนเธรดนั้น ตามเอกสาร Android ทาสก์อยู่เกินคำเรียกโดยการออกแบบ ดังนั้นมันต้องมีการย้าย new_global_ref ที่อธิบายละเอียดใน ตอนที่ 7 เรื่องการจัดการหน่วยความจำ JNI crate jni ปิดวง: เมื่อทาสก์ดรอป GlobalRef crate จะลบ global reference ของ JNI โดย attach เธรดก่อนถ้าจำเป็น
การ attach ถาวรดีกว่าการ์ดตรงนี้ crate jni มีสามรส attach_current_thread คืนการ์ดที่ detach ตอนดรอป: ถูกต้อง แต่เวิร์กเกอร์อายุยาวจะทำท่า attach ซ้ำ และการสร้าง java.lang.Thread ของมัน ทุก callback attach_current_thread_permanently attach ครั้งเดียวและ detach อัตโนมัติเมื่อเธรดจบ ซึ่งเป็นไปตามกฎ detach ก่อนออก ตัวแปร daemon คือ attach_current_thread_as_daemon เปลี่ยนแค่พฤติกรรมตอน JVM ปิด และ Android ฆ่าโปรเซสแทนการปิด VM ดังนั้นมันแทบไม่สำคัญในแอป สำหรับพูล Tokio ที่ขนาดคงที่ การ attach ถาวรคือค่าเริ่มต้นที่ถูก
การยกเลิกผ่าน id ไม่ใช่พอยน์เตอร์ ผมส่งพอยน์เตอร์ดิบ Box::into_raw ของ AbortHandle ให้ Kotlin ได้ แต่การยกเลิกที่แข่งกับการจบปกติจะกลายเป็นคำถาม double-free แมป Mutex ทำให้ทั้งสองการแข่งน่าเบื่อ: ยกเลิกหลังจบแล้วไม่พบอะไร และการจบหลังยกเลิกไม่รัน เพราะ abort ดรอป future ที่จุด await ถัดไป callback ไม่ถูกยิง global reference ถูกปล่อย
การประกาศ Kotlin ที่คู่กันอยู่ใน app/src/main/java/dev/davthecoder/rustseries/AsyncBridge.kt:
package dev.davthecoder.rustseries
interface FetchCallback {
fun onSuccess(payload: String)
fun onError(message: String)
}
object AsyncBridge {
init {
System.loadLibrary("async_bridge")
}
external fun startFetch(name: String, callback: FetchCallback): Long
external fun cancelFetch(handle: Long)
}
การสะพาน callback เข้าคอร์รูทีนของ Kotlin
อินเทอร์เฟซ callback เป็น API ที่ใช้ได้ และเป็น API ที่ลำบาก ผู้เรียกฝั่ง Kotlin อยากได้ฟังก์ชัน suspend และ suspendCancellableCoroutine คือตัวแปลงมาตรฐานสำหรับสถานการณ์นี้พอดี: API แบบครั้งเดียว ที่เป็น callback และรองรับการยกเลิก (kotlinx.coroutines docs) ตัวห่ออยู่ใน app/src/main/java/dev/davthecoder/rustseries/FetchGreeting.kt:
package dev.davthecoder.rustseries
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
class RustFetchException(message: String) : Exception(message)
suspend fun fetchGreeting(name: String): String =
suspendCancellableCoroutine { continuation ->
val handle = AsyncBridge.startFetch(name, object : FetchCallback {
override fun onSuccess(payload: String) {
continuation.resume(payload)
}
override fun onError(message: String) {
continuation.resumeWithException(RustFetchException(message))
}
})
continuation.invokeOnCancellation {
AsyncBridge.cancelFetch(handle)
}
}
onSuccess รันบนเวิร์กเกอร์ Tokio การ resume ตรงนั้นปลอดภัยเพราะ continuation ส่งคอร์รูทีนกลับไปที่ dispatcher ของมัน โค้ดหลังจุดแขวนรันที่ที่บริบทของผู้เรียกบอก โดยทั่วไปคือ Dispatchers.Main ใน ViewModel คุณไม่แตะวิวจาก callback และไม่จำเป็นต้องแตะ
สโคปของผู้เรียกตาย structured concurrency ยกเลิกคอร์รูทีน invokeOnCancellation ยิงและเรียก cancelFetch Rust เอา abort handle ออกแล้วยกเลิกทาสก์ และ callback ไม่มาถึง ถ้า callback อยู่ระหว่างทางอยู่แล้ว การรับประกันการยกเลิกทันทีครอบคลุมคุณ: เมื่อจ็อบถูกยกเลิก คอร์รูทีนจะไม่ resume สำเร็จ แม้ resume จะถูกเรียกไปแล้ว ทั้งสองลำดับจบอย่างเงียบ ถ้าเครื่องจักร Job ใต้ประโยคนั้นยังพร่ามัว บทความของผมเรื่อง ชนิดของ Job ในคอร์รูทีนของ Kotlin ครอบคลุมไว้
การใช้งานตอนนี้แยกไม่ออกจากการเรียก suspend อื่น จาก app/src/main/java/dev/davthecoder/rustseries/GreetingViewModel.kt:
package dev.davthecoder.rustseries
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
class GreetingViewModel : ViewModel() {
fun load() {
viewModelScope.launch {
val message = try {
fetchGreeting("David")
} catch (e: RustFetchException) {
"Rust said no: ${e.message}"
}
// message arrives on the main dispatcher, ready for UI state.
}
}
}
เมื่อ ViewModel นี้ถูกล้าง viewModelScope ยกเลิกคอร์รูทีน และทั้งโซ่คลายลงไปถึง Tokio โดยไม่ต้องมีโค้ดอีกบรรทัด: การรับรู้ไลฟ์ไซเคิลได้ฟรี ฝั่ง Rust ของขอบเขต
กฎที่กันคุณออกจาก tombstone
- อย่าแคช
JNIEnvเด็ดขาด ไม่ใน static ไม่ใน struct ไม่ข้ามเธรด เก็บJavaVMแล้วสร้าง env ในที่ที่ต้องการ ขอบเขตSendของ crate jni บังคับสิ่งนี้ - ทำ global ref ให้ทุก
jobjectที่อยู่เกินคำเรียกหรือเปลี่ยนเธรด local ตายพร้อมคำเรียกที่สร้างมัน ไม่ว่าอ็อบเจกต์ข้างใต้จะทำอะไร ตอนที่ 7 เรื่องชนิด reference ของ JNI และการรั่ว ครอบคลุมสวนสัตว์ของ reference ทั้งหมด - เธรดที่ attach แล้วต้อง detach ก่อนออก ใช้การ์ดสำหรับเธรดอายุสั้น และการ attach ถาวรสำหรับพูล และปล่อยให้ crate jni เป็นเจ้าของบัญชีในทั้งสองกรณี
- runtime เดียว สร้างครั้งเดียว ไม่เคยปิด ปฏิบัติกับมันเหมือนทรัพยากรระดับโปรเซสอย่างที่มันเป็น
- ถือว่า callback ลงบนเธรดต่างชาติ ให้ dispatcher ของคอร์รูทีนเป็นคนกระโดดเธรด callback ที่แตะสถานะ UI ตรงๆ คือบั๊กที่รออุปกรณ์ช้ามาพิสูจน์
หมายเหตุ panic หนึ่งข้อเพื่อปิดวงกับ ตอนที่ 8 เรื่องการจัดการข้อผิดพลาดและ panic: panic ภายในทาสก์ Tokio ที่ถูก spawn ไม่ข้ามขอบเขต JNI เพราะ runtime จับมันแล้วรายงานผ่าน JoinHandle ซึ่งการออกแบบนี้ดรอปทิ้ง ความเงียบนั้นคือเหตุที่ panic hook ไป logcat จากตอนที่ 8 ยังบังคับที่นี่ และถ้าโปรไฟล์ release ตั้ง panic = "abort" ยิ่งเป็นสองเท่า: panic ของทาสก์จะฆ่าโปรเซสตรงๆ
คำถามที่พบบ่อย
Tokio แชร์เธรดพูลกับคอร์รูทีนของ Kotlin ได้ไหม?
ไม่ได้ และไม่ควรพยายาม เวิร์กเกอร์ Tokio กับ dispatcher ของคอร์รูทีนเป็นคนละพูล คนละตัวจัดตาราง และสะพานระหว่างพวกมันคือ callback บวก continuation ไม่ใช่ executor ที่ใช้ร่วมกัน ให้พูล Tokio เล็ก เพื่อให้สอง runtime ไม่แย่งคอร์ที่เธรดของ Android เองก็ต้องการ
UniFFI จัดการ async ของ Rust ให้ไหม?
ส่วนใหญ่ใช่ UniFFI เปิด async fn เป็นฟังก์ชัน suspend ของ Kotlin ได้ตรงๆ ซึ่งเอาการเดินท่อ callback และ continuation ของบทความนี้ออก (UniFFI futures docs) เอกสารของมันบอกว่าการยกเลิกไม่ได้ถูกสร้างมาในตัว ดังนั้นเส้นทางยกเลิกอย่างรีจิสทรี abort ของบทความนี้ยังเป็นงานของคุณ ตอนที่ 3 เรื่องบิดดิง UniFFI ครอบคลุมว่า UniFFI เข้าที่ไหนโดยรวม
บทความถัดไปเอาหลักเธรดเหล่านี้ไปที่ที่ให้อภัยน้อยกว่ามาก ตอนที่ 10 DSP เสียงความหน่วงต่ำด้วย Rust: AAudio และ Oboe จากคอร์ Rust วาง Rust บนเธรดเสียง ที่ซึ่งการบล็อกและการจัดสรรหน่วยความจำถูกห้าม และแม้ JNI ก็ไม่อยู่บนโต๊ะ ถ้าคุณมาถึงตรงนี้กลางชุด บทความฮับ มีแผนที่ทั้งสิบห้าตอน
แหล่งที่มา
- Android Developers, “JNI tips”, เข้าถึงเมื่อ 2026-07-23, https://developer.android.com/training/articles/perf-jni
- docs.rs, jni crate 0.21 API documentation, เข้าถึงเมื่อ 2026-07-23, https://docs.rs/jni/0.21.1/jni/
- docs.rs, tokio runtime Builder documentation, เข้าถึงเมื่อ 2026-07-23, https://docs.rs/tokio/latest/tokio/runtime/struct.Builder.html
- kotlinx.coroutines API documentation, suspendCancellableCoroutine, เข้าถึงเมื่อ 2026-07-23, https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/suspend-cancellable-coroutine.html
- Mozilla, UniFFI async/futures documentation, เข้าถึงเมื่อ 2026-07-23, https://mozilla.github.io/uniffi-rs/latest/futures.html

Loading comments…Cargando comentarios…กำลังโหลดความคิดเห็น…