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
@Override protected Integer initialValue() {
return uniqueId.getAndIncrement(); }
};
public static int getCurrentThreadId() {
return uniqueId.get();
}
} // UniqueThreadIdGenerator
No comments:
Post a Comment