From the course: Java 25 for Professionals with Jetbrains AI Assistant
Safe data sharing with scoped values - Java Tutorial
From the course: Java 25 for Professionals with Jetbrains AI Assistant
Safe data sharing with scoped values
- Sometimes you want to share a little piece of information with all methods that get called while your program runs. For example, a user ID, a request ID, or some other context value that you want to log everywhere. For example, a request ID, a user ID, or some other context value that you want to log everywhere. Of course, you could pass it down as a parameter to every method. However, that is not very pretty and it clutters your code. Java 25 introduces a clean, new tool for this, ScopedValue. A ScopedValue is really like a temporary and read-only sticky notes. You can pin a value for the duration of a block of code and every method you call inside that block can read it. When the block ends, the sticky note disappears automatically and you don't accidentally leak the value to code that has no business knowing that value. This might sound somewhat complex, so just let me show you. Here's how to use it. The first step is define a ScopedValue. I'm doing this on line nine. I'm saying ScopedValue.newInstance and I'm storing it in a variable called REQUEST_ID. Then step two of my main method, I'm binding a value for the scope. In this case, the scope is handling a request. The first time, it is request 42 as ID, and the second time, request 43. On handleRequest, I'm calling two methods, a method log and a method doWork. The method log is using the request ID and so is the method doWork because it is calling the log method as well, but then we're doing work instead. And if I run this, you can see that it has access to REQUEST_ID with the value that I was binding for the duration. So first it is 42 and the second time it is 43. Before ScopedValue, the usual way to go was ThreadLocal. ThreadLocal lets you stick values to a thread so they could be read later without passing them in as parameters. But the ThreadLocals were error-prone. Why? Well, you had to remember to clear them or the values would leak into the next request, and they didn't fit in well with the newer concurrency models, especially virtual threads. And that's why ScopedValue is awesome because it fixes this. The value is bound for a block of code and automatically cleaned up afterwards, and it's read-only so you don't get weird accidental overrides. So the next time you find yourself passing the same context variable through a long chain of methods, with Java 25, you can use a ScopedValue instead. It's safer, cleaner, and easier to use.