1 26 27 package net.sourceforge.groboutils.util.thread.v1; 28 29 30 40 public class TimedProcess 41 { 42 protected static TimedProcess s_instance = new TimedProcess(); 43 44 public static final int REASONABLE_TIME = 500; 45 46 53 public static interface RunnableKiller 54 { 55 public void killRunnable( Runnable r, Thread t ); 56 } 57 58 59 private static class InterruptRunnableKiller implements RunnableKiller 60 { 61 public void killRunnable( Runnable r, Thread t ) 62 { 63 t.interrupt(); 64 } 65 } 66 67 private RunnableKiller interruptor = new InterruptRunnableKiller(); 68 69 70 71 protected TimedProcess() 72 { 73 } 75 76 77 public static TimedProcess getInstance() 78 { 79 return s_instance; 80 } 81 82 83 92 public void runTimed( Runnable process, long waitTimeMillis ) 93 throws InterruptedException 94 { 95 runTimed( process, waitTimeMillis, this.interruptor ); 96 } 97 98 99 108 public void runTimed( Runnable process, long waitTimeMillis, 109 RunnableKiller processEnder ) 110 throws InterruptedException 111 { 112 if (processEnder == null || process == null || 113 waitTimeMillis <= 0L) 114 { 115 throw new IllegalArgumentException ("no null args"); 116 } 117 118 Thread t = new Thread ( process, "TimedProcess" ); 119 setupThread( t ); 120 t.start(); 121 joinThread( t, waitTimeMillis ); 122 if (t.isAlive()) 123 { 124 stopThread( t, process, processEnder ); 125 126 throw new InterruptedException ( "Process did not end within "+ 127 waitTimeMillis+" milliseconds." ); 128 } 129 } 130 131 132 133 136 protected void setupThread( Thread t ) 137 { 138 } 140 141 142 145 protected void stopThread( Thread t, Runnable process, 146 RunnableKiller processEnder ) 147 { 148 processEnder.killRunnable( process, t ); 149 joinThread( t, REASONABLE_TIME ); 150 if (t.isAlive()) 151 { 152 t.interrupt(); 154 joinThread( t, REASONABLE_TIME ); 155 if (t.isAlive()) 156 { 157 t.stop(); if (t.isAlive()) 161 { 162 throw new IllegalStateException ( 163 "After stopping the thread, the thread still lives. "+ 164 "The thread cannot be killed." ); 165 } 166 } 167 } 168 } 169 170 171 protected void joinThread( Thread t, long joinTime ) 172 { 173 try 174 { 175 t.join( joinTime ); 176 } 177 catch (InterruptedException e) 178 { 179 } 181 } 182 } 183 184 | Popular Tags |