Skip to content

Instantly share code, notes, and snippets.

@diegopacheco
Last active February 9, 2024 00:07
Show Gist options
  • Save diegopacheco/a81e6dc67de5548c670f6d360304ed80 to your computer and use it in GitHub Desktop.
Save diegopacheco/a81e6dc67de5548c670f6d360304ed80 to your computer and use it in GitHub Desktop.
Java 21 - Virtual Threads Summary

Summary JVM Threads vs Vritual Threads

Threads

  • Threads are wrapper around OS Threads
  • Have a cost and consume memory
  • Can't have many, need a thread pool
  • Good for CPU Bound, not good for IO Bound.
  • 2k metadata, 1MB stack, 1-10us context switch

Code Sample (dont do this - use thread pools)

public class JDKThread extends Thread {
  public void run(){
     System.out.println("running");
  }
}
JDKThread thread = new JDKThread();
thread.start();

Virtual Threads (Green Threads)

  • Not 1:1 between Virtual/OS Threads (N:1 create millions of virtual threads)
  • Virtual thread blocks, does not block the OS thread
  • Virtual Threas are very good in waiting(suspend), it's a concurrency model like (Reactive programing, actors, STM). Make async looks like sync.
  • Massive nun of virtual threads can lead to large cache misses and GC work(ThreadLocal on many virutal threads).
  • Good for IO Bound, not good for CPU Bound(not pre-emptive - cant deschedulled while running).
  • 200-300B metadata, Allocated on the heap, bellow 1us context switch

Code Sample

Thread thread = Thread.ofVirtual().start(() -> System.out.println("Hello"));
thread.join();

Great Resources

About me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment