All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ebay.jetstream.util.RequestThreadPool Maven / Gradle / Ivy

The newest version!
/*******************************************************************************
 *  Copyright © 2012-2015 eBay Software Foundation
 *  This program is dual licensed under the MIT and Apache 2.0 licenses.
 *  Please see LICENSE for more information.
 *******************************************************************************/
package com.ebay.jetstream.util;

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * An implementation of a request thread pattern
 * 
 * *
 * 
 * @author [email protected]
 * @version 1.0
 */

public class RequestThreadPool {
  FifoPriorityQueue m_queue = null;
  AtomicInteger m_numThreads = new AtomicInteger(2);
  CopyOnWriteArrayList m_threadList;
  boolean m_initialized = false;
  private RequestThreadMonitor m_monitor;
  
  public int getNumThreads() {
	return m_numThreads.get();
  }

    public RequestThreadPool() {
  }

  public RequestThreadMonitor getMonitor() {
    return m_monitor;
  }

  public void init(FifoPriorityQueue queue, int numThreads) {
    m_queue = queue;
    m_numThreads.set(numThreads);
    m_threadList = new CopyOnWriteArrayList();
    m_initialized = true;
  }

  public void setMonitor(RequestThreadMonitor monitor) {
    m_monitor = monitor;
  }

  public synchronized void shutdown() {

    for (int i = 0; i < m_numThreads.get(); i++) {

      AbortRequest ar = new AbortRequest();

      m_queue.insertAtTail(ar);
    }

  }

  public synchronized void start() throws Exception {
    if (!m_initialized)
      throw new Exception("Thread pool not initialized");

    for (int i = 0; i < m_numThreads.get(); i++) {
      if (m_monitor != null)
        m_threadList.add(i, new RequestThread(m_queue, m_monitor));
      else
        m_threadList.add(i, new RequestThread(m_queue));

      m_threadList.get(i).start();
    }
  }
  
	public void increasePoolSize(int numThreads) {
		for (int i = 0; i < numThreads; i++) {
			if (m_monitor != null)
				m_threadList.add(m_numThreads.get() + i, new RequestThread(
						m_queue, m_monitor));
			else
				m_threadList.add(m_numThreads.get() + i, new RequestThread(
						m_queue));

			m_threadList.get(m_numThreads.get() + i).start();
			
			m_numThreads.addAndGet(numThreads);
		}
	}

	public void decreasePoolSize(int numThreads) {
		for (int i = 0; i < numThreads; i++) {
			 AbortRequest ar = new AbortRequest();

		      m_queue.insertAtTail(ar);
		}
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy