Scala Future:等待在另一个独立线程中发生更新
Scala Future: Wait for update occurring in another independent thread
我有一个 class,它有自己的内部线程 运行 处理一系列操作,它一直在循环做事。为此,它会读取一个通知队列,告诉它下一步要做什么。有一条通知告诉 class 停止所有操作并自行终止。当另一个线程调用 notifyClose 通知时,它被添加到队列中并采用优先级编号 1。我想要在另一个线程处理关闭通知时将通知添加到 return a Future.success 的方法。
代码运行如下:
def loop(): Future[Unit] = {
current = if(queue.contains(KILL)) disable() // <--- disable will set the state to Closed
else process() // <--- if queue is empty it will call loop(),
// if its not empty it will do de action and then call loop()
}
private def disable(): Future[Unit] = {
state = Closed
Future.unit
}
def close(): Future[Unit] = {
queue.add(KILL)
while (state != Closed) { /* Wait until state is NotAvailable */ }
Future.successful()
}
我想要一个更好的方法来等待 close()
方法中的状态变为 Closed。我填充它,空循环是有史以来最糟糕的主意。
变量 current 保存当前正在处理的 Future,也许有办法将我的结果挂钩到那个 Future?问题是我不知道 disable()
方法什么时候真正开始。任何帮助将不胜感激。
感谢您抽空阅读。
尝试使用Promise
作为一种状态,例如
def loop(): Future[Unit] = {
if(queue.contains(KILL)) Future.successful(disable.trySuccess())
else process()
}
private val disable = Promise[Unit]()
def close(): Future[Unit] = {
queue.add(KILL)
disable.future
}
这样 close()
返回的 Future
只有在 loop()
实际调用 disable.trySuccess
时才会完成。
我有一个 class,它有自己的内部线程 运行 处理一系列操作,它一直在循环做事。为此,它会读取一个通知队列,告诉它下一步要做什么。有一条通知告诉 class 停止所有操作并自行终止。当另一个线程调用 notifyClose 通知时,它被添加到队列中并采用优先级编号 1。我想要在另一个线程处理关闭通知时将通知添加到 return a Future.success 的方法。
代码运行如下:
def loop(): Future[Unit] = {
current = if(queue.contains(KILL)) disable() // <--- disable will set the state to Closed
else process() // <--- if queue is empty it will call loop(),
// if its not empty it will do de action and then call loop()
}
private def disable(): Future[Unit] = {
state = Closed
Future.unit
}
def close(): Future[Unit] = {
queue.add(KILL)
while (state != Closed) { /* Wait until state is NotAvailable */ }
Future.successful()
}
我想要一个更好的方法来等待 close()
方法中的状态变为 Closed。我填充它,空循环是有史以来最糟糕的主意。
变量 current 保存当前正在处理的 Future,也许有办法将我的结果挂钩到那个 Future?问题是我不知道 disable()
方法什么时候真正开始。任何帮助将不胜感激。
感谢您抽空阅读。
尝试使用Promise
作为一种状态,例如
def loop(): Future[Unit] = {
if(queue.contains(KILL)) Future.successful(disable.trySuccess())
else process()
}
private val disable = Promise[Unit]()
def close(): Future[Unit] = {
queue.add(KILL)
disable.future
}
这样 close()
返回的 Future
只有在 loop()
实际调用 disable.trySuccess
时才会完成。