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());
}
}



Posted by 김용환 '김용환'

댓글을 달아 주세요