ThreadLocal allows to associate a per-thread value with an object.
It provides get / set methods that maintains a separate copy of the value for each thread that uses it.
Example
private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>() {
public Connection initialValue() {
return DriverManager.getConnection(URL);
}
};
public static Connection getConnection() {
return threadLocal.get();
}
When a thread calls ThreadLocal.get for the first time, initialValue method provides the initial value.
Thread specific values are stored in the Thread object itself and garbage collected when thread terminates.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.