View Javadoc
1   /*
2    * Licensed under the Apache License, Version 2.0 (the "License");
3    * you may not use this file except in compliance with the License.
4    * You may obtain a copy of the License at
5    *
6    * http://www.apache.org/licenses/LICENSE-2.0
7    *
8    * Unless required by applicable law or agreed to in writing, software
9    * distributed under the License is distributed on an "AS IS" BASIS,
10   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11   * See the License for the specific language governing permissions and
12   * limitations under the License.
13   */
14  package com.addthis.codec.utils;
15  
16  import java.util.concurrent.ScheduledExecutorService;
17  import java.util.concurrent.ScheduledThreadPoolExecutor;
18  import java.util.concurrent.ThreadFactory;
19  
20  import com.google.common.annotations.Beta;
21  import com.google.common.util.concurrent.MoreExecutors;
22  
23  import com.fasterxml.jackson.annotation.JsonCreator;
24  import com.fasterxml.jackson.annotation.JsonProperty;
25  import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
26  
27  @Beta
28  @JsonDeserialize(builder = ScheduledExecutorServiceBuilder.class)
29  public class ScheduledExecutorServiceBuilder {
30  
31      private final ThreadFactory threadFactory;
32      private final int coreThreads;
33      private final boolean shutdownHook;
34  
35      @JsonCreator
36      public ScheduledExecutorServiceBuilder(@JsonProperty("thread-factory") ThreadFactory threadFactory,
37                                             @JsonProperty("core-threads") int coreThreads,
38                                             @JsonProperty("shutdown-hook") boolean shutdownHook) {
39          this.threadFactory = threadFactory;
40          this.coreThreads = coreThreads;
41          this.shutdownHook = shutdownHook;
42      }
43  
44      public ScheduledExecutorService build() {
45          ScheduledThreadPoolExecutor service = new ScheduledThreadPoolExecutor(coreThreads, threadFactory);
46          if (shutdownHook) {
47              return MoreExecutors.getExitingScheduledExecutorService(service);
48          } else {
49              return service;
50          }
51      }
52  }