ThreadLocal in Java

Posted on by By Somen Sarkar, in ETL, Javascript, Services | 0

ThreadLocal

What is ThreadLocal?
There are different scope of a variable in java.
1. Local Scope : This scope includes the variable declared inside the methods.
2. Instance Scope: This scope is also known as instance variable. This is created one per instance.
3. Class Scope: The variable is created one per class. They are generally static
4. Thread Scope: The variable is available in thread scope using ThreadLocal.

ThreadLocal allows the java developer to store any variable or data in Thread scope. The treadlocal will take care that the data is only visible to thread. ThreadLocal thus helps to manage threadsaftey for an object/pojo across the thread without using the synchronous keyword.

How to keep data in ThreadLocal?
ThreadLocal provides set() method to store the data, and get() method to retrive the data. Using the getter and setter the manipulation can be done quite easily.

Generally ThreadLocal instances are private static fields in classes (e.g.,we may associate a user ID or Transaction ID etc).
Frameworks generally use threadlocal to store context related data.
Using Generics in ThreadLocal.
After java 1.5 we can use Generic notation in the ThreadLocal declaration.
eg. ThreadLocal<String> threadLocal = new ThreadLocal<String>();

Mehods in ThreadLocal.
1. protected T initialValue() : This can be used to set the intial value of threadlocal other than null.
2. public T get() : This is the getter method
3. public void set(T value): Setter method to set the value
4. public void remove(): This method clears the data from the thread local

 

 

Sample Code to illustrate the ThreadLocal

package com.helical;

import com.helical.model.User;

public class ThreadLocalExample {

    private static ThreadLocal threadContext = new ThreadLocal();

    public User getUser() {
        User user = threadContext.get();
        if (user == null) {
            throw new UserDoesNotExistsException("There is no user inside the ThreadLocal");
        } else {
            return user;
        }

    }

    public void setUser(User user) {
        User localUser = threadContext.get();
        if (localUser != null) {
            throw new UserExistsException("There is already  a user in ThreadLocal");
        } else {
            threadContext.set(user);
        }
    }

    public void clearThreadLocal() {
        threadContext.remove();
    }

    private class UserExistsException extends RuntimeException {
        public UserExistsException(String s) {
        }
    }
}
logo

Best Open Source Business Intelligence Software Helical Insight is Here

logo

A Business Intelligence Framework

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments