In Java, Scoped variables enable the exchange of immutable data across and between threads. This new API is implemented as an incubator preview feature in Java 20 as part of JEP 439. They are preferred over thread-local variables, especially when a large number of virtual threads are used. This is an API that is still in development.
What is Scoped Value?
Scoped values are method parameters that allow disconnected methods to send arbitrary objects without the need for input from the user. They are immutable, thread-safe, and can be shared by many threads without synchronization when implemented as public static fields. Parent threads send down scoped values to their child threads, making data transmission easier.
Syntax:
ScopedValue<String> KEY= ScopedValue.newInstance();
Example of Scoped Variable
Below is the implementation of the scoped method:
Java
// Java Program to implement
// Scoped Values
import java.util.function.Supplier;
// Driver Class
// with Scoped Values
public class ScopedValue<T> {
private T value;
private ScopedValue(){
// Private constructor to prevent external
// instantiation
}
public static <T> ScopedValue<T> newInstance(){
return new ScopedValue<>();
}
public void where(Runnable code) {
code.run();
}
public T get() { return value; }
public void set(T value) { this.value = value; }
// main function
public static void main(String[] args)
{
ScopedValue<String> MY_SCOPED_VALUE
= ScopedValue.newInstance();
MY_SCOPED_VALUE.where(() -> {
MY_SCOPED_VALUE.set("Hello, Scoped World!");
String scopedValue = MY_SCOPED_VALUE.get();
System.out.println(scopedValue);
});
}
}
OutputHello, Scoped World!
Why we need Scoped Values?
You may want to transfer data between distinct components of your software, such as a web framework and a database access layer, on occasion. For example, You may wish to share a user's identity or permissions between many request threads. Thread-local variables, which have different values for each thread, are one technique.
Problems with Thread Local Variables
- They are mutable, which means any code with access to them can change them. This can make it difficult to understand and debug your application.
- They have an infinite lifetime, which means they will remain in memory until the thread is killed unless you manually remove them. Memory leaks are possible if they are not removed or if multiple threads inherit them from their parent threads.
- Because they are expensive to inherit, each child thread must allocate memory for each thread-local variable set by its parent thread. This can add a lot of expense when there are a lot of threads.
Advantages of Scoped Values
- Immutability: Scoped values are immutable, which means they cannot be changed once bounded. Concurrency difficulties are avoided, and the code is more reliable and logical as a result. Scoped values are optimized for both single-threaded and multi-threaded applications.
- Inheritance: Child threads can inherit scoped values. This allows data to be exchanged between parent and child threads without having to directly send it.
- Scoped values can help to enhance code readability and maintainability by containing data and reducing the amount of code that must be passed around as arguments.
- Performance: By decreasing the work related to data sharing between threads, scoped values can help improve the performance of concurrent applications.
- Concurrency errors: By containing data and providing an ordered way of sharing it between threads, scoped values reduce the risk of concurrency difficulties such as race situations and data corruption.
Disadvantages of Scoped Values
- New feature: Because scoped values are a newer feature in Java, they have less documentation and support than more established features.
- Complexity: Scoped values can complicate coding, particularly for those who are unfamiliar with them.
- Performance overhead: Scoped values might cause some performance overhead, especially in high-concurrency applications. This overhead, however, is usually insignificant.
Similar Reads
Scope of Variables in Java The scope of variables is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e., scope of a variable can be determined at compile time and independent of the function call stack. In this article, we will learn about
7 min read
Static Variables in Java In Java, when a variable is declared with the static keyword. Then, a single variable is created and shared among all the objects at the class level. Static variables are, essentially, global variables. All instances of the class share the same static variable. These are the main scenarios when we u
3 min read
HashMap values() Method in Java The java.util.HashMap.values() method of HashMap class in Java is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the HashMap. Syntax: Hash_Map.values() Parameters: The method does not accept any parameters. Return Value: The method i
2 min read
var keyword in Java The var reserved type name (not a Java keyword) was introduced in Java 10. Type inference is used in var keyword in which it detects automatically the datatype of a variable based on the surrounding context. The below examples explain where var is used and also where you can't use it. 1. We can decl
4 min read
Using Static Variables in Java Here we will discuss the static variables in java. Java actually doesnât have the concept of Global variable. To define a Global variable in java, the keyword static is used. The advantage of the static variable is discussed below. Now geeks you must be wondering out what are the advantages of stati
3 min read