62,621
社区成员
发帖
与我相关
我的任务
分享
public class withStaticData {
...
public static ThreadLocal threadSharedClass;
public ThreadLocal threadSharedObject;
}
will have one copy of threadSharedClass per thread that uses the class, whereas threadSharedObject will have one copy per thread per instance of the class withStaticData.
Consider, for example, a secure server that requires a client to log in before allowing it to call its methods. The login method returns a password that must be presented by the thread each time it issues a method call. Now the server could save a mapping between threads and passwords. However, this is tedious and error prone. Thread-local data provides a simple and elegant solution. First, a class is provided, which allocates a new password:
public class Password {
public Password();
// Generates a new password.
public String getPassword();
// Returns the password.
public boolean match(String pass)
// Returns true if pass is the password.
} public class SecureService {
private ThreadLocal password = new ThreadLocal();
public String login() {
Password pass = new Password();
password.set(pass);
return pass.getPassword();
}
public void service(String pass) throws Exception {
Password check = (Password) password.get();
if(check.match(pass)) {
// perform service
} else throw new Exception("no access allowed");
}
}