001: /*
002: * Copyright 1999,2004 The Apache Software Foundation.
003: *
004: * Licensed under the Apache License, Version 2.0 (the "License");
005: * you may not use this file except in compliance with the License.
006: * You may obtain a copy of the License at
007: *
008: * http://www.apache.org/licenses/LICENSE-2.0
009: *
010: * Unless required by applicable law or agreed to in writing, software
011: * distributed under the License is distributed on an "AS IS" BASIS,
012: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013: * See the License for the specific language governing permissions and
014: * limitations under the License.
015: */
016:
017: package org.apache.catalina.cluster.tcp;
018:
019: import java.util.List;
020: import java.util.LinkedList;
021: import java.io.IOException;
022:
023: /**
024: * <p>Title: </p>
025: * <p>Description: </p>
026: * <p>Copyright: Copyright (c) 2002</p>
027: * <p>Company: </p>
028: * @author not attributable
029: * @version 1.0
030: */
031:
032: public class ThreadPool {
033: /**
034: * A very simple thread pool class. The pool size is set at
035: * construction time and remains fixed. Threads are cycled
036: * through a FIFO idle queue.
037: */
038:
039: List idle = new LinkedList();
040: Object mutex = new Object();
041: Object interestOpsMutex = null;
042:
043: ThreadPool(int poolSize, Class threadClass, Object interestOpsMutex)
044: throws Exception {
045: // fill up the pool with worker threads
046: this .interestOpsMutex = interestOpsMutex;
047: for (int i = 0; i < poolSize; i++) {
048: WorkerThread thread = (WorkerThread) threadClass
049: .newInstance();
050: thread.setPool(this );
051:
052: // set thread name for debugging, start it
053: thread.setName(threadClass.getName() + "[" + (i + 1) + "]");
054: thread.setDaemon(true);
055: thread.setPriority(Thread.MAX_PRIORITY);
056: thread.start();
057:
058: idle.add(thread);
059: }
060: }
061:
062: /**
063: * Find an idle worker thread, if any. Could return null.
064: */
065: WorkerThread getWorker() {
066: WorkerThread worker = null;
067:
068: synchronized (mutex) {
069: while (worker == null) {
070: if (idle.size() > 0) {
071: try {
072: worker = (WorkerThread) idle.remove(0);
073: } catch (java.util.NoSuchElementException x) {
074: //this means that there are no available workers
075: worker = null;
076: }
077: } else {
078: try {
079: mutex.wait();
080: } catch (java.lang.InterruptedException x) {
081: }
082: }
083: }
084: }
085:
086: return (worker);
087: }
088:
089: /**
090: * Called by the worker thread to return itself to the
091: * idle pool.
092: */
093: void returnWorker(WorkerThread worker) {
094: synchronized (mutex) {
095: idle.add(worker);
096: mutex.notify();
097: }
098: }
099:
100: public Object getInterestOpsMutex() {
101: return interestOpsMutex;
102: }
103: }
|