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.
Effective Java Item 49: Auto boxed type NullPointerException
Seems quite innocuous, but throws NPE
Example 1
Example 2
Example 1
public static void main(String[] args){
Boolean b = null;
call(b);
}
public static void call(boolean b){
System.out.println(b);
}
Example 2
public static void main(String[] args){
Integer i = null;
if (i == 42){
System.out.println(i);
}
}
Subscribe to:
Posts (Atom)