KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jsmtpd > generic > threadpool > ThreadWorker


1 /*
2  *
3  * Jsmtpd, Java SMTP daemon
4  * Copyright (C) 2005 Jean-Francois POUX, jf.poux@laposte.net
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19  *
20  */

21 package org.jsmtpd.generic.threadpool;
22
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25
26 /**
27  * Handles a job
28  * @author Jean-Francois POUX
29  * Jsmtp
30  */

31 public class ThreadWorker extends Thread JavaDoc {
32
33     private boolean free = false;
34     private boolean running = true;
35     private IThreadedClass wrk;
36     private Log log = LogFactory.getLog(ThreadWorker.class);
37     
38     public void run() {
39         while (true) {
40             goSleep();
41             if (!running) {
42                 log.debug("Worker "+getName()+" stopping");
43                 return;
44             }
45             try {
46                 wrk.doJob();
47             } catch (RuntimeException JavaDoc e) {
48                log.error("Generic Thread pool worker #" + Thread.currentThread().getId() + " Caught a runtime exception : ",e);
49                log.error("Thread job lost, recycling thread");
50             }
51         }
52     }
53
54     public void forceShutdown() {
55         running = false;
56         free = false;
57         wrk.forceShutdown();
58         wake();
59     }
60
61     public void gracefullShutdown() {
62         running = false;
63         free = false;
64         wrk.gracefullShutdown();
65         wake();
66     }
67
68     public void setParam(Object JavaDoc o) {
69         wrk.setParam(o);
70     }
71
72     public void setWorker(IThreadedClass cl) {
73         wrk = cl;
74     }
75
76     public boolean isFree() {
77         return free;
78     }
79
80     public synchronized void wake() {
81         free = false;
82         notify();
83     }
84
85     private synchronized void goSleep() {
86         free = true;
87         try {
88             wait();
89         } catch (InterruptedException JavaDoc e) {
90             e.printStackTrace();
91         }
92     }
93 }
Popular Tags