티스토리 뷰
Thread는 자원과 안정성 문제가 항상 따라다닌다. Thread가 많다면 대기 중인 상태가 되어, 메모리 사용량이 많아지면서 JVM 가비지 콜렉터에 영향을 주게 된다. 이러한 문제를 해결하기 위해 Thread Pool 관리가 필요하고, Java에서는 java.util.concurrent.* 패키지에서 Thread Pool을 제공하고 있다.
ExecutorService 생성자
- newFixedThreadPool : 지정된 숫자만큼 고정된 Thread를 유지한다. Thread가 작업이 종료되었으면 Thread 다시 생성하여 주어진 개수를 맞춘다.
/**
* Creates a thread pool that reuses a fixed number of threads
* operating off a shared unbounded queue. At any point, at most
* {@code nThreads} threads will be active processing tasks.
* If additional tasks are submitted when all threads are active,
* they will wait in the queue until a thread is available.
* If any thread terminates due to a failure during execution
* prior to shutdown, a new one will take its place if needed to
* execute subsequent tasks. The threads in the pool will exist
* until it is explicitly {@link ExecutorService#shutdown shutdown}.
*
* @param nThreads the number of threads in the pool
* @return the newly created thread pool
* @throws IllegalArgumentException if {@code nThreads <= 0}
*/
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
- newCachedThreadPool : Thread가 가변적으로 생성되며, 쉬고 있는 Thread가 있다면(60초) Thread를 종료한다. Thread에 대한 제한을 두지 않는 점을 유의해야 한다.
/**
* Creates a thread pool that creates new threads as needed, but
* will reuse previously constructed threads when they are
* available. These pools will typically improve the performance
* of programs that execute many short-lived asynchronous tasks.
* Calls to {@code execute} will reuse previously constructed
* threads if available. If no existing thread is available, a new
* thread will be created and added to the pool. Threads that have
* not been used for sixty seconds are terminated and removed from
* the cache. Thus, a pool that remains idle for long enough will
* not consume any resources. Note that pools with similar
* properties but different details (for example, timeout parameters)
* may be created using {@link ThreadPoolExecutor} constructors.
*
* @return the newly created thread pool
*/
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
- newSingleThreadExecutor : Thread가 1개이며, 작은 단위 작업을 처리할 때 사용된다.
/**
* Creates an Executor that uses a single worker thread operating
* off an unbounded queue. (Note however that if this single
* thread terminates due to a failure during execution prior to
* shutdown, a new one will take its place if needed to execute
* subsequent tasks.) Tasks are guaranteed to execute
* sequentially, and no more than one task will be active at any
* given time. Unlike the otherwise equivalent
* {@code newFixedThreadPool(1)} the returned executor is
* guaranteed not to be reconfigurable to use additional threads.
*
* @return the newly created single-threaded Executor
*/
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
- newScheduledThreadPool : 특정 시간 이후에 실행되거나 주기적으로 작업을 실행할 수 있다.
/**
* Creates a thread pool that can schedule commands to run after a
* given delay, or to execute periodically.
* @param corePoolSize the number of threads to keep in the pool,
* even if they are idle
* @return a newly created scheduled thread pool
* @throws IllegalArgumentException if {@code corePoolSize < 0}
*/
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
메서드
- execute - 반환 값이 없고, 예외 발생 시 Thread를 재 생성한다.
- submit - Future 객체를 반환하고, 예외 발생 시 사용하던 Thread를 재 사용한다.
- shutdown - 시작된 Task를 모두 완료하면 종료(새로운 Task를 받지 않음)
- shutdownNow - 실행 중인 Task 모두 강제 종료
- awaitTermination - 수행 중인 Task가 지정된 시간 동안 끝나기를 기다린다. 지정된 시간 내 끝나지 않으면 false
'프로그래밍 > Back end' 카테고리의 다른 글
[Back end] Spring Boot Quartz Scheduler (0) | 2023.05.18 |
---|---|
[Back end] Spring Boot @Autowired null 에러 (0) | 2022.11.22 |
[Back end] Java Tutorial Map and HashMap (0) | 2022.03.25 |
[Back end] Java Tutorial ArrayList VS LinkedList (0) | 2022.03.20 |
[Back end] Java Tutorial Array VS ArrayList (0) | 2022.03.20 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
링크
TAG
- Collection
- 리액트
- 오라클
- Linux 명령어
- 소프트웨어공학
- Tomcat
- effective java
- SQL
- React
- 회고
- 프로그래머스
- Maven
- 성능분석
- 정렬 알고리즘
- spring
- 리눅스 명령어
- 프로그래머
- 개발환경
- 제주도 여행
- Java
- 리액트 16
- 자바스크립트
- 이직
- Eclipse
- 제주도 3박4일 일정
- 오라클 내장 함수
- sort algorithm
- 자바
- 경력관리
- javascript
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
글 보관함