Open In App

Scoped Values in Java

Last Updated : 29 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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);
        });
    }
}


Output

Hello, 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

  1. 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.
  2. Inheritance: Child threads can inherit scoped values. This allows data to be exchanged between parent and child threads without having to directly send it.
  3. 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.
  4. Performance: By decreasing the work related to data sharing between threads, scoped values can help improve the performance of concurrent applications.
  5. 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

  1. New feature: Because scoped values are a newer feature in Java, they have less documentation and support than more established features.
  2. Complexity: Scoped values can complicate coding, particularly for those who are unfamiliar with them.
  3. Performance overhead: Scoped values might cause some performance overhead, especially in high-concurrency applications. This overhead, however, is usually insignificant.

Frequently Asked Questions

1. What is jep 446 scoped values?

A scoped value enables data to be exchanged safely and effectively between methods in a big program without the need of method arguments. It is a ScopedValue type variable.

2. What is scoped value in Java 20?

Developers can use scoped values to store and communicate immutable data within and across threads. As an incubator preview feature proposed in JEP 439, this new API is implemented in Java 20.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads