开发者

Abort loop after fixed time

I hava a thread in which I have an infinite loop, doing some network stuff. It appears that I don't get a response every time i'm doing this so the thread hangs for several seconds which causes serious problems to my software. What I need is some kind of "deadline" for the loop, if it takes more then (e.g. 100ms) restart again.

private boolean active = true;
public void run(){

   while(active){
       //some network stuff e.g:
       dnshandler.reverselookup("8.8.8.8");
   }

}

(this is not the real class... it's just to get an impression of what I mean.)

Any Ideas how to handle this?

Update: I handeled it with a seperate Thread as suggested. Actually I used a Callable becouse I need a return value.

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        try {
            List<Future<String>> results = executor.invokeAll(Arrays.asList(new CallableClass()), 500), TimeUnit.MILLISECONDS);
          开发者_如何学运维  for (Future<String> current : results) {
                if (!current.isCancelled()) {
                    someValue = current.get();
                } else {
                    // timeout
                    executor.shutdownNow();
                }
            }

        } catch (Exception e) {
            //handle it!
            e.printStackTrace();
        }

But the problem I face now is, that executor.shutdownNow() isn't terminating the hanging Callable task(which is the correct behaviour according to the Documentation). Is there a way to kill an executor task? (I know this is not a clean solution but some of the requests are handled by a library)


You can put your networking stuff into a separate thread and run it for a couple of seconds for instance:

int timeoutTime = ...
Runnable networkingStuff = ... // put the networking in here
Thread thread =new Thread(networkingStuff);
thread.start();
try {
    thread.join(timeoutTime);
    if(thread.isAlive()) {
        thread.interrupt();
    }
} catch (InterruptedException e) {
    // catch here the interruption
 }


Google Guava's TimeLimiter may do what you need.

[TimeLimiter] produces proxies that impose a time limit on method calls to the proxied object.


Apologies if this is wrong as I'm not a Java developer, but from a general programming perspective you should have your method that may take time return some form of TimeoutException.

You can catch this in your loop and then it will automatically restart.

This isn't a problem with the loop, moreso the method(s) you're calling within.

An alternative approach would be to run your time-consuming operations on a separate thread, so that nothing hangs. You can then notify the main (UI) thread of completion at any time.


Your infinite while loop is hogging the CPU. Try adding a delay of 50 ms or so, so that you give a small break for the CPU to attend to other tasks. Better yet, schedule your task using Timer with a certain amount of delay and TimerTask.


You should interrupt the thread after timeout. Check out java concurrency tutorial.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜