Skip to content
Advertisement

Callable in ExecutorService with shared data

I have a scenario which I have somehow simulated into the following: I have a list of Callable tasks that are being executed in 4 threads. The execution should return a value(a Map<String, String>). Each task has an item attribute.

JavaScript

If for a task I get timeout (I have a Timeout flag in a Map<> that each Callable returns) or an exception then I want to cancel or remove all the tasks which has the same item attribute or I want to notify the threads to avoid those tasks.
I am using invokeAll() for execution.

JavaScript

Below is my Callable class code:

JavaScript

How do I achieve this? I wanted to create a custom ThreadPoolExecutor and try the afterExecute() or beforeExecute() hooks to intervene between tasks assuming I could access Future<?> in there, but only Runnable is allowed in ThreadPoolExecutor. On the otherhand, with Runnable I cant get the results.

Advertisement

Answer

When creating the tasks, share a concurrent structure with each thread so that they can coordinate:

JavaScript

Then, in each task, check the shared state before starting, and update the shared state as appropriate:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement