Wednesday, March 16, 2011

ThreadLocal in Java

In Java a thread-local variable is implemented by one class called ThreadLocal rather than built-in language support. In oreder to create a thread-local variable you need to create an instance of ThreadLocal.

public class ThreadLocal {
public Object get();
public void set(Object newValue);

public void remove();
public Object initialValue();


ThreadLocal acts as the warppper for the variable that should be thread-local.

How ThreadLocal works? ThreadLocal maintains one table internally that holds the thread and associating object reference. When you try to get the object from ThreadLocal it will return the object reference that is stored with the current thread.

import java.util.concurrent.atomic.AtomicInteger;
public class UniqueThreadIdGenerator {
private static final AtomicInteger uniqueId = new AtomicInteger(0);

private static final ThreadLocal uniqueNum = new ThreadLocal )
@Override protected Integer initialValue() {
return uniqueId.getAndIncrement(); }
public static int getCurrentThreadId() {
return uniqueId.get();
} // UniqueThreadIdGenerator

No comments:

Post a Comment