Thursday, July 31, 2008

Thread Local

Thread local is the concept of storing data which is specific to the thread. For example member variables are specific to instance, thread local variables are specific to Thread.

The IBM's page outlines exactly how it works..

This is definitely good way to do thread related transactions where in each thread denotes on transaction or session. Caling the get method on the thread local will return value based on the thread from which the method is called.

An example:

public class ThreadLocalTest {

static class CountdownThread extends Thread {
public static final ThreadLocal local = new ThreadLocal();
private int start;

public CountdownThread(int s) {
start= s;
}

public void run() {
init();
while(true) {
System.out.println(local.get());
int i = local.get();
local.set(--i);
if(i==0) {
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public void init() {
local.set(start);
}
}

public static void main(String[] args) {
CountdownThread t1 = new CountdownThread(10);
CountdownThread t2 = new CountdownThread(5);
t1.start();
t2.start();

}
}


Output:

10
5
4
9
3
8
2
7
1
6
5
4
3
2
1

I wonder how come I didn't hear about this for long time!!!

Happy coding!!

No comments: