KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > openedit > util > TaskRunner


1 package com.openedit.util;
2
3 import java.util.Timer JavaDoc;
4 import java.util.TimerTask JavaDoc;
5
6 import org.apache.commons.logging.Log;
7 import org.apache.commons.logging.LogFactory;
8
9 public class TaskRunner
10 {
11     protected Object JavaDoc fieldNotify = new Object JavaDoc();
12     public Object JavaDoc getNotify()
13     {
14         return fieldNotify;
15     }
16     protected Timer JavaDoc fieldQueue;
17     private static final Log log = LogFactory.getLog(TaskRunner.class);
18     
19     protected int fieldCount;
20     protected boolean fieldHasHitMax;
21     protected int fieldMaxQueueSize = 200;
22     
23     public Timer JavaDoc getQueue()
24     {
25         if( fieldQueue == null)
26         {
27             fieldQueue = new Timer JavaDoc(true);
28         }
29         return fieldQueue;
30     }
31
32     public void setQueue(Timer JavaDoc inQueue)
33     {
34         fieldQueue = inQueue;
35     }
36     protected void reduce()
37     {
38         fieldCount--;
39         if( fieldHasHitMax && fieldCount == 0)
40         {
41             log.info("Image Queue is now empty");
42             fieldHasHitMax = false;
43         }
44         synchronized (getNotify())
45         {
46             getNotify().notifyAll();
47         }
48
49     }
50     protected void increase()
51     {
52         fieldCount++;
53     }
54     public int getCount()
55     {
56         return fieldCount;
57     }
58     
59     public void add(final Runnable JavaDoc inTask)
60     {
61         if(( fieldCount > getMaxQueueSize())) //We dont want this queue to get too big in case they cancel
62
{
63             fieldHasHitMax = true;
64             inTask.run();
65             return;
66         }
67         increase();
68         log.debug("Adding " + inTask);
69         TimerTask JavaDoc task = new TimerTask JavaDoc()
70         {
71             public void run()
72             {
73                 try
74                 {
75                     log.debug("Running " + inTask);
76                     inTask.run();
77                 }
78                 catch ( Throwable JavaDoc ex)
79                 {
80                     log.error("task failed " + ex.getMessage() + " on " + inTask );
81                 }
82                 reduce();
83             }
84         };
85         getQueue().schedule(task, 0);
86     }
87
88     public int getMaxQueueSize()
89     {
90         return fieldMaxQueueSize;
91     }
92
93     public void setMaxQueueSize(int inMaxQueueSize)
94     {
95         fieldMaxQueueSize = inMaxQueueSize;
96     }
97 }
98
Popular Tags