Thread Pool 간단한 소개
Servlet에서는 많은 요청을 효율적으로 처리하기 위해 Thread Pool을 사용한다. Servlet은 1개의 요청에 1개의 스레드를 할당하는데 미리 준비된 몇개의 스레드를 pool에 대기시켜 두었다가 요청이 들어오면 스레드를 이용하여 처리하고 다시 pool에 반납하는 과정을 거친다. 이의 장점은 각각의 요청을 처리하기 위해 스레드를 생성하고 해제하는 과정을 거치지 않고 가용 스레드를 미리 생성하고 작업이 종료되면 반납하는 식으로 작동되므로 성능이 향상된다.
직접 구현할 수도 있지만 자바에서는 편리한 구현을 위해 ExecutorService라는 인터페이스를 제공하고 있어서 인터페이스에 맞게 개발을 하면된다.
import java.util.concurrent.*;
public class ThreadTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
// 스레드이름을 출력하고 1초간 대기하는 Runnable 구현체 생성
Runnable worker = () -> {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " : start");
try {
Thread.sleep(1000);
} catch (Exception ignored) {}
System.out.println(threadName + " : end");
};
// queue에 할당하기
es.submit(worker);
}
// 이전까지 반영한 작업한 수행하고 종료
es.shutdown();
}
}
Executors는 ExecutorService 인터페이스에 맞는 구현체를 생성해 주는데 크게 3가지가 있다.
newFixedThreadPool : 고정된 스레드 개수를 운용하는 풀을 생성한다
newCachedThreadPool : 고정된 스레드 개수를 초과하는 요청이 들어오면 추가로 스레드를 생성한다
newSingleThreadExecutor : 단일 스레드만 운용한다
작업 요청을 담아주는 Queue는 LinkedBlockingQueue라는 내부 구현체를 별도로 사용한다. (최종적으로 TaskQueue가 이를 상속받아 사용됨)
pool-1-thread-4 : start
pool-1-thread-3 : start
pool-1-thread-5 : start
pool-1-thread-1 : start
pool-1-thread-2 : start
pool-1-thread-3 : end
pool-1-thread-4 : end
pool-1-thread-5 : end
pool-1-thread-1 : end
pool-1-thread-2 : end
pool-1-thread-1 : start
pool-1-thread-3 : start
pool-1-thread-5 : start
pool-1-thread-2 : start
pool-1-thread-4 : start
pool-1-thread-1 : end
pool-1-thread-3 : end
pool-1-thread-2 : end
pool-1-thread-4 : end
pool-1-thread-5 : end
위 코드를 실행하면 가용 스레드는 5개이지만 실제 작업은 10개를 요청하였으므로 5개가 시작되고, 5개가 끝나는 식으로 반복된다. 간편한 테스트를 위해 중간에 1초가량 스레드를 중지시키는 코드를 넣었지만 실제로는 다양한 환경에서 작동되므로 시작과 끝의 순서가 보장되지 않는다.
문제점
데드락 : 멀티쓰레딩 프로그램에선 어느 곳이든 일어날 수 있는 문제이다.
스레드누수 : 스레드가 작업을 수행하고 비정상적인 이유로 풀로 반납되지 못했을 때 발생된다.
자원 쓰레싱(Thrashing) : 스레드 풀의 크기가 클 경우 Thread Context Switching 간 오버헤드가 많이 발생하며 필요한 자원을 제때 할당받지 못하여 기아문제가 발상한다