Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Structured Concurrency in Java: The what and the why

Balkrishna Rawool
July 01, 2023
49

Structured Concurrency in Java: The what and the why

Balkrishna Rawool

July 01, 2023
Tweet

Transcript

  1. 3 Project Loom Purpose: Ø Supporting easy-to-use, high-throughput lightweight concurrency

    and new programming models for it Features: Ø Virtual Threads: It will be finalized in Java 21 JEP - 444 Ø Structured Concurrency: Preview – JEP - 453 Ø Scoped Values: Preview – JEP - 446
  2. 4 (Platform) Threads JVM OS Platform Threads Platform Threads: Ø

    Abstraction over OS threads Ø Limited scalability (when using thread-per-request model) Ø Need for pooling
  3. 5 Virtual Threads JVM OS Platform Threads Virtual Threads: Ø

    Lightweight user threads Ø Highly scalable Ø No need for pooling Virtual Threads
  4. 8 Virtual Threads continued… PT 1 VT 1 VT 2

    VT 3 VT 4 VT 1 VT 1 VT 2 VT 2 VT 3 VT 3 VT 4 VT 4 VT 1 VT 2 VT 3 VT 1 VT 2 VT 4 VT 3 VT 4
  5. 12 Structured Concurrency: Continued Principle: Ø When flow of execution

    splits into multiple concurrent flows, they rejoin in the same code block Benefits: Ø Error handling with short-circuiting Ø Cancellation propagation Ø Clarity Ø Observability
  6. 14 CompletableFuture Ø Provides API for asynchronous processing Ø Chain

    multiple stages to create pipeline Ø Callbacks
  7. 17 Use case 2: Weather Service Get Weather From Source

    1 Get Weather From Source 2 Get Weather From Source 3
  8. 18 Use case 1: Banking Portal Get Savings Data Get

    Loans Data Get Customer Data Calculate Offer
  9. 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 Extend StructuredTaskScope Override handleComplete() Useful when you want custom logic/ some tasks to complete successfully 19
  10. Be aware of Pinning! 20 Ø When virtual thread is

    executing a synchronized code-block or method, it gets pinned Ø Problem if you’re doing long-running/ blocking operations inside synchronized Ø Identify cases with JFR (JDK Flight Recorder) Ø Use re-entrant lock