abstract public class TimeoutHelper implements Runnable
{
private Throwable error;
private boolean running = true;
private Object retValue;
protected String name;
private long waitTime;
private Thread thread;
/**
* Creates a new helper. Use {@link #start} to run the code.
*
* @param name A name that will be used in the helper thread name
* @param waitTime The time (in msec) to wait before timeout.
*/
public TimeoutHelper(String name, long waitTime)
{
this.name = name;
this.waitTime = waitTime;
}
public Object start() throws Throwable
{
return asyncExecute();
}
abstract protected Object execute() throws Throwable;
private synchronized Object asyncExecute() throws Throwable
{
createThread().start();
if (running)
{
try
{
wait(waitTime);
if (running)
{
// Timeout!!
abortThread();
throw new TimeOutException("Timeout for: " + name);
}
}
catch (InterruptedException ie)
{
// Ignore
}
}
if (error != null)
{
throw error;
}
return retValue;
}
private void abortThread()
{
if (thread != null)
{
thread.interrupt();
}
}
protected Thread createThread()
{
thread = new Thread(this, name);
return thread;
}
public void run()
{
try
{
retValue = execute();
}
catch (Throwable th)
{
error = th;
}
synchronized (this)
{
running = false;
notifyAll();
}
}
}
Use the class by extending it and implementing "execute". For example:
TimeoutHelper helper = new TimeoutHelper("Runner", 5000)
{
protected Object execute() throws Throwable
{
Runtime runtime = Runtime.getRuntime();
return runtime.exec("rsh localhost ls");
}
};
try
{
Process p = (Process)helper.start();
}
catch (TimeOutException e)
{
// Handle timeout here
}
catch (Exception e)
{
// Handle other errors here.
}
posted on 2005-01-26 12:04
Lcruiser (Cookie) 阅读(302)
评论(0) 编辑 收藏 网摘 所属分类:
好好工作