View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.hc.core5.http.impl.bootstrap;
28  
29  import java.util.HashSet;
30  import java.util.Map;
31  import java.util.Set;
32  import java.util.concurrent.BlockingQueue;
33  import java.util.concurrent.ConcurrentHashMap;
34  import java.util.concurrent.ThreadFactory;
35  import java.util.concurrent.ThreadPoolExecutor;
36  import java.util.concurrent.TimeUnit;
37  
38  /**
39   * @since 4.4
40   */
41  class WorkerPoolExecutor extends ThreadPoolExecutor {
42  
43      private final Map<Worker, Boolean> workerSet;
44  
45      public WorkerPoolExecutor(
46              final int corePoolSize,
47              final int maximumPoolSize,
48              final long keepAliveTime,
49              final TimeUnit unit,
50              final BlockingQueue<Runnable> workQueue,
51              final ThreadFactory threadFactory) {
52          super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
53          this.workerSet = new ConcurrentHashMap<>();
54      }
55  
56      @Override
57      protected void beforeExecute(final Thread t, final Runnable r) {
58          if (r instanceof Worker) {
59              this.workerSet.put((Worker) r, Boolean.TRUE);
60          }
61      }
62  
63      @Override
64      protected void afterExecute(final Runnable r, final Throwable t) {
65          if (r instanceof Worker) {
66              this.workerSet.remove(r);
67          }
68      }
69  
70      public Set<Worker> getWorkers() {
71          return new HashSet<>(this.workerSet.keySet());
72      }
73  
74  }