- Arawn's Dev Blog
- Outsider's Dev Story
- Toby's Epril
- Benelog
- NHN 개발자 블로그
- SK 플래닛 기술 블로그
- OLC CENTER
- 소프트웨어 경영/공학 블로그
- 모바일 컨버전스
- KOSR - Korea Operating System …
- 넥스트리 블로그
- 리버스코어 ReverseCore
- SLiPP
- 개발자를 위하여... (Nextree 임병인 수석)
- "트위터 부트스트랩: 디자이너도 놀라워할 매끈하고 직관…
- Learning English - The English…
- real-english.com
- 'DataScience/Deep Learning' 카테…
- Deep Learning Summer School, M…
- Deep Learning Courses
민서네집
[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 한 파일.
'Java' 카테고리의 다른 글
Crystal Report에서 Command 쿼리에서 매개변수 사용하는법 (0) | 2015.10.07 |
---|---|
이클립스 Dynamic 웹 프로젝트를 maven 프로젝트로 바꾸는 방법 (0) | 2015.10.06 |
Java 정규식 option 주기 (대소문자 구분 무시, Dot 줄바꿈 문자도 대응되도록) (0) | 2015.07.10 |
Crystal Report 2013 - 문자열을 숫자로 형변환 하기 (2) | 2015.07.03 |
Crystal Report 자료 (0) | 2015.06.16 |