Java Reference
In-Depth Information
14.13.
THReadLocal
Variables
The
THReadLocal
class allows you to have a single logical variable that has
independent values in each separate thread. Each
THReadLocal
object has
a
set
method that lets you set the value of the variable in the current
thread, and a
get
method that returns the value for the current thread. It
is as if you had defined a new field in each thread class, but without the
need to actually change any thread class. This is a feature you may well
never need, but if you do need it
THReadLocal
may simplify your work.
For example, you might want to have a user object associated with all
operations, set on a per-thread basis. You could create a
ThreadLocal
ob-
ject to hold each thread's current user object:
public class Operations {
private static ThreadLocal<User> users =
new ThreadLocal<User>() {
/** Initially start as the "unknown user". */
protected User initialValue() {
return User.UNKNOWN_USER;
}
};
private static User currentUser() {
return users.get();
}
public static void setUser(User newUser) {
users.set(newUser);
}
public void setValue(int newValue) {
User user = currentUser();
if (!canChange(user))
throw new SecurityException();
// ... modify the value ...
}