I have a third-party MyService
class which is not thread safe, I have the same issue as this with one difference: I need to submit Callable
s not Runnable
s.
With a regular ThreadPoolExecutor
I would have done this:
ExecutorService executor = Executors.newFixedThreadPool(8);
// later in another thread
Future<String> result = executor.submit(() -> {
// compute return value then return it
return computed value
})
I would have then waited on the result future to get the result of callable.
But ExecutorService doesn't have a way to associate an object with each thread and the answer to the question above doesn't consider that the worker thread needs to communicate back to the Thread who submitted the task.
Using ThreadLocal
has the obvious drawback at shutdown phase, I thought of a Map of Thread Ids to the results they need but ConcurrentHashMap
doesn't provide a method that blocks current thread waiting for a key to be added and this question doesn't give me a good answer: BlockingQueue<Map.Entry> is not what I need here and the BlockingMap
library linked is very old.
So How do I achieve what I want ?