Merge "Initial implementation of the ClusteredDataStore"
[controller.git] / opendaylight / config / threadpool-config-impl / src / main / java / org / opendaylight / controller / config / threadpool / util / FlexibleThreadPoolWrapper.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.controller.config.threadpool.util;
10
11 import java.io.Closeable;
12 import java.io.IOException;
13 import java.util.concurrent.ExecutorService;
14 import java.util.concurrent.Executors;
15 import java.util.concurrent.SynchronousQueue;
16 import java.util.concurrent.ThreadFactory;
17 import java.util.concurrent.ThreadPoolExecutor;
18 import java.util.concurrent.TimeUnit;
19
20 import org.opendaylight.controller.config.threadpool.ThreadPool;
21
22 /**
23  * Implementation of {@link ThreadPool} using flexible number of threads wraps
24  * {@link ExecutorService}.
25  */
26 public class FlexibleThreadPoolWrapper implements ThreadPool, Closeable {
27     private final ThreadPoolExecutor executor;
28
29     public FlexibleThreadPoolWrapper(int minThreadCount, int maxThreadCount, long keepAlive, TimeUnit timeUnit,
30             ThreadFactory threadFactory) {
31
32         executor = new ThreadPoolExecutor(minThreadCount, maxThreadCount, keepAlive, timeUnit,
33                 new SynchronousQueue<Runnable>(), threadFactory);
34         executor.prestartAllCoreThreads();
35     }
36
37     @Override
38     public ExecutorService getExecutor() {
39         return Executors.unconfigurableExecutorService(executor);
40     }
41
42     public int getMinThreadCount() {
43         return executor.getCorePoolSize();
44     }
45
46     public void setMinThreadCount(int minThreadCount) {
47         executor.setCorePoolSize(minThreadCount);
48     }
49
50     @Override
51     public int getMaxThreadCount() {
52         return executor.getMaximumPoolSize();
53     }
54
55     public void setMaxThreadCount(int maxThreadCount) {
56         executor.setMaximumPoolSize(maxThreadCount);
57     }
58
59     public long getKeepAliveMillis() {
60         return executor.getKeepAliveTime(TimeUnit.MILLISECONDS);
61     }
62
63     public void setKeepAliveMillis(long keepAliveMillis) {
64         executor.setKeepAliveTime(keepAliveMillis, TimeUnit.MILLISECONDS);
65     }
66
67     public void setThreadFactory(ThreadFactory threadFactory) {
68         executor.setThreadFactory(threadFactory);
69     }
70
71     public void prestartAllCoreThreads() {
72         executor.prestartAllCoreThreads();
73     }
74
75     @Override
76     public void close() throws IOException {
77         executor.shutdown();
78     }
79
80 }