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)