Reader small image

You're reading from  Java Coding Problems - Second Edition

Product typeBook
Published inMar 2024
PublisherPackt
ISBN-139781837633944
Edition2nd Edition
Right arrow
Author (1)
Anghel Leonard
Anghel Leonard
author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard

Right arrow

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...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Java Coding Problems - Second Edition
Published in: Mar 2024Publisher: PacktISBN-13: 9781837633944

Author (1)

author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard