尽管可以以细粒度的方式传播(如executor.execute(Context.current().wrap(runnable))
),但您应该尝试将Context
传播集成到跨线程工作传输中。对于许多应用中,会尽快,因为它是建立像wrapping the "main" executor简单:
executor = Context.currentContextExecutor(executor);
// executor now auto-propagates
在你的应用程序的开始做这一次,然后你大多停止担心传播。
但是应用程序会有所不同。例如,创建应用程序Thread
小号直接或许应该做一个ThreadFactory
中传播调用线程的Context
到Thread
:
class PropagatingThreadFactory implements ThreadFactory {
private final ThreadFactory delegate;
public PropagatingThreadFactory(ThreadFactory d) {delegate = d;}
@Override public Thread newThread(Runnable r) {
return delegate.newThread(Context.current().wrap(r));
}
}