@backstreetbrogrammer
--------------------------------------------------------------------------------
Chapter 02 - Virtual Threads - Futures with Callbacks OMS
--------------------------------------------------------------------------------
One of the oldest strategies is the idea of a callback.
Instead of waiting for the result of a future, which requires blocking, the developer specifies, as a callback, the computation that will use this result.
The future thenAccept() method takes as its argument the code that will consume the output of the future.
Note that the invocation of thenAccept() only registers this code for later execution; it does not wait for the future to be completed and, thus, it takes very little time.
The actual object building will run later, in the thread pool, after the validation, enrichment and persistence tasks are done. As a result, a single request is processed in one second as before.
Threads are never blocked in this server, and a single, reasonably sized pool can be used.
The code above is free from deadlocks for any pool size.
Indeed, setting threadPool as a single-thread pool would result in a sequential server, but would not cause any deadlock.
However, still there is one caveat here:
- Callbacks are notoriously hard to write and even harder to debug.
In the simple callback illustration, thenAccept() calls are nested three levels deep.
Github: github.com/backstreetbrogramm...
- Upgrade to Java 21 Playlist: • Upgrade to Java 21
- Apache Spark for Java Developers Playlist: • Apache Spark for Java ...
- Top Java Coding Interview Problems Playlist: • Top Java Coding Interv...
- Java Serialization Playlist: • Java Serialization
- Dynamic Programming Playlist: • Dynamic Programming
#java #javadevelopers #javaprogramming
Негізгі бет Ғылым және технология 13 - Futures with Callbacks OMS
Пікірлер