java7에서 ThreadLocal을 초기화하는 코드이다.
참조 코드: https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadId {
// Atomic integer containing the next thread ID to be assigned
private static final AtomicInteger nextId = new AtomicInteger(0);
// Thread local variable containing each thread's ID
private static final ThreadLocal<Integer> threadId =
new ThreadLocal<Integer>() {
@Override protected Integer initialValue() {
return nextId.getAndIncrement();
}
};
// Returns the current thread's unique ID, assigning it if necessary
public static int get() {
return threadId.get();
}
}
java8에서는 위의 코드를
import java.util.concurrent.atomic.AtomicInteger;public class ThreadId {
// Atomic integer containing the next thread ID to be assigned
private static final AtomicInteger nextId = new AtomicInteger(0);
// Thread local variable containing each thread's ID
private static final ThreadLocal<Integer> threadId = ThreadLocal.withInitial(()->new Integer(5));
// Returns the current thread's unique ID, assigning it if necessary
public static int get() {
return threadId.get();
}
}
또는
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadId {
// Atomic integer containing the next thread ID to be assigned
private static final AtomicInteger nextId = new AtomicInteger(0);
// Thread local variable containing each thread's ID
private static final ThreadLocal<Integer> threadId =
ThreadLocal.withInitial(() -> nextId.getAndIncrement());
// Returns the current thread's unique ID, assigning it if necessary
public static int get() {
return threadId.get();
}
}
간단 테스트 코드이다.
public class ThreadLocalTest {
public static void main(String[] args) {
ThreadLocal<Integer> myThreadLocal = ThreadLocal.withInitial( ()-> new Integer(5));
System.out.println(myThreadLocal.get());
myThreadLocal.set(10);
System.out.println(myThreadLocal.get());
}
}
'java core' 카테고리의 다른 글
java8 + centos7 이슈 (0) | 2016.01.05 |
---|---|
IntStream, LongStream의 범위 - range, rangeClose 차이 및 예제 (0) | 2015.12.14 |
[java8] List<Object>를 List<String>으로 변환하기 (0) | 2015.11.19 |
[java8] List 쪼개기 (split by fixed num) (0) | 2015.11.19 |
java8 소스 보기 (0) | 2015.10.19 |