java.util.concurrent.Future 的 scala.concurrent.Future 包装器 [英] scala.concurrent.Future wrapper for java.util.concurrent.Future

查看:25
本文介绍了java.util.concurrent.Future 的 scala.concurrent.Future 包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Play Framework 2.1.1 与一个产生 java.util.concurrent.Future 结果的外部 java 库一起使用.我正在使用 scala 未来而不是 Akka,我认为这是从 Play 2.1 开始的正确做法.如何将 java.util.concurrent.Future 包装到 scala.concurrent.Future 中,同时仍然保持代码非阻塞?

def geConnection() : Connection = {//使用 get 阻塞connectionPool.getConnectionAsync().get(30000, TimeUnit.MILLISECONDS)}

上面的代码返回一个连接但是使用了一个get,所以它变成了阻塞

def getConnectionFuture() : Future[Connection] = {未来 {//如何移除阻塞 get 并返回一个 Scala 未来?connectionPool.getConnectionAsync().get(30000, TimeUnit.MILLISECONDS)}}

理想情况下,我想要一个 Scala 函数,它像上面的代码一样将连接作为未来返回,但不会通过 get 阻塞代码.我还需要在函数中添加什么才能使其非阻塞.

任何指针都会很棒.

解决方案

import java.util.concurrent.{Future =>J未来}导入 scala.concurrent.{Future =>未来}

你不能包装 JFutureSFuture 没有阻塞,因为 SFuture (onComplete) 中有回调,而 JFuture 中只有阻塞 get.

您所能做的就是创建额外的线程并使用 get 阻止它,然后完成 Promise 带有 get 的结果.

val jfuture: JFuture[T] = ???val promise = Promise[T]()new Thread(new Runnable { def run() { promise.complete(Try{ jfuture.get }) }}).startval 未来 = 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.

这篇关于java.util.concurrent.Future 的 scala.concurrent.Future 包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆