SlideShare uma empresa Scribd logo
1 de 47
Project Loom
OR
How to Be Happy With Blocking
Code
@AndriiRodionov
https://blog.softwaremill.com/synchronous-or-asynchronous-and-why-wrestle-with-wrappers-2c5667eb7acf
https://www.baeldung.com/thread-pool-java-and-guava
BlockingQueue
Blocking request processing!
Problems
Problems
• Wasting thread-pool threads
• Wasting memory
Solutions
• Add more threads to thread pool?
• To be non-blocking?
• Project Loom?
Million Threads Baby
Why it fails?
Non-blocking request processing
McDonald's Kiosks
What means to be non-blocking
• An “event” should trigger a code execution -
callback
• How we can describe or register this callback?
– Callbacks
– Wrappers
– Coroutines
https://blog.softwaremill.com/synchronous-or-asynchronous-and-why-wrestle-with-wrappers-2c5667eb7acf
Future -> CompletableFuture
Java 5:
• Future<T>.get() - blocking
Java 8:
• CompletableFuture<T>.thenApply(...).... - non-blocking
• ~70 CompletableFuture methods to be non-blocking
Code readability
• Statements is now encoded as method calls
HttpClient.newBuilder()
.build()
.sendAsync(request,
HttpResponse.BodyHandlers.ofString())
.thenAccept(response -> . . .);
.thenApply(. . .);
.exceptionally(. . .);
• If we loved this style of programming, we would not have statements
in our programming language and code in Lisp
To be Reactive or not to be?
• If your Spring MVC application works fine - don’t touch!
• Imperative programming is the easiest way to write,
understand, and debug code
• Reactive and non-blocking generally do not make
applications run faster
Spring-framework-reference
To be Reactive or not to be?
• Reactive in some cases (WebClient to execute remote calls in
parallel) can make applications faster
• On the whole, it requires more work and can increase slightly
the required processing time
To be Reactive or not to be?
The key benefit of reactive and non-blocking is:
• the ability to scale with a small,
• fixed number of threads
• and less memory
Back to Green threads
Green Threads
– class Thread - @since 1.0
– M to N (M:1) mapping
– Threads scheduling - Java
– stop(), destroy(), resume(), suspend()
– When a green thread blocked, its carrier thread was also
blocked, preventing all other green threads from making
progress
– Loom is a (partial) return to the idea of green threads
https://www.youtube.com/watch?v=oBMZc2VMujw
class Thread
– At Sun’s Solaris OS with Java 1.2/1.3 - 1:1 threads mapping
– Threads scheduling - OS
– stop(), destroy(), resume(), suspend()
• @Deprecated(since="1.2", forRemoval=true)
– In 1998 the Sun Java Web Server (the precursor of Tomcat)
run each request in a separate thread, and not an OS process
– Able to serve thousands of concurrent requests this way
https://www.youtube.com/watch?v=oBMZc2VMujw
1:1 costs
• Native thread creation time
– Native thread
• Thread stack size - 1-2Mb
• Native threads time-slice scheduling
– Context switching (Memory/Cache/Registers)
Problems with blocking
Imperative programming
Problems:
• Wasting thread-pool threads
• Wasting memory
Project Loom way:
• Do not use thread pool
• Make thread instantiation fast
• Do not consume much memory
Virtual threads
• Exists only in Java runtime
– no 1-to-1 wrappers over OS threads
• Creating a virtual thread is cheap and fast
– they should never be pooled
– no OS-level data structures for the stack - no memory wasting
• Blocking a virtual thread is cheap
• Threads scheduling - Java
– no OS context switching
https://www.youtube.com/watch?v=oBMZc2VMujw
Carrier threads
• Virtual threads must be attached to OS thread to execute
• Carrier threads - OS threads upon which a virtual thread
executes
• Over virtual thread lifetime, a single virtual thread may
run on several different carrier threads
• When a virtual thread blocks (when a blocking call such as
I/O is made), it is “parked” and another virtual thread runs
on the carrier thread
https://lukstei.com/2020-07-25-a-first-look-into-the-project-loom-in-java/
Virtual thread 1
…
parked/blocked
Virtual thread 2
…
Virtual thread 1
…
Carrier
Thread 1
Carrier
Thread 2
Stack is saved
Stack is restored,
execution continues
Time
Carrier threads
Virtual thread creation
• class Thread
Thread thread = Thread.startVirtualThread(runnable);
• unbounded executor -
ExecutorService exec =
Executors.newVirtualThreadExecutor();
exec.submit(runnable1);
exec.submit(runnable2);
Demo
1M threads example
Sleeping threads
https://blog.softwaremill.com/synchronous-or-asynchronous-and-why-wrestle-with-wrappers-2c5667eb7acf
Virtual threads scheduler
• The default scheduler is the work-stealing scheduler from
ForkJoinPool
• Work-stealing schedulers work well for threads involved:
– that normally process in short bursts and block often
• Long running (without blocking) virtual threads can be pinned
to its carrier
– none of the existing schedulers for virtual threads uses
time slices to preempt virtual threads
Demo
Pinned threads
STRUCTURED CONCURRENCY
• When multiple threads run without coordination, it’s spaghetti
code
• Should use different approach to coordinate them
• In the 1960s, structured programming replaced goto with branches,
loops, and functions
STRUCTURED CONCURRENCY
• Structured concurrency should do the same for concurrent tasks
• We should know, from reading the program text, when they all
finish
https://vorpus.org/blog/notes-on-structured-concurrency-or-
go-statement-considered-harmful
Demo
Structured concurrency
try(var ex = Executors.newVirtualThreadExecutor()) {
ex.submit(() -> run());
ex.submit(() -> run());
} // Blocks and waits
Open questions
• Thread local
• Thread dump
• Threads communication
– BlockingQueue
– Channel (Carrier)
• Structured concurrency
• Supported API
– https://wiki.openjdk.java.net/display/loom/Blocking+Operations
– except synchronized/wait/notify and local file I/O operations
Cheap threads
can do expensive things
1M virtual threads illusion
• Loom does allow you to have many threads, even 1,000,000 threads,
• but ...
• not if those threads have deep stacks
Stack Trace From Hell
https://dzone.com/articles/filtering-
stack-trace-hell
1M virtual threads illusion
For deep stack it increase
• total memory usage for stack entries and
• also comes at a cost of long garbage collections
https://webtide.com/do-looms-claims-stack-up-part-1/
Why Thread Pools?
- Why Small Thread Pools?
- We can create up to 50K native threads in a pool!
- A limited thread pool is a coarse grained limit on all
resources, not only threads
- Limiting the number of threads puts a limit on concurrent
lock contention, memory consumption and CPU usage
https://webtide.com/do-looms-claims-stack-up-part-2/
Conclusion
• blocking code is much easier to write
• virtual threads are very fast to start and cheap to block
• for “real world tasks” we should anyway limit the number of
virtual threads
1994
“He (Bill Joy) would often go on at length about how
great Oak would be if he could only add closures and
continuations and parameterized types”
“While we all agreed these were very cool language
features, we were all kind of hoping to finish this
language in our lifetimes and get on to creating cool
applications with it”
“It is also interesting that Bill was absolutely right about
what Java needs long term. When I go look at the list of
things he wanted to add back then, I want them all. He
was right, he usually is”
Patrick Naughton,
one of the creators of the Java
To read
• https://inside.java/tag/loom
• https://www.javaadvent.com/2020/12/project-loom-and-
structured-concurrency.html
• https://blogs.oracle.com/javamagazine/going-inside-javas-project-
loom-and-virtual-threads
• https://blog.softwaremill.com/will-project-loom-obliterate-java-
futures-fb1a28508232
• https://webtide.com/do-looms-claims-stack-up-part-1/
• https://vorpus.org/blog/notes-on-structured-concurrency-or-go-
statement-considered-harmful/
Comparing APIs
API Type No value Single value Multiple values
Standard Java –
Synchronous APIs
void T Iterable<T>
Standard Java –
Asynchronous APIs
CompletableFuture
<Void>
CompletableFuture
<T>
CompletableFuture
<List<T>>
Project Reactor
implementation of
Reactive Streams
Mono<Void> Mono<T> Flux<T>
https://devblogs.microsoft.com/azure-sdk/async-programming-with-project-reactor/

Mais conteúdo relacionado

Mais de GlobalLogic Ukraine

GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Ukraine
 

Mais de GlobalLogic Ukraine (20)

GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
 
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
 
“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?
 
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
 
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
 
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
 
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
 
GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"
 
C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"
 
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
 
GlobalLogic Azure TechTalk ONLINE “Marketing Data Lake in Azure”
GlobalLogic Azure TechTalk ONLINE “Marketing Data Lake in Azure”GlobalLogic Azure TechTalk ONLINE “Marketing Data Lake in Azure”
GlobalLogic Azure TechTalk ONLINE “Marketing Data Lake in Azure”
 
GlobalLogic Test Automation Online TechTalk “Playwright — A New Hope”
GlobalLogic Test Automation Online TechTalk “Playwright — A New Hope”GlobalLogic Test Automation Online TechTalk “Playwright — A New Hope”
GlobalLogic Test Automation Online TechTalk “Playwright — A New Hope”
 
Java Webinar #13 “Where Is My Development Zone?”
Java Webinar #13 “Where Is My Development Zone?”Java Webinar #13 “Where Is My Development Zone?”
Java Webinar #13 “Where Is My Development Zone?”
 
NET Webinar #1 "Is There a Life Outside the Entity Framework"
NET Webinar #1 "Is There a Life Outside the Entity Framework"NET Webinar #1 "Is There a Life Outside the Entity Framework"
NET Webinar #1 "Is There a Life Outside the Entity Framework"
 
GlobalLogic С/C++/Embedded Live Coding Challenge. Basic graph algorithms
GlobalLogic С/C++/Embedded Live Coding Challenge. Basic graph algorithmsGlobalLogic С/C++/Embedded Live Coding Challenge. Basic graph algorithms
GlobalLogic С/C++/Embedded Live Coding Challenge. Basic graph algorithms
 
Online TechTalk “Flutter Mobile Development”
Online TechTalk “Flutter Mobile Development”Online TechTalk “Flutter Mobile Development”
Online TechTalk “Flutter Mobile Development”
 
Online TechTalk  "Patterns in Embedded SW Design"
Online TechTalk  "Patterns in Embedded SW Design"Online TechTalk  "Patterns in Embedded SW Design"
Online TechTalk  "Patterns in Embedded SW Design"
 
Сloud Webinar #1 “Architecture of Highly Loaded Geo-Distributed Applications”
Сloud Webinar #1 “Architecture of Highly Loaded Geo-Distributed Applications”Сloud Webinar #1 “Architecture of Highly Loaded Geo-Distributed Applications”
Сloud Webinar #1 “Architecture of Highly Loaded Geo-Distributed Applications”
 
Сloud Webinar #2: “PCI DSS Compliance: Getting Ready for the Certification”
Сloud Webinar #2: “PCI DSS Compliance: Getting Ready for the Certification”Сloud Webinar #2: “PCI DSS Compliance: Getting Ready for the Certification”
Сloud Webinar #2: “PCI DSS Compliance: Getting Ready for the Certification”
 

Último

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Último (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 

Project Loom or how to be happy with blocking code

  • 1. Project Loom OR How to Be Happy With Blocking Code @AndriiRodionov
  • 6. Problems • Wasting thread-pool threads • Wasting memory
  • 7. Solutions • Add more threads to thread pool? • To be non-blocking? • Project Loom?
  • 11. What means to be non-blocking • An “event” should trigger a code execution - callback • How we can describe or register this callback? – Callbacks – Wrappers – Coroutines
  • 13. Future -> CompletableFuture Java 5: • Future<T>.get() - blocking Java 8: • CompletableFuture<T>.thenApply(...).... - non-blocking • ~70 CompletableFuture methods to be non-blocking
  • 14. Code readability • Statements is now encoded as method calls HttpClient.newBuilder() .build() .sendAsync(request, HttpResponse.BodyHandlers.ofString()) .thenAccept(response -> . . .); .thenApply(. . .); .exceptionally(. . .); • If we loved this style of programming, we would not have statements in our programming language and code in Lisp
  • 15. To be Reactive or not to be? • If your Spring MVC application works fine - don’t touch! • Imperative programming is the easiest way to write, understand, and debug code • Reactive and non-blocking generally do not make applications run faster Spring-framework-reference
  • 16. To be Reactive or not to be? • Reactive in some cases (WebClient to execute remote calls in parallel) can make applications faster • On the whole, it requires more work and can increase slightly the required processing time
  • 17. To be Reactive or not to be? The key benefit of reactive and non-blocking is: • the ability to scale with a small, • fixed number of threads • and less memory
  • 18. Back to Green threads
  • 19. Green Threads – class Thread - @since 1.0 – M to N (M:1) mapping – Threads scheduling - Java – stop(), destroy(), resume(), suspend() – When a green thread blocked, its carrier thread was also blocked, preventing all other green threads from making progress – Loom is a (partial) return to the idea of green threads
  • 21. class Thread – At Sun’s Solaris OS with Java 1.2/1.3 - 1:1 threads mapping – Threads scheduling - OS – stop(), destroy(), resume(), suspend() • @Deprecated(since="1.2", forRemoval=true) – In 1998 the Sun Java Web Server (the precursor of Tomcat) run each request in a separate thread, and not an OS process – Able to serve thousands of concurrent requests this way
  • 23. 1:1 costs • Native thread creation time – Native thread • Thread stack size - 1-2Mb • Native threads time-slice scheduling – Context switching (Memory/Cache/Registers)
  • 24. Problems with blocking Imperative programming Problems: • Wasting thread-pool threads • Wasting memory Project Loom way: • Do not use thread pool • Make thread instantiation fast • Do not consume much memory
  • 25. Virtual threads • Exists only in Java runtime – no 1-to-1 wrappers over OS threads • Creating a virtual thread is cheap and fast – they should never be pooled – no OS-level data structures for the stack - no memory wasting • Blocking a virtual thread is cheap • Threads scheduling - Java – no OS context switching
  • 27. Carrier threads • Virtual threads must be attached to OS thread to execute • Carrier threads - OS threads upon which a virtual thread executes • Over virtual thread lifetime, a single virtual thread may run on several different carrier threads • When a virtual thread blocks (when a blocking call such as I/O is made), it is “parked” and another virtual thread runs on the carrier thread
  • 28. https://lukstei.com/2020-07-25-a-first-look-into-the-project-loom-in-java/ Virtual thread 1 … parked/blocked Virtual thread 2 … Virtual thread 1 … Carrier Thread 1 Carrier Thread 2 Stack is saved Stack is restored, execution continues Time Carrier threads
  • 29. Virtual thread creation • class Thread Thread thread = Thread.startVirtualThread(runnable); • unbounded executor - ExecutorService exec = Executors.newVirtualThreadExecutor(); exec.submit(runnable1); exec.submit(runnable2);
  • 32. Virtual threads scheduler • The default scheduler is the work-stealing scheduler from ForkJoinPool • Work-stealing schedulers work well for threads involved: – that normally process in short bursts and block often • Long running (without blocking) virtual threads can be pinned to its carrier – none of the existing schedulers for virtual threads uses time slices to preempt virtual threads
  • 34. STRUCTURED CONCURRENCY • When multiple threads run without coordination, it’s spaghetti code • Should use different approach to coordinate them • In the 1960s, structured programming replaced goto with branches, loops, and functions
  • 35. STRUCTURED CONCURRENCY • Structured concurrency should do the same for concurrent tasks • We should know, from reading the program text, when they all finish https://vorpus.org/blog/notes-on-structured-concurrency-or- go-statement-considered-harmful
  • 36. Demo Structured concurrency try(var ex = Executors.newVirtualThreadExecutor()) { ex.submit(() -> run()); ex.submit(() -> run()); } // Blocks and waits
  • 37. Open questions • Thread local • Thread dump • Threads communication – BlockingQueue – Channel (Carrier) • Structured concurrency • Supported API – https://wiki.openjdk.java.net/display/loom/Blocking+Operations – except synchronized/wait/notify and local file I/O operations
  • 38. Cheap threads can do expensive things
  • 39. 1M virtual threads illusion • Loom does allow you to have many threads, even 1,000,000 threads, • but ... • not if those threads have deep stacks
  • 40. Stack Trace From Hell https://dzone.com/articles/filtering- stack-trace-hell
  • 41. 1M virtual threads illusion For deep stack it increase • total memory usage for stack entries and • also comes at a cost of long garbage collections https://webtide.com/do-looms-claims-stack-up-part-1/
  • 42. Why Thread Pools? - Why Small Thread Pools? - We can create up to 50K native threads in a pool! - A limited thread pool is a coarse grained limit on all resources, not only threads - Limiting the number of threads puts a limit on concurrent lock contention, memory consumption and CPU usage https://webtide.com/do-looms-claims-stack-up-part-2/
  • 43. Conclusion • blocking code is much easier to write • virtual threads are very fast to start and cheap to block • for “real world tasks” we should anyway limit the number of virtual threads
  • 44. 1994 “He (Bill Joy) would often go on at length about how great Oak would be if he could only add closures and continuations and parameterized types” “While we all agreed these were very cool language features, we were all kind of hoping to finish this language in our lifetimes and get on to creating cool applications with it” “It is also interesting that Bill was absolutely right about what Java needs long term. When I go look at the list of things he wanted to add back then, I want them all. He was right, he usually is” Patrick Naughton, one of the creators of the Java
  • 45. To read • https://inside.java/tag/loom • https://www.javaadvent.com/2020/12/project-loom-and- structured-concurrency.html • https://blogs.oracle.com/javamagazine/going-inside-javas-project- loom-and-virtual-threads • https://blog.softwaremill.com/will-project-loom-obliterate-java- futures-fb1a28508232 • https://webtide.com/do-looms-claims-stack-up-part-1/ • https://vorpus.org/blog/notes-on-structured-concurrency-or-go- statement-considered-harmful/
  • 46.
  • 47. Comparing APIs API Type No value Single value Multiple values Standard Java – Synchronous APIs void T Iterable<T> Standard Java – Asynchronous APIs CompletableFuture <Void> CompletableFuture <T> CompletableFuture <List<T>> Project Reactor implementation of Reactive Streams Mono<Void> Mono<T> Flux<T> https://devblogs.microsoft.com/azure-sdk/async-programming-with-project-reactor/