Using local thread variables

Shared data is one of the most critical aspect of concurrent programming. When you create an instance of a class that implements Runnable interface or extends Thread class and use same object to create multiple Threads then all the threads share same attributes. This means if you change any attribute in one thread, all threads are affected by this change

Sometimes you may be interested in having an attribute that is not shared across all the threads that run the same object. Java’s Concurrency api provides a clean mechanism via ThreadLocal class to do this.

We create a Task class as shown below and define a static initDate variable that will hold the time when this variable is accessed.

ThreadLocal class has a method called initialValue() which is used to return the initialization value to the thread local variable. Each thread gets it’s own independently initialized copy of the variable. ThreadLocal variables are usually created as static variables. value of these variables can be accessed using get() and set() methods of ThreadLocal class. There is also a method called remove() that deletes the value stored in the thredLocal variable of the Thread calling it.

  1. get() : Returns the value in the current thread’s copy of this thread-local variable.
  2. initialValue() : Returns the current thread’s “initial value” for this thread-local variable.
  3. remove() : Removes the current thread’s value for this thread-local variable.
  4. set(T value) : Sets the current thread’s copy of this thread-local variable to the specified value.

package com.bharatonjava.concurrency.threadlocal;

import java.util.Date;
import java.util.concurrent.TimeUnit;


public class Task implements Runnable{

	private static ThreadLocal<Date> initDate = new ThreadLocal<Date>(){
	
		@Override
		protected Date initialValue(){
			System.out.printf("%s : intialValue method called - " +Thread.currentThread().getName());
			return new Date();
		}
		
	};
		
	
	@Override
	public void run(){

		System.out.printf("%s initDate: %s\n", Thread.currentThread().getName(), initDate.get());
		try {
			TimeUnit.SECONDS.sleep(4);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}



Then implement the main method to create threads. Note that we are creating only one instance of our Runnable Task class. Same reference of this Task instance is passed on to all three Threads. We create 3 threads here and wait of a couple of seconds between creation of next thread.


package com.bharatonjava.concurrency.threadlocal;

import java.util.concurrent.TimeUnit;

public class MainClass {

	public static void main(String[] args) {
		
		Task task = new Task();
		
		for(int i = 0; i < 3 ; i++)
		{
			Thread t = new Thread(task);
			t.setName("THREAD-"+i);
			t.start();
			
			try {
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
		}
	}
}



Output

A sample execution log of the example shows each thread has a different value in it’s thread local variable.

thredlocal-output

References

http://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html

Advertisements

, , ,

  1. Leave a comment

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

%d bloggers like this: