ThreadLocal Example with Java 8

Posted on Updated on

What is ThreadLocal in Java?

ThreadLocal is a specially provisioned functionality by JVM to provide an isolated storage space for threads only. like the value of instance scoped variable are bound to a given instance of a class only. each object has its only values and they can not see each other value. so is the concept of ThreadLocal variables, they are local to the thread in the sense of object instances other thread except for the one which created it, can not see it.

Like request, session and application scope of any Object, We can define a Thread Scope of any Object thus Object visibility would be only within the Thread and Every Thread has it execution life cycle, After a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

Although we usually create a Synchronize  Object for Thread safety in MultiThread application therefore only one Thread can be obtained a monitor to access shared Object Since shared Object is not thread safe.

In Java 8, A new method is introdued  to determine the initial value.

public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
    return new SuppliedThreadLocal<>(supplier);
}

Here, a simple ThreadLocal example of Java 8 is demonstrated that how each Thread gets own ThreadLocal copy of variable and value remain same even in Iteration process and each thread are executing separately on the ThreadLocal variable.

 

import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

/**
 * Created by MYPC on 5/29/2017.
 */
public class ThreadLocalExample {
    private static final AtomicInteger transactionId = new AtomicInteger(10000);
    private static final ThreadLocal threadLocal = ThreadLocal.withInitial(() -> transactionId.getAndIncrement());

    public static void main(String[] args) {

        // Thread 1 executing and getting same Transaction Id for all iteration
        new Thread(() -> IntStream.range(0, 3).forEach(val -> {
            System.out.println(Thread.currentThread().getName() + " > " + threadLocal.get());
        })).start();

        // Thread 2 executing and getting same Transaction Id for all iteration
        new Thread(() -> IntStream.range(0, 3).forEach(val -> {
            System.out.println(Thread.currentThread().getName() + " > " + threadLocal.get());
        })).start();
        // Thread 3 executing and getting same Transaction Id for all iteration
        new Thread(() -> IntStream.range(0, 3).forEach(val -> {
            System.out.println(Thread.currentThread().getName() + " > " + threadLocal.get());
        })).start();

    }
}
Execution Output :-

Thread-1 > 10001
Thread-1 > 10001
Thread-1 > 10001
Thread-0 > 10000
Thread-0 > 10000
Thread-0 > 10000
Thread-2 > 10002
Thread-2 > 10002
Thread-2 > 10002

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s