Saturday, November 29, 2008

Thread Local

Introduction

Thread local is a java class which provided the thread local variable. As per standard definition “These variables differ from their normal counterparts in that each thread that accesses one has its own, independently initialized copy of the variable. Thread Local instances are typically private static fields in classes that wish to associate state with a thread.

When should we use thread local?

If the object is accessed by multiple threads (concurrently) and you want to hold local data for each thread.

Following are the scenarios where you can implement the thread local concept

1. Many users access same servlet at time and many threads will be running the same servlet code concurrently. In this scenario we can apply the thread local concept by implementing thread local object for the servlet.

2. If we are using multiple data source in the application. Then we need to maintain transactionId for the each connection object. In this case we can also use the thread local object to maintain the transactionID.

What is the benefit of thread local?

Thread local gives support for your program to run without fail in the concurrent environment

Following are the steps to implement Thread local object.

1. You need to instantiate Thread local object.
2. Provide getter, setter method to access thread Local object.

These are the following methods provide by thread local.

Object get() Returns the value for the current thread
set(Object) Sets a new value for the current thread
Object initialValue() Used to return an initial value (if ThreadLocal is subclassed)
remove() In JDK 5 only - used to delete the current thread's value (for clean-up only)

One implementation for the beginner’s:-

public class CustomThreadLocal {

//for singleton purpose
private static ThreadLocal localObject = new ThreadLocal();

public static void set(Object obj) {
localObject.set(obj);
}

public static Object get() {
return localObject.get();
}
. . .
Its work in the very simple way but behind the scenes its fetch the local data by unique ID of the thread.

There is one adverse affect:
It’s slow down the application performance

have a good day!