posts - 72,comments - 807,trackbacks - 0
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)  编辑 收藏 网摘 所属分类: 好好工作




标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
Google站内搜索

相关文章:

相关链接: