scala.concurrent.Future java.util.concurrent.Future的包装器 [英] scala.concurrent.Future wrapper for java.util.concurrent.Future
问题描述
我使用Play Framework 2.1.1与外部的java库,产生一个java.util.concurrent.Future结果。我使用的scala未来,而不是Akka,我认为是正确的事情做Play 2.1。如何将java.util.concurrent.Future包装到scala.concurrent.Future中,同时仍然保持代码无阻塞?
def geConnection():Connection = {
//使用get
阻塞connectionPool.getConnectionAsync()。get(30000,TimeUnit.MILLISECONDS)
}
$上述代码返回一个连接,但使用一个get,所以它变成阻塞
<$> p $ p> def getConnectionFuture():Future [Connection] = {
future {
//如何清除阻塞get和返回一个scala未来?
connectionPool.getConnectionAsync(。)get(30000,TimeUnit.MILLISECONDS)
}
}
理想情况下,我想要一个scala函数,返回的连接作为一个未来像上面的代码,但没有代码通过get阻塞。
任何指针都会很棒。
import java.util.concurrent。{Future => JFuture}
import scala.concurrent。{Future => SFuture}
您不能换行 JFuture
与 SFuture
,因为在<$ c中有回调$ c> SFuture ( onComplete
)并且只有 get
$ c> JFuture 。
所有你可以做的是创建额外的线程并用 get
,然后完成 承诺
,结果为 get
。
val jfuture:JFuture [T] =?
val promise = Promise [T]()
new Thread(new Runnable {def run(){promise.complete(Try {jfuture.get})}})。 = promise.future
您可以检查 isDone
在无限循环,但我不认为这是更好然后阻止。
I'm using Play Framework 2.1.1 with an external java library that produces a java.util.concurrent.Future result. I'm using the scala future's as opposed to Akka which I think is the right thing to do as of Play 2.1. How can I wrap the java.util.concurrent.Future up into a scala.concurrent.Future while still keeping the code non-blocking?
def geConnection() : Connection = {
// blocking with get
connectionPool.getConnectionAsync().get(30000, TimeUnit.MILLISECONDS)
}
The above code returns a connection but uses a get so it becomes blocking
def getConnectionFuture() : Future[Connection] = {
future {
// how to remove blocking get and return a scala future?
connectionPool.getConnectionAsync().get(30000, TimeUnit.MILLISECONDS)
}
}
Ideally I want a scala function that returns the connection as a future like the code above but without the code blocking via the get. What else do I need to put into the function to make it non blocking.
Any pointers would be great.
import java.util.concurrent.{Future => JFuture}
import scala.concurrent.{Future => SFuture}
You can't wrap JFuture
with SFuture
without blocking since there is a callback in SFuture
(onComplete
) and there is only blocking get
in JFuture
.
All you can do is to create additional thread and block it with get
, then complete Promise
with result of get
.
val jfuture: JFuture[T] = ???
val promise = Promise[T]()
new Thread(new Runnable { def run() { promise.complete(Try{ jfuture.get }) }}).start
val future = promise.future
You could check isDone
in endless loop, but I don't think it is better then blocking.
这篇关于scala.concurrent.Future java.util.concurrent.Future的包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!