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  class WorkerPoolExecutor extends ThreadPoolExecutor {
39  
40      private final Map<Worker, Boolean> workerSet;
41  
42      public WorkerPoolExecutor(
43              final int corePoolSize,
44              final int maximumPoolSize,
45              final long keepAliveTime,
46              final TimeUnit unit,
47              final BlockingQueue<Runnable> workQueue,
48              final ThreadFactory threadFactory) {
49          super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
50          this.workerSet = new ConcurrentHashMap<>();
51      }
52  
53      @Override
54      protected void beforeExecute(final Thread t, final Runnable r) {
55          if (r instanceof Worker) {
56              this.workerSet.put((Worker) r, Boolean.TRUE);
57          }
58      }
59  
60      @Override
61      protected void afterExecute(final Runnable r, final Throwable t) {
62          if (r instanceof Worker) {
63              this.workerSet.remove(r);
64          }
65      }
66  
67      public Set<Worker> getWorkers() {
68          return new HashSet<>(this.workerSet.keySet());
69      }
70  
71  }