Yielding control in Java asynchronous code

77 views Asked by At

I come from a Rust/C#/Javascript background for asynchronous programming, and trying to understand comparable Java idioms. Specifically, I'm trying to understand whether there's a "green threads" model, in which a task runs on a thread, and once it reaches a point where it waits on I/O, it suspends itself (in other languages it would be represented by the await or suspend keywords) and allows another task to run.

From what I see, CompletableFuture can run asynchronously, but it doesn't release the thread that runs it - if you execute 1000 futures concurrently, you'll need 1000 threads, or depending on your executor, you might use less threads, but you'll also execute less tasks concurrently.

Are there other mechanisms that allow me to perform a large amount of concurrent I/O operations with a limited number of threads? Maybe Kotlin's Coroutines, or Virtual Threads (I prefer not to rely on Virtual Threads, since they require a relatively new version of Java)?

To clarify - I'm looking for an answer that can be exposed to any JVM application, regardless of language. So I don't care about language implementation, only that the API doesn't bind the caller to the language by some assumption.

2

There are 2 answers

1
Fabian Andres Aspee Encina On

If your I/O operation are small as a task you can use fork/join https://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html

0
ODDminus1 On

Virtual threads is what you're looking for within the JDK itself.

Otherwise project-reactor, popularly through spring-webflux achieves the same, but by introducing a declarative code style.