사용자 도구

사이트 도구


java:concurrent:executorservice

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

양쪽 이전 판 이전 판
다음 판
이전 판
java:concurrent:executorservice [2016/07/16 15:30]
kwon37xi [최적의 쓰레드 풀 수]
java:concurrent:executorservice [2020/08/07 13:53] (현재)
kwon37xi
줄 2: 줄 2:
   * [[https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html|ExecutorService]]   * [[https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html|ExecutorService]]
   * [[https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html|Executors]]   * [[https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html|Executors]]
 +  * [[http://executorservice.org/|VMLens Executor Service]]
   * [[http://www.baeldung.com/java-executor-service-tutorial|A Guide To The Java ExecutorService]]   * [[http://www.baeldung.com/java-executor-service-tutorial|A Guide To The Java ExecutorService]]
   * [[https://dzone.com/articles/properly-shutting-down-an-executorservice|Properly Shutting Down An ExecutorService]]   * [[https://dzone.com/articles/properly-shutting-down-an-executorservice|Properly Shutting Down An ExecutorService]]
 +  * [[http://www.nurkiewicz.com/2014/11/executorservice-10-tips-and-tricks.html|ExecutorService - 10 tips and tricks]]
  
 ===== 최적의 쓰레드 풀 수 ===== ===== 최적의 쓰레드 풀 수 =====
줄 53: 줄 55:
   * 웹 애플리케이션 등에서 모든 요청마다 ''ExecutorService''를 생성하지 말라. 요청이 폭주할 때 요청보다 더 많은 쓰레드가 생성된다. 미리 생성해둔 것을 ''ExecutorService''를 재사용해야한다.   * 웹 애플리케이션 등에서 모든 요청마다 ''ExecutorService''를 생성하지 말라. 요청이 폭주할 때 요청보다 더 많은 쓰레드가 생성된다. 미리 생성해둔 것을 ''ExecutorService''를 재사용해야한다.
  
 +===== ThreadPoolExecutor =====
 +  * 대표적인 Thread Pool?
 +  * [[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html|ThreadPoolExecutor]]
 +  * [[springframework:async|Spring @Async]]가 사용한다.
 +  * ''corePoolSize'' : 기본 Pool Size
 +  * ''maximumPoolSize'' : 최대 Pool Size
 +  * ''corePoolSize''를 먼저 값을 설정하고 후에 ''maximumPoolSize''를 설정할 것. ''setMaxPoolSize''에서 ''corePoolSize'' validation을 수행함.
 +  * 여기서 매우 중요한 점은 Pool을 늘리는 규칙이다. 이 규칙을 잘 못 이해하면 corePoolSize 만큼의 pool 밖에 안 만들어진다.
 +
 +> A ThreadPoolExecutor will automatically adjust the pool size (see getPoolSize()) according to the bounds set by corePoolSize (see getCorePoolSize()) and maximumPoolSize (see getMaximumPoolSize()). When a new task is submitted in method execute(Runnable), and fewer than corePoolSize threads are running, a new thread is created to handle the request, even if other worker threads are idle. If there are more than corePoolSize but less than maximumPoolSize threads running, a new thread will be created only if the queue is full. By setting corePoolSize and maximumPoolSize the same, you create a fixed-size thread pool. By setting maximumPoolSize to an essentially unbounded value such as Integer.MAX_VALUE, you allow the pool to accommodate an arbitrary number of concurrent tasks. Most typically, core and maximum pool sizes are set only upon construction, but they may also be changed dynamically using setCorePoolSize(int) and setMaximumPoolSize(int).
 +> corePoolSize 만큼의 쓰레드가 만들어져 있으면, 그 다음 쓰레드는 queueCapacity만큼 큐에 쌓여 있다가 corePool로 실행이 인입된다. 따라서 corePoolSize가 작고 queueCapacity가 매우 크면 queue가 꽉차기 전까지는 실제로 쓰레드 풀이 확장되지 않고 계속해서 corePool 만 재사용하게 된다.
 +
 +  * reject : Executor가 shutdown 상태이거나, queue와 maximum size가 정해져 있을 경우 이것이 꽉 차면 ''execute(Runnable)''가 reject 된다. 이 때  ''RejectedExecutionHandler.rejectedExecution(Runnable, ThreadPoolExecutor)''가 호출된다.
 +  * ''corePoolSize=0'', ''maximumPoolSize=Integer.MAX_VALUE'', ''keepAliveTime=60sec'', **''queueCapacity=0''** 으로 지정하면 ''Executors.newCachedThreadPool()'' 설정.
 +
 +===== ExecutorCompletionService =====
 +  * [[https://dzone.com/articles/executorcompletionservice|ExecutorCompletionService in Practice - DZone Java]]
 +  * 여러개의 ''Future''를 submit 한 상황에서 빨리 실행되는대로 값을 반환받아 사용할 수 있게 해준다.
 +  * [[java:8:completable_future|Java 8 CompletableFuture]]를 사용한다면 불필요해보인다.
 +
 +<code java>
 +final ExecutorService pool = Executors.newFixedThreadPool(5);
 +
 +// 응답 타입(String) 명시 필요
 +final ExecutorCompletionService<String> completionService = new ExecutorCompletionService<>(pool);
 +
 +for (final String site : topSites) {
 +    completionService.submit(new Callable<String>() {
 +        @Override
 +        public String call() throws Exception {
 +            return IOUtils.toString(new URL("http://" + site), StandardCharsets.UTF_8);
 +        }
 +    });
 +}
 +
 +// submit 한 갯수가 정확해야한다.
 +for(int i = 0; i < topSites.size(); ++i) {
 +    final Future<String> future = completionService.take(); // 먼저 실행되는 대로 바로 리턴
 +    try {
 +        final String content = future.get();
 +        //...process contents
 +    } catch (ExecutionException e) {
 +        log.warn("Error while downloading", e.getCause());
 +    }
 +}
 +</code>
java/concurrent/executorservice.1468652410.txt.gz · 마지막으로 수정됨: 2016/07/16 15:30 저자 kwon37xi