Sunday, April 14, 2024

Java Thread Local example

An example demonstrating the use of `ThreadLocal` variables in Java:


public class ThreadLocalExample {


    // Create a ThreadLocal variable to store a thread-specific value

    private static ThreadLocal<Integer> threadLocalValue = ThreadLocal.withInitial(() -> 0);


    public static void main(String[] args) {

        // Create and start multiple threads

        for (int i = 0; i < 3; i++) {

            Thread thread = new Thread(() -> {

                // Increment and print the thread-specific value

                int value = threadLocalValue.get(); // Get the thread-specific value

                value++; // Increment the value

                threadLocalValue.set(value); // Set the updated value back to the ThreadLocal variable

                System.out.println("Thread " + Thread.currentThread().getId() + ": Value = " + value);

            });

            thread.start();

        }

    }

}

In this example:


- We create a `ThreadLocal` variable named `threadLocalValue` to store an integer value. We initialize it with an initial value of `0` using the `ThreadLocal.withInitial()` method.


- We create three threads in a loop, each performing the following actions:

  - Get the current value stored in the `threadLocalValue` using the `get()` method.

  - Increment the value.

  - Set the updated value back to the `threadLocalValue` using the `set()` method.

  - Print the thread ID and the updated value.


When you run this code, you'll see that each thread maintains its own copy of the `threadLocalValue`, and the updates made by one thread do not affect the values seen by other threads. 

This demonstrates how `ThreadLocal` variables allow you to store and access thread-specific data in a thread-safe manner.

No comments:

Post a Comment

LeetCode C++ Cheat Sheet June

🎯 Core Patterns & Representative Questions 1. Arrays & Hashing Two Sum – hash map → O(n) Contains Duplicate , Product of A...