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

Virtual Threads, Structured Concurrency and Sco...

Virtual Threads, Structured Concurrency and Scoped Values: Putting it all together

Avatar for Balkrishna Rawool

Balkrishna Rawool

May 26, 2025
Tweet

More Decks by Balkrishna Rawool

Other Decks in Technology

Transcript

  1. 2

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

    and new programming models for it Features: Ø Virtual Threads – Final in JDK 21 Ø Structured Concurrency – Preview Ø Scoped Values – Final in JDK 25
  3. 6 Platform Threads and Virtual Threads JVM OS Platform Threads

    Platform Threads: Ø Thin wrapper over OS threads Ø One-to-one mapping with OS threads Ø Thread pools Virtual Threads Virtual Threads: Ø Lightweight user threads Ø Highly scalable Ø No need for pooling
  4. 9 A simple web-app with virtual threads Ø SpringBoot App

    Ø SpringBoot 3.4 Ø JDK 25 (Project Loom early access build) Ø Domain: Banking Ø Name: A Bank
  5. 14 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. 16 Feature: Loan application Ø Customer applies for loan Ø

    Get customer details Ø Using customer details Ø Get accounts Ø Get loans Ø Get external credit scores Ø Two services provide this score Ø Response from one is enough Ø Aggregate all this info and send to offer-calculation service
  7. 17 Feature: Loan application Get Customer Details Get Account Details

    Get Loan Details Get Credit Score Calculate Offer Get Credit Score Get Credit Score 1 Get Credit Score 2
  8. ThreadLocal 19 Ø Each thread gets its own copy of

    the object. Ø Useful for Ø Request/session-specific data Ø Resource management (of non-thread-safe objects) Ø Caching Ø Observability (e.g. CorrelationID) Ø VirtualThread-s support ThreadLocal-s. Ø Problems Ø Unconstrained mutability Ø Unbounded lifetime Ø Expensive inheritance (with InheritableThreadLocal)
  9. Scoped Values 20 Ø Immutable Ø All (allowed) threads use

    the same copy Ø Inherited through the StructuredTaskScope to the child-virtual-threads Ø Bounded by the scope ScopedValue VALUE = ScopedValue.newInstance(); ScopedValue.where(VALUE, someValue) .run(() -> {...});