初始化后更改 Future 的 ExecutionContext

Changing ExecutionContext of a Future after initialisation

我明白了"ExecutionContext is like a cockroach":

We can’t talk about Futures without talking about its ExecutionContext: they form a duo (unfortunately)... It means the ExecutionContext was decided early on (generally on startup) and therefore is fixed. But callers should be able to decide on which ExecutionContext they want to run your function (like using their own). It’s not the responsibility of the callee service to enforce it (exceptions aside).

我们必须在构造时将其作为隐式参数传递

object Future {
  def apply[T](body: =>T)(implicit executor: ExecutionContext)
}

如果我们想完全控制任务在哪个线程池中执行,我们应该使用像 cats-effect 这样的库。

尽管如此,我想知道是否有任何方法可以破解 lazy 初始化 Future 使其在不同的执行上下文中 运行从它初始化的那个?也许是一些可怕的反光黑魔法,我们以某种方式识别任务并从其放入的队列中窃取它?

例如,假设我们有一个接受传递名称的函数 Future

def foo(f: => Future) = {
  val differentExecutionContext = ExecutionContext.fromExecutor(...
  /* run f on differentExecutionContext */
}

foo(Future(42)(ExecutionContext.Implicits.global))

现在我们可以做的是在调用点使用不同的执行上下文,就像这样

val differentExecutionContext = ExecutionContext.fromExecutor(...
foo(Future(42)(differentExecutionContext))

但是,这会强制用户记住提供和使用不同的执行上下文。有什么方法 Future(42) 可以在 differentExecutionContextfoo 而不是 global 上对用户透明地 运行?

如果这是 XY 问题,这里是 context

不认为这是可能的。在黑客攻击方面,=> Future[T]Future[T] 没有区别。我想你想做这样的事情:

f.asInstanceOf[SomeImplOfFuture[T]].setExecutionContext(myContexty).

但任何此类操作都会触发执行 f