2 * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.md.sal.dom.xsql;
11 import java.util.LinkedList;
13 public class XSQLThreadPool {
14 private LinkedList<Runnable> tasks = new LinkedList<Runnable>();
15 private int threadCount = 0;
16 private int maxThreadCount = 10;
17 private String threadPoolName = "Simple Thread Pool";
18 private int waitTimeForIdle = 10000;
19 private int maxQueueSize = -1;
20 public Object waitForSlotSync = new Object();
22 public XSQLThreadPool(int _maxThreadCount, String name,
23 int _waitTimeForIdle) {
24 this.maxThreadCount = _maxThreadCount;
25 this.threadPoolName = name;
26 this.waitTimeForIdle = _waitTimeForIdle;
29 public void addTask(Runnable r) {
30 synchronized (tasks) {
33 if (threadCount < maxThreadCount) {
35 new WorkerThread(threadCount).start();
40 private class WorkerThread extends Thread {
42 private long lastTimeExecuted = System.currentTimeMillis();
44 public WorkerThread(int threadNumber) {
46 "Thread #" + threadNumber + " Of Threadpool " + threadPoolName);
50 Runnable runthis = null;
53 if (maxQueueSize != -1) {
54 synchronized (waitForSlotSync) {
55 if (tasks.size() < maxQueueSize) {
56 waitForSlotSync.notifyAll();
60 synchronized (tasks) {
61 if (tasks.isEmpty()) {
64 } catch (Exception err) {
68 if (!tasks.isEmpty()) {
69 runthis = tasks.removeFirst();
72 if (runthis != null) {
75 } catch (Exception err) {
76 err.printStackTrace();
78 lastTimeExecuted = System.currentTimeMillis();
80 if (System.currentTimeMillis() - lastTimeExecuted
85 synchronized (tasks) {
91 public int getNumberOfThreads() {
95 public void waitForSlot() {
96 if (tasks.size() > maxQueueSize) {
97 synchronized (waitForSlotSync) {
99 waitForSlotSync.wait();
100 } catch (Exception err) {
101 err.printStackTrace();
107 public boolean isEmpty() {
108 if (this.threadCount == 0) {
114 public void setMaxQueueSize(int size) {
115 this.maxQueueSize = size;