java - Cancelling a thread safely due to timeout -
i have queue of tasks need performed, , pool of workers pick tasks , perform them. there's "manager" class keeps track of worker, allows user stop or restart them, reports on progress, etc. each worker this:
public void dowork() { checkarguments(); performcalculation(); saveresultstodatabase(); performanothercalculation(); saveresultstodatabase(); performyetanothercalculation(); saveresultstodatabase(); }
in case, "database" not refer oracle database. that's 1 of options, results saved on disk, in amazon simpledb, etc.
so far, good. however, performcalculation() code locks intermittently, due variety of factors, due poor implementation of networking code in bunch of third-party libraries (f.ex. socket.read() never returns). bad, obviously, because task stuck forever, , worker dead.
what i'd wrap entire dowork() method in sort of timeout, and, if timeout expires, give task else.
how can that, though ? let's original worker stuck in "performcalculation()" method. give task other worker, completes it, , original worker decides wake , save intermediate results database... corrupting valid data. there general pattern can use avoid ?
i can see couple of solutions, of them require serious refactoring of business-logic code, ground up... right thing philosophically, not have time for.
have tried using future
? useful running task , waiting complete, using timeout etc. example:
private runnable performcalc = new runnable() { public void run() { performcalculation(); } } public void dowork() { try { executorservice executor = executors.newfixedthreadpool(1); executor.submit(performcalc).get(); // timeouts can used here. executor.submit(anothercalc).get(); } catch(interruptedexception e) { // asked stop. rollback out transactions. } catch(otherexceptions here) { } }
Comments
Post a Comment