Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: org/altara/util/Worker.java


1   /* Altara Utility Classes
2      Copyright (c) 2001,2002 Brian H. Trammell
3   
4     This library is free software; you can redistribute it and/or
5     modify it under the terms of the GNU Lesser General Public
6     License as published by the Free Software Foundation; either
7     version 2.1 of the License, or (at your option) any later version.
8     
9     This library is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    Lesser General Public License for more details.
13    
14    You should have received a copy of the GNU Lesser General Public
15    License along with this library; if not, it is available at
16    http://www.gnu.org/copyleft/lesser.html, or by writing to the
17    Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18    Boston, MA  02111-1307  USA
19  */
20  
21  package org.altara.util;
22  
23  public abstract class Worker extends Thread {
24  
25    private boolean running;
26    private boolean awake;
27  
28    protected Worker() {
29      super();
30    }
31  
32    protected Worker(String name) {
33      super(name);
34    }
35  
36    // thread control methods
37  
38    public void start() {
39      this.running = true;
40      this.awake = true;
41      super.start();
42    }
43  
44    public void startAsleep() {
45      this.running = true;
46      this.awake = false;
47      super.start();
48    }
49  
50    public synchronized void lull() {
51      this.awake = false;
52    }
53  
54    public synchronized void wake() {
55      this.awake = true;
56      this.notify();
57    }
58    
59    public synchronized void kill() {
60      this.awake = true;
61      this.running = false;
62      this.interrupt();
63    }
64  
65    // thread body
66  
67    public final void run() {
68      while (running) {
69        // Check to see if I should sleep
70        if (!awake) {
71          synchronized(this) {
72            try {
73              this.wait();
74            } catch (InterruptedException ex) {
75              // We must skip over our action, since
76              // this interrupt may be a kill() interrupt.
77              continue;
78            }
79          }
80        }
81      
82        // this can block too
83        try {
84          work();
85        } catch (Exception ex) {
86          workException(ex);
87        }
88      }
89      workExit();
90    }
91  
92    protected abstract void work() throws Exception;
93  
94    protected void workException(Exception ex) {
95      // do nothing by default
96    }
97  
98    protected void workExit() {
99      // do nothing by default
100   }
101 }