structured concurrency in java - loom
Purpose: supporting easy-to-use, high-throughput lightweight concurrency and new programming models to it
Platform threads:
- abstraction over OS threads
- limited scalability (when using thread-per-request model)
- need for pooling
Virtual threads:
- lightweight user threads
- highly scalable
- no need for polling
How to create virtual threads:
Benefits of structured concurrency:
- error handling with short-circuiting
- cancellation propagation
- clarity
- observability
CompletableFuture
vs structured concurrency
Get all
+--> reserVenue --+
| |
--+--> bookHotel ---+-->
| |
+--> buySupplies -+
CompletableFuture
example:
Structured concurrency example:
Get first
+--> getWeatherFromSource1 ---+
| |
--+--> getWeatherFromSource2 ---+-->
| |
+--> getWeatherFromSource3 ---+
CompletableFuture
example:
Structured concurrency example
Get then
CompletableFuture
example:
-> getCurrentCustomer +-> getSavingsData +--> calculateOffer
| |
+-> getLoansData --+
Structured concurrency example:
Shutdown policies
`ShutdownOnFailure
- stops when one of the tasks “fail”
- cancels other tasks
- useful when you want that all tasks must complete successfully
ShutdownOnSuccess
- stops when one of the tasks “succeed”
- cancels other tasks
- useful when you want any one of the tasks to complete successfully
Custom
- extends
StructuredTaskScope
- override
handleComplete
- useful when you want custom login / some tasks to complete successfully