001: // ***************************************************************
002: // * *
003: // * File: ReusableThread.java *
004: // * *
005: // * Copyright (c) 2002 Sun Microsystems, Inc. *
006: // * All rights reserved. *
007: // * *
008: // * *
009: // * Author - alejandro.abdelnur@sun.com *
010: // * *
011: // ***************************************************************
012:
013: package com.sun.portal.common.pool;
014:
015: import com.sun.portal.common.concurrent.LockWithMemory;
016:
017: public class ReusableThread implements Runnable, PartitionObject {
018: private ThreadPool _ownerPool;
019: private Thread _thread;
020: private boolean _running = true;
021: private LockWithMemory _begin = new LockWithMemory();
022: private LockWithMemory _end = new LockWithMemory();
023: private Runnable _runnable = null;
024: private boolean _executing = false;
025: private int _partition;
026: private boolean _reuse = true;
027:
028: public ReusableThread() {
029: this (null);
030: }
031:
032: ReusableThread(ThreadPool ownerPool) {
033: _ownerPool = ownerPool;
034: _thread = new Thread(this );
035: _thread.setDaemon(true);
036: _thread.start();
037: }
038:
039: void setReuseThread(boolean b) {
040: _reuse = b;
041: }
042:
043: public void setPartition(int partition) {
044: _partition = partition;
045: }
046:
047: public int getPartition() {
048: return _partition;
049: }
050:
051: void setRunnable(Runnable runnable) {
052: _runnable = runnable;
053: _executing = false;
054: }
055:
056: public void start() {
057: _begin.signal();
058: _executing = true;
059: }
060:
061: public void join() {
062: join(0, 0);
063: }
064:
065: public void join(long timeout) {
066: join(timeout, 0);
067: }
068:
069: public void join(long timeout, int nanos) {
070: if (_runnable != null) {
071: _end.waitFor(timeout, nanos);
072: }
073: }
074:
075: public boolean isAlive() {
076: return _executing;
077: }
078:
079: void finish() {
080: _running = false;
081: _begin.signal();
082: }
083:
084: public void run() {
085: try {
086: while (_running) {
087: try {
088: _begin.waitFor();
089: if (_running) {
090: try {
091: if (_runnable != null) {
092: _runnable.run();
093: }
094: } catch (Throwable ex1) {
095: System.out
096: .println("ReusableThread.run(), ex1: "
097: + ex1);
098: }
099: _running = _reuse;
100: _end.signal();
101: _executing = false;
102: if (_ownerPool != null) {
103: _ownerPool.releaseThread(this );
104: }
105: }
106: } catch (Exception ex2) {
107: System.out.println("ReusableThread.run(), ex2: "
108: + ex2);
109: }
110: }
111: } catch (Exception ex3) {
112: System.out.println("ReusableThread.run(), ex3: " + ex3);
113: }
114: }
115:
116: }
|