What is a thread-local variable?
A thread-local variable effectively provides a separate copy of its value for each thread that uses it. Each thread can see only the value associated with that thread, and is unaware that other threads may be using or modifying their own copies

Using ThreadLocal to implement a per-thread Singleton
Thread-local variables are commonly used to render stateful Singleton or shared objects thread-safe, either by encapsulating the entire unsafe object in a ThreadLocal or by encapsulating the object’s thread-specific state in a ThreadLocal.

code snippest:

public class ConnectionDispenser {
private static class ThreadLocalConnection extends ThreadLocal {
public Object initialValue() {
return DriverManager.getConnection(ConfigurationSingleton.getDbUrl());
}
}  private static ThreadLocalConnection conn = new ThreadLocalConnection();

public static Connection getConnection() {
return (Connection) conn.get();
}
}

Ref:
Sometimes it’s best not to share
Writing multithreaded Java applications
Connection pools
Can ThreadLocal solve the double-checked locking problem?
Hibernate: Improved Thread Local Pattern

update: 09/17/2007

Thread Local: A Convenient Abomination 

Advertisements