[java] ThreadLocal 샘플
Java Thread Local – How to use and code sample
http://veerasundar.com/blog/2010/11/java-thread-local-how-to-use-and-code-sample/
ThreadLocal 을 위 예제와 같이 사용하면 된다.
package com.veerasundar;
public class ThreadLocalDemo extends Thread {
public static void main(String args[]) {
Thread threadOne = new ThreadLocalDemo();
threadOne.start();
Thread threadTwo = new ThreadLocalDemo();
threadTwo.start();
}
@Override
public void run() {
// sample code to simulate transaction id
Context context = new Context();
context.setTransactionId(getName());
// set the context object in thread local to access it somewhere else
MyThreadLocal.set(context);
/* note that we are not explicitly passing the transaction id */
new BusinessService().businessMethod();
MyThreadLocal.unset();
}
}
package com.veerasundar;
/**
* this class acts as a container to our thread local variables.
* @author vsundar
*
*/
public class MyThreadLocal {
private static final ThreadLocal<Context> userThreadLocal = new ThreadLocal<Context>();
public static void set(Context user) {
userThreadLocal.set(user);
}
public static void unset() {
userThreadLocal.remove();
}
public static Context get() {
return userThreadLocal.get();
}
}
원래 예제와 달라진 점은 ThreadLocal 변수를 선언할 때 <Context> 를 추가했다. 이렇게 하지 않으면 형변환 에러가 발생한다. 또 한 가지는 userThreadLocal 변수를 private 으로 변경해서 외부에서 함부로 접근하지 못하도록 했다.
package com.veerasundar;
public class Context {
private String transactionId = null;
// getter
public String getTransactionId() {
return transactionId;
}
// setter
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
}
package com.veerasundar;
public class BusinessService {
public void businessMethod() {
// get the context from thread local
Context context = MyThreadLocal.get();
System.out.println(context.getTransactionId());
}
}
[실행결과]
Thread-0
Thread-1
[첨부] Eclipse Project 를 zip 파일로 Export 한 파일.