Difference Await.ready and Await.result

末鹿安然 提交于 2020-12-27 17:15:42

问题


I know this is quite an open ended question and I apologize.

I can see that Await.ready returns Awaitable.type while Await.result returns T but I still confuse them.

What are the difference between the two?

Is one blocking and the other one non-blocking?


回答1:


They both block until the future completes, the difference is just their return type.

The difference is useful when your Future throws exceptions:

def a = Future { Thread.sleep(2000); 100 }
def b = Future { Thread.sleep(2000); throw new NullPointerException }

Await.ready(a, Duration.Inf) // Success(100)
Await.ready(b, Duration.Inf) // Failure(java.lang.NullPointerException)

Await.result(a, Duration.Inf) // 100
Await.result(b, Duration.Inf) // crash with java.lang.NullPointerException



回答2:


Both are blocking for at most the given Duration. However, Await.result tries to return the future result right away and throws an exception if the future failed while Await.ready returns the completed future from which the result (Success or Failure) can safely be extracted via the value property.

The latter is very handy when you have to deal with a timeout as well:

val future = Future { Thread.sleep(Random.nextInt(2000)); 123 }

Try(Await.ready(future, 1.second)) match {
    case Success(f) => f.value.get match {
      case Success(res) => // handle future success 
      case Failure(e) => // handle future failure
    }
    case Failure(_) => // handle timeout
}

When using Await.result, the timeout exception and exceptions from failing futures are "mixed up".

Try(Await.result(future, 1.second)) match {
    case Success(res) => // we can deal with the result directly
    case Failure(e) => // but we might have to figure out if a timeout happened
}



回答3:


In general, both are blocking.

The difference is that Await.ready is blocking until the Future has finished (successful or failed) in given time.

The only one difference is that ready blocks until the Awaitable is ready and the result does yield the result type T.

Postscriptum: In practice, if you want to perform some actions like error checking or logging you would take Await.ready(...) if you want to compose the result and throw an error if something goes wrong take Await.result(...).

As rule of thumb - try to avoid Await.



来源:https://stackoverflow.com/questions/41170280/difference-await-ready-and-await-result

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!