如何在Java中实现有效的超时 [英] How to implement a efficient timeout in java

查看:498
本文介绍了如何在Java中实现有效的超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

n对象执行一些操作.执行动作后,时间戳将被更新.现在,我想实现一个超时线程,该线程可以验证时间戳是否早于例如60秒.

There are n object which perform some actions. After performing an action a timestamp will be updated. Now I want to implement a timeout-thread which verifies if a timestamp is older than for example 60 seconds.

我的第一个解决方案是使用线程(while循环+睡眠)来执行此操作,该线程持有包含所有对象(包括最后一个时间戳记)的列表.现在我有一个问题,那就是在最坏的情况下,线程需要59秒加上睡眠时间来决定超时.

My first solution was to do that with a thread (while-loop + sleep) which is holding a list with all objects including the last timestamp. Now I have the problem that there is a worst-case scenario where the thread needs 59 seconds plus sleep time to decide for a timeout.

我正在寻找一种解决方案,例如计时器,可以更新延迟时间.

I’m searching for a solution like a Timer where it is possible to update the delay time.

有什么想法吗?

推荐答案

我认为将监视器对象与wait/notify一起使用是合理的(如果您使用的是JDK> = 5,则可以将Condition与await/signal一起使用)

I think using a monitor object with wait/notify is reasonable (you may use Condition with await/signal if you are using JDK >= 5)

想法很简单:

工作线程:

doYourActualWork();
synchronized(jobFinishedMonitor) {
    updateTimestamp();

    jobFinishedMonitor.notify();
}

超时线程:

synchronized(jobFinishedMonitor) {
    while(within60Second(timestamp)) {
        jobFinishedMonitor.wait(60);
    }
    if (within60Second(timestamp)) {
        timeoutHappened=true;
    }
 }
 if (timeoutHappened) {
     // do timeout handling
 }

这篇关于如何在Java中实现有效的超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆