问题
I want to ensure all methods of my class (updater service) are called within the ExecutorService
's thread (provided there's even a single thread). The order of the methods is not given so those that are public might get called from both the Executor
's thread and some other threads, mostly GUI thread.
My code:
// Instantiated lazy using synchronized getter - I decided not to bother with shared locks
private ExecutorService executor;
/**
* Provides compatibility between calls from executor thread pool and other threads.
* No matter the thread from which you call this method, the callback will be executed
* within the loop. Proper events will be raised in the loop thread as well, so
* mind to use SwingUtilities.invokeLater if event involves GUI operations.
* @param callback
* @throws Exception
*/
protected void runInExecutorIfNeeded(Callable callback) throws Exception {
// Already in executor thread
if(Thread.currentThread() == /* ??? */)
callback.call();
// Not in executor thread, go to executor thread and call callback there
else
getExecutor().submit(callback);
}
I have already done a similar thing in Swing - for methods like changeApplicationTrayIcon
I simply checked if I'm in GUI thread and if not, I used SwingUtilities.invokeLater
.
So, how do I check if current code is running in Executor's thread?
回答1:
If you provide an implementation of a ThreadFactory to your implementation of an ExecutorService (e.g. a ThreadPoolExecutor), you could record the threads created by the factory (either by reference or id) and perform a lookup against that ThreadFactory later on in order to determine if they've been created by the factory, and thus an executor thread
来源:https://stackoverflow.com/questions/34798891/detect-if-current-thread-is-executorservice-thread