Let’s say I do something in Java like:
RemoteResponse response = null; try { FutureTask task new FutureTask(....); executor.execute(task); response = task.get(1000, TimeUnits.MILLISECONDS); } catch( TimeoutException te ) { .. should I do something special here? ... .. what happens to the return value of the task if task.get() throws an exception? ... .. is it ever garbage collected? .. }
My question is does something hold onto RemoteResponse in the case where TimeoutException is thrown? Will it get garbage collected? Do I have to call the cancel() method on the task for that to happen?
Edit after the question was revised:
responseis a reference to aRemoteResponsethattaskis responsible for allocating. The assignment of the return value from a method won’t happen if the method threw an exception, so there is no need for special handling ofresponse.taskwill be unreferenced when it goes out of scope, either through normal execution or if an exception is thrown.If the resources allocated by
taskare well encapsulated, ie there are no externally held references, and are released (close,release, whatever), then there should be no resource leakage.There’s no need to call cancel unless there is some shared resource the
taskhas exclusively or some other consumable resource that the rest of the application needs.I’d at least log the fact that the task didn’t complete in the time allotted. What else you do depends on the requirements of your application.
Note that
taskwill continue executing until completion, regardless of thegetcall.