1 package com.openedit.util; 2 3 import java.util.Timer ; 4 import java.util.TimerTask ; 5 6 import org.apache.commons.logging.Log; 7 import org.apache.commons.logging.LogFactory; 8 9 public class TaskRunner 10 { 11 protected Object fieldNotify = new Object (); 12 public Object getNotify() 13 { 14 return fieldNotify; 15 } 16 protected Timer 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 getQueue() 24 { 25 if( fieldQueue == null) 26 { 27 fieldQueue = new Timer (true); 28 } 29 return fieldQueue; 30 } 31 32 public void setQueue(Timer 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 inTask) 60 { 61 if(( fieldCount > getMaxQueueSize())) { 63 fieldHasHitMax = true; 64 inTask.run(); 65 return; 66 } 67 increase(); 68 log.debug("Adding " + inTask); 69 TimerTask task = new TimerTask () 70 { 71 public void run() 72 { 73 try 74 { 75 log.debug("Running " + inTask); 76 inTask.run(); 77 } 78 catch ( Throwable 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 |