2 * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may
5 * not use this file except in compliance with the License. You may obtain
6 * a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 * implied. See the License for the specific language governing
14 * permissions and limitations under the License.
16 package org.akraino.validation.ui.conf;
18 import java.lang.reflect.Field;
19 import java.util.Comparator;
20 import java.util.concurrent.ExecutorService;
21 import java.util.concurrent.PriorityBlockingQueue;
22 import java.util.concurrent.ThreadPoolExecutor;
23 import java.util.concurrent.TimeUnit;
25 import org.springframework.context.annotation.Bean;
26 import org.springframework.context.annotation.Configuration;
29 public class ExecutorServiceInitializer {
31 private static final int QUEUE_CAPACITY = 500;
32 private static final int EXECUTOR_SIZE = 30; // the number of threads to keep in the pool, even if
33 // they are idle, unless allowCoreThreadTimeOut is
35 private static final int EXECUTOR_MAX_SIZE = 30; // the maximum number of threads to allow in the pool
36 private static final int KEEPALIVE_TIME = 30; // when the number of threads is greater than the
37 // core, this is the maximum time that excess idle
38 // threads will wait for new tasks before
40 private static final PriorityBlockingQueue<Runnable> BLOCKING_QUEUE = new PriorityBlockingQueue<Runnable>(
41 QUEUE_CAPACITY, new CFRunnableComparator());
42 private static ExecutorService executorService = new ThreadPoolExecutor(EXECUTOR_SIZE, EXECUTOR_MAX_SIZE,
43 KEEPALIVE_TIME, TimeUnit.SECONDS, BLOCKING_QUEUE);
45 @Bean(name = "executorService")
46 public ExecutorService getExecutorService() {
47 return this.executorService;
50 private static class CFRunnableComparator implements Comparator<Runnable> {
52 @SuppressWarnings("unchecked")
53 public int compare(Runnable runnable1, Runnable runnable2) {
54 return ((Comparable) unwrap(runnable1)).compareTo(unwrap(runnable2));
57 private Object unwrap(Runnable runnable) {
59 Field field = runnable.getClass().getDeclaredField("fn");
60 field.setAccessible(true);
61 return field.get(runnable);
62 } catch (IllegalAccessException | NoSuchFieldException e) {
63 throw new IllegalArgumentException("Couldn't unwrap " + runnable, e);