Introduction and pitfalls of Java's new concurrency model by David Vlijmincx

Explore the introduction and pitfalls of Java's new concurrency model, including virtual threads and structured concurrency, and discover how they can simplify thread management and provide a clear path for shutdown and failure.

Key takeaways
  • Concurrency is about managing threads as a single unit of work, not replacing existing way of threading.
  • Virtual threads are an alternative implementation of the thread class, not a replacement.
  • They run on a carrier thread, which is a platform thread managed and scheduled by the operating system.
  • Virtual threads are lighter and cheaper to create, using a stack size of 256KB or 1MB by default.
  • They can scale to 100,000 or more without consuming a significant amount of memory.
  • They can be used with structured concurrency, which simplifies the process of managing threads.
  • Structured concurrency helps to manage threads as a single unit of work and provides a clear path for shutdown and failure.
  • It is implemented using the structured task scope, which has two shutdown policies: shutdown on success and shutdown on failure.
  • The StructuredTaskScope class provides a way to manage threads and provides a shutdown policy.
  • Virtual threads can be used with the structured concurrency mechanism, which simplifies the process of managing threads.
  • They can be used to create a task for every virtual thread, which can be submitted to a ThreadPoolExecutor.
  • The ThreadPoolExecutor class provides a way to manage a pool of threads and execute tasks asynchronously.
  • Virtual threads can be used with the Future class, which provides a way to get the result of a task.
  • Structured concurrency makes it easy to manage threads and provides a clear path for shutdown and failure.
  • It simplifies the process of managing threads and makes it easier to write concurrent code.
  • Virtual threads are still in development and are expected to be part of the standard library in Java 21.