232. Using ScopedValue and executor services
In Problem 230, we wrote an application that combines ThreadLocal
and executor services (we have used newVirtualThreadPerTaskExecutor()
and newFixedThreadPool()
).
In this problem, we re-write the code from Problem 230 in order to use ScopedValue
. First, we have the following Runnable
:
Runnable task = () -> {
logger.info(() -> Thread.currentThread().toString()
+ " | before sleep | " + (SCOPED_VALUE.isBound()
? SCOPED_VALUE.get() : "Not bound"));
try {
Thread.sleep(Duration.ofSeconds(new Random().nextInt(5)));
} catch (InterruptedException ex) {}
logger.info(() -> Thread.currentThread().toString()
+ " | after sleep | " + (SCOPED_VALUE.isBound()
? SCOPED_VALUE.get() : "Not bound"));
};
This code is straightforward. We retrieve the value mapped to SCOPED_VALUE
, we sleep from a random number of seconds (between 0 and 5), and we retrieve the value...