package threadlocal;
class SecurityContext {
private String userId = null;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
class MyThreadLocal {
private static final ThreadLocal userThreadLocal = new ThreadLocal();
public static void set(SecurityContext user) {
userThreadLocal.set(user);
}
public static void unset() {
userThreadLocal.remove();
}
public static SecurityContext get() {
return (SecurityContext)userThreadLocal.get();
}
}
class BusinessService {
public void businessMethod() {
SecurityContext securityContext = MyThreadLocal.get();
System.out.println(securityContext.getUserId());
}
}
public class Main extends Thread{
public static void main(String[] args){
new Main().start();
new Main().start();
}
@Override
public void run() {
SecurityContext securityContext = new SecurityContext();
securityContext.setUserId(getName());
MyThreadLocal.set(securityContext);
new BusinessService().businessMethod();
MyThreadLocal.unset();
}
}
Reference: http://veerasundar.com/blog/2010/11/java-thread-local-how-to-use-and-code-sample/Saturday, 16 April 2016
Threadlocal example
Business layer can access userId without passing the parameter from web layer.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment