如何"break"需要太多时间才能完成该过程的方法?



我正在使用一种方法(使用spring)来管理大量的数据和信息,咨询数据库并生成一些文件。

我试图避免timeout exception,所以,我决定我应该使用@Async注释。

不太确定它是否像我想的那样有效,但我也意识到,我需要调用Async的方法,直到它完成…所以,可能是同样的问题,不是吗?

是否有任何方法我可以有一种侦听器,将读取正在处理的异步信息在我的bean,而不必等待所有的异步进程完成?

现在是这样的

private Long myFIrstMethod(){
// DO A LOT OF THINGS AND CALL TO MY ASYNC METHOD
// evaluate if the Async method will have something or not... and based on it make the return
if (myOtherMethod()){
    return soemvalue;
}else{
    return someOtherValue
}
@Async Future<Boolean> myOtherMethod() {
        //do something
         new AsyncResult<Boolean>(true); //or false...
    }
}

所以,我在想,我可能会在myFirstMethod上得到一个超时异常,有没有办法处理长时间的处理方法并避免这个异常?

谢谢。

您可以使用Timeout

http://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/io/TimeOut.java

设置超时长度为您想要等待的长度。同时,如果你的方法及时返回,你可以取消TimeOut。

package tjacobs.io;
public class TimeOut implements Runnable {
    private long mWaitTime;
    private boolean mRunning = true;
    private Thread mMyThread;
    private TimeOutCmd mTimeOutCmd;
    public static final int DEFAULT_URL_WAIT_TIME = 30 * 1000; // 30 Seconds
    public static final int NO_TIMEOUT = -1;
    public static final int DEFAULT_WAIT_TIME = NO_TIMEOUT;
    public static interface TimeOutCmd {
        public void timeOut();
    }
    public TimeOut(TimeOutCmd cmd) {
        this(cmd, DEFAULT_WAIT_TIME);
    }
    public TimeOut(TimeOutCmd cmd, int timeToWait) {
        mWaitTime = timeToWait;
        mTimeOutCmd = cmd;
    }
    public void stop() {
        mRunning = false;
        mTimeOutCmd.timeOut();
        if (mMyThread != null) mMyThread.interrupt();
    }
    /**
     * reset the TimeOut
     *
     */
    public void tick() {
        if (mMyThread != null)
            mMyThread.interrupt();
    }
    public void run () {
        mMyThread = Thread.currentThread();
        while (true) {
            try {
                Thread.sleep(mWaitTime);
                stop();
            }
            catch (InterruptedException ex) {
                if (!mRunning) {
                    return;
                }
            }
        }
    }
}

最新更新