카테고리 없음
Java Virtual Thread (6), Reentrant을 이용한 Pinned Virtual Thread 방지
개발정리
2024. 6. 23. 14:48
private final ReentrantLock lock = new ReentrantLock();
private final Runnable runnable = new Runnable() {
@Override
public void run() {
//synchronized (this) {
lock.lock();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
//}
}
};
Reentrant 클래스는 Java에서 제공되는 클래스이다. 이를 이용해 synchronized lock 을 대체할 수 있다.
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
log.info("1) main. thread: " + Thread.currentThread());
platform();
//virtual();
log.info("2) main. time: " + (System.currentTimeMillis()-startTime) + " , thread: " + Thread.currentThread());
}
private static void virtual() {
ThreadFactory factory = Thread.ofVirtual().name("myVirtual-", 0).factory();
try (ExecutorService executorService = Executors.newThreadPerTaskExecutor(factory)) {
for (int i = 0; i < 20; i++) {
Pinning pinning = new Pinning();
executorService.submit(pinning.runnable);
}
}
}
private static void platform() {
try (ExecutorService executorService = Executors.newFixedThreadPool(20)) {
for (int i = 0; i < 20; i++) {
Pinning pinning = new Pinning();
executorService.submit(pinning.runnable);
}
}
}
수행 시간을 확인해보면 platform thread와 virtual thread가 동일한 수행시간을 가지는 것을 확인할 수 있다.
synchronized lock 대신 Reentrant lock 을 사용하면 virtual thread의 효용성을 그대로 살릴 수 있다.