ThreadLocal in java

Posted By : Prakhar Verma | 08-Feb-2021

ThreadLocal is the part of java.lang package.

ThreadLocal is used to maintain an object variable as a local variable for each thread on a single object.

A ThreadLocal instance can be created as a variable that can only be read and written by the same thread. Thus, even if two threads are executing the same code, and the code has a reference to a ThreadLocal variable, then the two threads cannot see each other's ThreadLocal variables.

A ThreadLocal instance is used as a private static field in the class that wishes to associate state with a thread.

It is a small example showing the use of ThreadLocal in java and proving that every thread has it’s own copy of the ThreadLocal variable.

1. The Transaction is a class which holds the information related to the transaction with ThreadLocal.

 

package com.demo.thread;

import java.util.Date;
import java.util.Random;

public class Transaction implements Runnable{

	private static ThreadLocal<Integer> transactionId = new ThreadLocal<Integer>();

	private Random random = new Random();

	private Date createdAt;

	private String type;

	public Transaction(){}
	
	public Transaction(Date createdAt,String type){
		this.createdAt = createdAt;
		this.type = type;
	}

	@Override
	public void run() {

		synchronized (this) {
			System.out.println("CurrentThread Name is => "+Thread.currentThread().getName());
			transactionId.set(random.nextInt(100000));
			System.out.println(Thread.currentThread().getName()+" initialized the value of transactionId => "+transactionId.get()+" and going to sleep mode.");
		}
		try{

			Thread.sleep(3000);
			System.out.println(Thread.currentThread().getName()+" wake up from sleep mode and the value of transactionId is => "+transactionId.get());
		}catch (Exception e) {
			System.out.println("Exception is : "+e);
		}

	}

	public static ThreadLocal<Integer> getTransactionId() {
		return transactionId;
	}

	public static void setTransactionId(ThreadLocal<Integer> transactionId) {
		Transaction.transactionId = transactionId;
	}

	public Date getCreatedAt() {
		return createdAt;
	}

	public void setCreatedAt(Date createdAt) {
		this.createdAt = createdAt;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

}

 

2. The Main class is used to create the object of the Transaction class and create the multiple Threads of Transaction object.
 

package com.demo.thread;

import java.util.Date;

public class Main {


	public static void main(String[] args) {

		Transaction transaction = new Transaction(new Date(),"MoneyTransfer");
		
		Thread thread1 = new Thread(transaction,"Thread1");
		Thread thread2 = new Thread(transaction,"Thread2");
		Thread thread3 = new Thread(transaction,"Thread3");
		Thread thread4 = new Thread(transaction,"Thread4");
		Thread thread5 = new Thread(transaction,"Thread5");
		
		thread1.start();
		thread2.start();
		thread3.start();
		thread4.start();
		thread5.start();
		
	}


}

3. Here is the Output of the ThreadLocal example.

 

CurrentThread Name is => Thread1
Thread1 initialized the value of transactionId => 35809 and going to sleep mode.
CurrentThread Name is => Thread5
Thread5 initialized the value of transactionId => 47029 and going to sleep mode.
CurrentThread Name is => Thread4
Thread4 initialized the value of transactionId => 74065 and going to sleep mode.
CurrentThread Name is => Thread3
Thread3 initialized the value of transactionId => 35987 and going to sleep mode.
CurrentThread Name is => Thread2
Thread2 initialized the value of transactionId => 86975 and going to sleep mode.
Thread1 wake up from sleep mode and the value of transactionId is => 35809
Thread4 wake up from sleep mode and the value of transactionId is => 74065
Thread3 wake up from sleep mode and the value of transactionId is => 35987
Thread2 wake up from sleep mode and the value of transactionId is => 86975
Thread5 wake up from sleep mode and the value of transactionId is => 47029

Output Description => The Transaction class used only one ThreadLocal variable 'transactionId'.

The field 'transactionId' holds the separate values on the basis of multiple Threads.

In this output, There is five Threads (Thread1, Thread2, Thread3,Thread4 and Thread5) and each Thread set the value of 'transactionId' field.

Threads will going to sleep for 3 Seconds after set the value of 'transaction Id' field and each Thread print the same value of 'transaction Id' field which was set by each Thread.

 

About Author

Author Image
Prakhar Verma

Prakhar is a Web App Developer. Experienced in Java and always gives his best effort to complete the given task. He is self motivated and fun loving person.

Request for Proposal

Name is required

Comment is required

Sending message..