【发布时间】:2019-12-18 21:48:35
【问题描述】:
我正在使用一个库,它的方法看起来像这样。
trait LibraryDependency {
/**
* This method if called while previous future is not resolved will return a failed future
* @return
*/
def foo(): Future[Boolean]
}
这里,如果foo() 返回的前一个未来尚未完成,那么foo() 方法将返回一个失败的未来。由于我无法修改库的 trait 实现,因此我尝试用我自己的包装器来包装它,以提供我需要的行为。
我需要的行为是,如果有对foo() 的并发调用,那么其他期货也将阻塞,直到第一个期货被解决。我试图做这样的事情。
class ThreadSafeLibraryWrapper(delegate: LibraryDependency) extends LibraryDependency {
private val lock: Object = new Object
private implicit val ec: ExecutionContext = ExecutionContext.Implicits.global
/**
* This one will block the other concurrent calls to foo()
* @return
*/
override def foo(): Future[Boolean] = {
val promise = Promise[Boolean]()
lock.synchronized {
val result = delegate.foo()
promise.completeWith(result)
result.onComplete { _ =>
lock.notify()
}
lock.wait()
}
promise.future
}
}
我遇到了下面的问题,不知道怎么阻塞调用这个方法的线程,完成原来的future,得到IllegalMonitorStateException。
编辑:我已经使用Await解决了这个问题
class ThreadSafeLibraryWrapper(delegate: LibraryDependency) extends LibraryDependency {
private val lock: Object = new Object
private implicit val ec: ExecutionContext = ExecutionContext.Implicits.global
/**
* This one will block the other concurrent calls to foo()
* @return
*/
override def foo(): Future[Boolean] = Future {
lock.synchronized {
Await.result(delegate.foo(), Duration.Inf)
}
}
}
我仍然不确定如何避免Await。
【问题讨论】:
标签: scala concurrency locking