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

Continuations The Magic Behind Virtual Threads

Continuations The Magic Behind Virtual Threads

Balkrishna Rawool

January 10, 2024
Tweet

More Decks by Balkrishna Rawool

Other Decks in Technology

Transcript

  1. 4 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
  2. Continuation 8 Ø A continuation can be viewed as Ø

    a representation of the current state of the program
  3. Continuation 9 Ø A continuation can be viewed as Ø

    a representation of the current state of the program or Ø ‘the rest of the computation’ Ø It allows us to pause execution of a program (or part thereof) and resume it later. Ø WARNING: Continuation API in Java is not supposed to be used directly by application developers. For now, it is only used internally to implement virtual threads.
  4. Continuations in Java 12 Continuation.yield() yield() d() c() b() run()

    a() main() Stack Heap d() c() b() run() a() main() Stack Heap yield()
  5. Continuations in Java 13 Continuation.run() c() b() run() a() main()

    Stack Heap d() c() b() run() a() main() Stack Heap yield() yield() d()
  6. Uses of continuations 14 Ø Green threads or virtual threads

    Ø Coroutines Ø Exception handling Ø Generators
  7. Generator 15 Ø A generator allows us to write a

    function that ‘yields’ values. Ø These values are lazily retrieved. Ø They can then be iterated over by using a loop. { //… //… yield 1; //… //… yield 2; //… //… yield 3; //… //… yield 4; } Generator while () { // … } Consumer
  8. Simple VirtualThread 18 Ø Goals Ø A VirtualThread instance should

    not use CPU (or platform thread) when waiting/ blocking. Ø A VirtualThread can get mounted on several platform threads during its lifetime. Ø A platform thread can support several VirtualThread-s during its lifetime.