diff --git a/es/overviews/core/actors.md b/es/overviews/core/actors.md index 525d4dbaf5..26aa06952a 100644 --- a/es/overviews/core/actors.md +++ b/es/overviews/core/actors.md @@ -273,7 +273,7 @@ un future. Estos pueden ser creados utilizando el método `future`. En el siguie ejemplo, `body` se ejecuta de manera concurrente, retornando un future como resultado. - val fut = future { body } + val fut = Future { body } // ... fut() // wait for future diff --git a/ja/overviews/core/futures.md b/ja/overviews/core/futures.md index daa01630ab..bf7432bac0 100644 --- a/ja/overviews/core/futures.md +++ b/ja/overviews/core/futures.md @@ -59,7 +59,7 @@ Future オブジェクトを返すメソッドだということだ。 import ExecutionContext.Implicits.global val session = socialNetwork.createSessionFor("user", credentials) - val f: Future[List[Friend]] = future { + val f: Future[List[Friend]] = Future { session.getFriends() } @@ -83,7 +83,7 @@ Future オブジェクトを返すメソッドだということだ。 `NullPointerException` を投げる。この Future `f` は、この例外とともに失敗する: val session = null - val f: Future[List[Friend]] = future { + val f: Future[List[Friend]] = Future { session.getFriends } @@ -99,7 +99,7 @@ Future オブジェクトを返すメソッドだということだ。 テキストファイルがあったとして、その中である特定のキーワードが最初に出てきた位置を知りたいとする。 この計算はファイルの内容をディスクから読み込むのにブロッキングする可能性があるため、他の計算と並行実行するのは理にかなっている。 - val firstOccurence: Future[Int] = future { + val firstOccurence: Future[Int] = Future { val source = scala.io.Source.fromFile("myText.txt") source.toSeq.indexOfSlice("myKeyword") } @@ -129,7 +129,7 @@ Future の実装の多くは、Future の結果を知りたくなったクライ ソーシャルネットワークの例に戻って、最近の自分の投稿した文のリストを取得して画面に表示したいとする。 これは `List[String]` を返す `getRecentPosts` メソッドを呼ぶことで行われ、戻り値には最近の文のリストが入っている: - val f: Future[List[String]] = future { + val f: Future[List[String]] = Future { session.getRecentPosts } @@ -141,7 +141,7 @@ Future の実装の多くは、Future の結果を知りたくなったクライ `onComplete` メソッドは、Future 計算の失敗と成功の両方の結果を扱えるため、汎用性が高い。 成功した結果のみ扱う場合は、(部分関数を受け取る) `onSuccess` コールバックを使う: - val f: Future[List[String]] = future { + val f: Future[List[String]] = Future { session.getRecentPosts } @@ -151,7 +151,7 @@ Future の実装の多くは、Future の結果を知りたくなったクライ 失敗した結果のみ扱う場合は、`onFailure` コールバックを使う: - val f: Future[List[String]] = future { + val f: Future[List[String]] = Future { session.getRecentPosts } @@ -168,7 +168,7 @@ Future の実装の多くは、Future の結果を知りたくなったクライ 部分関数は `isDefinedAt` メソッドを持つため、`onFailure` メソッドはコールバックが特定の `Throwable` に対して定義されている場合のみ発火される。 以下の例では、登録された `onFailure` コールバックは発火されない: - val f = future { + val f = Future { 2 / 0 } @@ -179,7 +179,7 @@ Future の実装の多くは、Future の結果を知りたくなったクライ キーワードの初出の位置を検索する例に戻ると、キーワードの位置を画面に表示したいかもしれない: - val firstOccurence: Future[Int] = future { + val firstOccurence: Future[Int] = Future { val source = scala.io.Source.fromFile("myText.txt") source.toSeq.indexOfSlice("myKeyword") } @@ -208,7 +208,7 @@ Future 内の値が利用可能となることを必要とするため、Future @volatile var totalA = 0 - val text = future { + val text = Future { "na" * 16 + "BATMAN!!!" } @@ -253,12 +253,12 @@ Future 内の値が利用可能となることを必要とするため、Future 為替トレードサービスの API があって、米ドルを有利な場合のみ買いたいとする。 まずコールバックを使ってこれを実現してみよう: - val rateQuote = future { + val rateQuote = Future { connection.getCurrentValue(USD) } rateQuote onSuccess { case quote => - val purchase = future { + val purchase = Future { if (isProfitable(quote)) connection.buy(amount, quote) else throw new Exception("有益ではない") } @@ -292,7 +292,7 @@ Future の投射はコレクションの投射と同様に考えることがで 上の例を `map` コンビネータを使って書き換えてみよう: - val rateQuote = future { + val rateQuote = Future { connection.getCurrentValue(USD) } @@ -329,8 +329,8 @@ Future の設計指針の 1つは for 内包表記から利用できるように 両方の貨幣の為替レートを取得して、両者の値に応じて購入を決定する必要がある。 以下に for 内包表記を使った `flatMap` と `withFilter` の例をみてみよう: - val usdQuote = future { connection.getCurrentValue(USD) } - val chfQuote = future { connection.getCurrentValue(CHF) } + val usdQuote = Future { connection.getCurrentValue(USD) } + val chfQuote = Future { connection.getCurrentValue(CHF) } val purchase = for { usd <- usdQuote @@ -405,12 +405,12 @@ Future は同じ `Throwable` とともに失敗する。 この Future と引数の Future が両方失敗した場合は、新しい Future はこの Future の例外とともに失敗する。 以下に米ドルの値を表示することを試みて、米ドルの取得に失敗した場合はスイス・フランの値を表示する具体例をみてみよう: - val usdQuote = future { + val usdQuote = Future { connection.getCurrentValue(USD) } map { usd => "値: " + usd + " USD" } - val chfQuote = future { + val chfQuote = Future { connection.getCurrentValue(CHF) } map { chf => "値: " + chf + "CHF" @@ -429,7 +429,7 @@ Future は同じ `Throwable` とともに失敗する。 val allposts = mutable.Set[String]() - future { + Future { session.getRecentPosts } andThen { posts => allposts ++= posts @@ -449,14 +449,14 @@ Future は同じ `Throwable` とともに失敗する。 もし元の Future が成功した場合は、`failed` 投射は `NoSuchElementException` とともに失敗する。以下は例外を画面に表示する具体例だ: - val f = future { + val f = Future { 2 / 0 } for (exc <- f.failed) println(exc) 以下の例は画面に何も表示しない: - val f = future { + val f = Future { 4 / 2 } for (exc <- f.failed) println(exc) @@ -474,11 +474,11 @@ the throwable types it matches. --> ### Future の拡張 @@ -501,7 +501,7 @@ Future の結果に対してブロックする方法を以下に具体例で説 import scala.concurrent.duration._ def main(args: Array[String]) { - val rateQuote = future { + val rateQuote = Future { connection.getCurrentValue(USD) } @@ -568,19 +568,19 @@ Promise の `p` は `p.future` によって返される Future を完了させ ある計算が値を生産し、別の計算がそれを消費する Producer-Consumer の具体例を使って説明しよう。 この値の受け渡しは Promise を使って実現している。 - import scala.concurrent.{ future, promise } + import scala.concurrent.{ Future, Promise } import scala.concurrent.ExecutionContext.Implicits.global - val p = promise[T] + val p = Promise[T]() val f = p.future - val producer = future { + val producer = Future { val r = produceSomething() p success r continueDoingSomethingUnrelated() } - val consumer = future { + val consumer = Future { startDoingSomething() f onSuccess { case r => doSomethingWithResult() @@ -599,10 +599,10 @@ Promise の `p` は `p.future` によって返される Future を完了させ 以下は Promise を失敗させる具体例だ。 - val p = promise[T] + val p = Promise[T]() val f = p.future - val producer = future { + val producer = Future { val r = someComputation if (isInvalid(r)) p failure (new IllegalStateException) @@ -639,8 +639,8 @@ HTTP レスポンスにのみ興味がある場合で、これは最初に Promi 渡された Future が完了すると、その Promise も Future の値とともに完了する。 以下のプログラムは `1` と表示する: - val f = future { 1 } - val p = promise[Int] + val f = Future { 1 } + val p = Promise[Int]() p completeWith f @@ -662,7 +662,7 @@ Promise、Future の `onComplete` メソッド、そして `future` 以下のように書くことができる: def first[T](f: Future[T], g: Future[T]): Future[T] = { - val p = promise[T] + val p = Promise[T]() f onSuccess { case x => p.tryComplete(x) diff --git a/overviews/core/_posts/2010-11-30-actors.md b/overviews/core/_posts/2010-11-30-actors.md index 0493ff979f..98df5726f8 100644 --- a/overviews/core/_posts/2010-11-30-actors.md +++ b/overviews/core/_posts/2010-11-30-actors.md @@ -275,11 +275,11 @@ In addition, a `Future` can be queried to find out whether its result is available without blocking using the `isSet` method. A message send-with-future is not the only way to obtain a -future. Futures can also be created from computations using the `future` -method. In the following example, the computation body is started to +future. Futures can also be created from computations directly. +In the following example, the computation body is started to run concurrently, returning a future for its result: - val fut = future { body } + val fut = Future { body } // ... fut() // wait for future diff --git a/overviews/core/_posts/2012-09-20-futures.md b/overviews/core/_posts/2012-09-20-futures.md index b5dcdd70dc..a0313df542 100644 --- a/overviews/core/_posts/2012-09-20-futures.md +++ b/overviews/core/_posts/2012-09-20-futures.md @@ -887,10 +887,10 @@ Consider the following producer-consumer example, in which one computation produces a value and hands it off to another computation which consumes that value. This passing of the value is done using a promise. - import scala.concurrent.{ future, promise } + import scala.concurrent.{ Future, Promise } import scala.concurrent.ExecutionContext.Implicits.global - val p = promise[T] + val p = Promise[T]() val f = p.future val producer = Future { @@ -922,7 +922,7 @@ promise that has already been completed (or failed) will throw an The following example shows how to fail a promise. - val p = promise[T] + val p = Promise[T]() val f = p.future val producer = Future { @@ -971,7 +971,7 @@ future. After the future is completed, the promise gets completed with the result of that future as well. The following program prints `1`: val f = Future { 1 } - val p = promise[Int] + val p = Promise[Int]() p completeWith f diff --git a/sips/completed/_posts/2012-01-21-futures-promises.md b/sips/completed/_posts/2012-01-21-futures-promises.md index 8090c5c624..bbe61d0a7e 100644 --- a/sips/completed/_posts/2012-01-21-futures-promises.md +++ b/sips/completed/_posts/2012-01-21-futures-promises.md @@ -58,10 +58,10 @@ popular social network to obtain a list of friends for a given user. After opening a new session we want to create an asynchronous request to the server for this list: - import scala.concurrent.future + import scala.concurrent.Future val session = socialNetwork.createSessionFor("user", credentials) - val f: Future[List[Friend]] = future { + val f: Future[List[Friend]] = Future { session.getFriends } @@ -73,7 +73,7 @@ the following example, the `session` value is incorrectly initialized, so the future will hold a `NullPointerException` instead of the value: val session = null - val f: Future[List[Friend]] = future { + val f: Future[List[Friend]] = Future { session.getFriends } @@ -101,7 +101,7 @@ Coming back to our social network example, let's assume we want to fetch a list of our own recent posts and render them to the screen. We do so by calling the method `getRecentPosts` which returns a `List[String]`: - val f: Future[List[String]] = future { + val f: Future[List[String]] = Future { session.getRecentPosts } @@ -115,7 +115,7 @@ client to handle the result of both failed and successful future computations. To handle only successful results, the `onSuccess` callback is used (which takes a partial function): - val f: Future[List[String]] = future { + val f: Future[List[String]] = Future { session.getRecentPosts } @@ -125,7 +125,7 @@ callback is used (which takes a partial function): To handle failed results, the `onFailure` callback is used: - val f: Future[List[String]] = future { + val f: Future[List[String]] = Future { session.getRecentPosts } @@ -148,7 +148,7 @@ Since partial functions have the `isDefinedAt` method, the `onFailure` method only triggers the callback if it is defined for a particular `Throwable`. In the following example the registered callback is never triggered: - val f = future { + val f = Future { 2 / 0 } @@ -215,12 +215,12 @@ interfacing with a currency trading service. Suppose we want to buy US dollars, but only when it's profitable. We first show how this could be done using callbacks: - val rateQuote = future { + val rateQuote = Future { connection.getCurrentValue(USD) } rateQuote onSuccess { case quote => - val purchase = future { + val purchase = Future { if (isProfitable(quote)) connection.buy(amount, quote) else throw new Exception("not profitable") } @@ -247,7 +247,7 @@ the future, produces a new future that is completed with the mapped value once the original future is successfully completed. Let's rewrite the previous example using the `map` combinator: - val rateQuote = future { + val rateQuote = Future { connection.getCurrentValue(USD) } @@ -278,8 +278,8 @@ Lets assume that we want to exchange US dollars for Swiss francs buying based on both quotes. Here is an example of `flatMap` usage within for-comprehensions: - val usdQuote = future { connection.getCurrentValue(USD) } - val chfQuote = future { connection.getCurrentValue(CHF) } + val usdQuote = Future { connection.getCurrentValue(USD) } + val chfQuote = Future { connection.getCurrentValue(CHF) } val purchase = for { usd <- usdQuote @@ -340,12 +340,12 @@ the exception from this future, as in the following example which tries to print US dollar value, but prints the Swiss franc value in the case it fails to obtain the dollar value: - val usdQuote = future { + val usdQuote = Future { connection.getCurrentValue(USD) } map { usd => "Value: " + usd + "$" } - val chfQuote = future { + val chfQuote = Future { connection.getCurrentValue(CHF) } map { chf => "Value: " + chf + "CHF" @@ -360,12 +360,12 @@ the result of this future or the argument future, whichever completes first, irregardless of success or failure. Here is an example in which the quote which is returned first gets printed: - val usdQuote = future { + val usdQuote = Future { connection.getCurrentValue(USD) } map { usd => "Value: " + usd + "$" } - val chfQuote = future { + val chfQuote = Future { connection.getCurrentValue(CHF) } map { chf => "Value: " + chf + "CHF" @@ -387,7 +387,7 @@ and then renders all the posts to the screen: val allposts = mutable.Set[String]() - future { + Future { session.getRecentPosts } andThen { posts => allposts ++= posts @@ -411,14 +411,14 @@ futures also have projections. If the original future fails, the fails with a `NoSuchElementException`. The following is an example which prints the exception to the screen: - val f = future { + val f = Future { 2 / 0 } for (exc <- f.failed) println(exc) The following example does not print anything to the screen: - val f = future { + val f = Future { 4 / 2 } for (exc <- f.failed) println(exc) @@ -436,11 +436,11 @@ the throwable types it matches. --> ### Extending Futures @@ -462,7 +462,7 @@ Here is an example of how to block on the result of a future: import scala.concurrent._ def main(args: Array[String]) { - val rateQuote = future { + val rateQuote = Future { connection.getCurrentValue(USD) } @@ -487,7 +487,7 @@ external condition or which may not complete the computation at all. The only be called by the execution context implementation itself. To block on the future to obtain its result, the `blocking` method must be used. - val f = future { 1 } + val f = Future { 1 } val one: Int = blocking(f, 0 ns) To allow clients to call 3rd party code which is potentially blocking @@ -554,18 +554,18 @@ may be the case that `p.future == p`. Consider the following producer-consumer example: - import scala.concurrent.{ future, promise } + import scala.concurrent.{ Future, Promise } - val p = promise[T] + val p = Promise[T]() val f = p.future - val producer = future { + val producer = Future { val r = produceSomething() p success r continueDoingSomethingUnrelated() } - val consumer = future { + val consumer = Future { startDoingSomething() f onSuccess { case r => doSomethingWithResult() @@ -588,10 +588,10 @@ promise that has already been completed (or failed) will throw an The following example shows how to fail a promise. - val p = promise[T] + val p = Promise[T]() val f = p.future - val producer = future { + val producer = Future { val r = someComputation if (isInvalid(r)) p failure (new IllegalStateException) @@ -636,8 +636,8 @@ The method `completeWith` completes the promise with another future. After the future is completed, the promise gets completed with the result of that future as well. The following program prints `1`: - val f = future { 1 } - val p = promise[Int] + val f = Future { 1 } + val p = Promise[Int]() p completeWith f diff --git a/sips/pending/_posts/2013-06-10-spores.md b/sips/pending/_posts/2013-06-10-spores.md index 6a43d1f2a9..83c07f9781 100644 --- a/sips/pending/_posts/2013-06-10-spores.md +++ b/sips/pending/_posts/2013-06-10-spores.md @@ -41,7 +41,7 @@ process incoming requests. def receive = { case Request(data) => - future { + Future { val result = transform(data) sender ! Response(result) } diff --git a/zh-cn/overviews/core/actors.md b/zh-cn/overviews/core/actors.md index d77e35689d..17412837d7 100644 --- a/zh-cn/overviews/core/actors.md +++ b/zh-cn/overviews/core/actors.md @@ -160,7 +160,7 @@ ReplyReactor和Actor trait支持发送带有结果的消息(!!方法),其 send-with-future的消息并不是获得future的唯一的方法。future也可以通过future方法计算而得。下述例子中,计算体会被并行地启动运行,并返回一个future实例作为其结果: - val fut = future { body } + val fut = Future { body } // ... fut() // 等待future diff --git a/zh-cn/overviews/core/futures.md b/zh-cn/overviews/core/futures.md index b4f73a66c0..5c7a36f271 100644 --- a/zh-cn/overviews/core/futures.md +++ b/zh-cn/overviews/core/futures.md @@ -63,7 +63,7 @@ Future的一个重要属性在于它只能被赋值一次。一旦给定了某 我们的例子是基于一个假定的社交网络API,此API的计算包含发送网络请求和等待响应。提供一个涉及到你能试着立即使用的异步计算的例子是公平的。假设你有一个文本文件,你想找出一个特定的关键字第一次出现的位置。当磁盘正在检索此文件内容时,这种计算可能会陷入阻塞,因此并行的执行该操作和程序的其他部分是合理的(make sense)。 - val firstOccurrence: Future[Int] = future { + val firstOccurrence: Future[Int] = Future { val source = scala.io.Source.fromFile("myText.txt") source.toSeq.indexOfSlice("myKeyword") } @@ -80,7 +80,7 @@ Future的一个重要属性在于它只能被赋值一次。一旦给定了某 回到我们的社交网络的例子,假设我们想要获取我们最近的帖子并显示在屏幕上,我们通过调用getRecentPosts方法获得一个返回值List[String]——一个近期帖子的列表文本: - val f: Future[List[String]] = future { + val f: Future[List[String]] = Future { session.getRecentPosts } @@ -91,7 +91,7 @@ Future的一个重要属性在于它只能被赋值一次。一旦给定了某 onComplete方法一般在某种意义上它允许客户处理future计算出的成功或失败的结果。对于仅仅处理成功的结果,onSuccess 回调使用如下(该回调以一个偏函数(partial function)为参数): - val f: Future[List[String]] = future { + val f: Future[List[String]] = Future { session.getRecentPosts } @@ -101,7 +101,7 @@ onComplete方法一般在某种意义上它允许客户处理future计算出的 对于处理失败结果,onFailure回调使用如下: - val f: Future[List[String]] = future { + val f: Future[List[String]] = Future { session.getRecentPosts } @@ -117,7 +117,7 @@ onComplete方法一般在某种意义上它允许客户处理future计算出的 因为偏函数具有 isDefinedAt方法, onFailure方法只有在特定的Throwable类型对象中被定义才会触发。下面例子中的onFailure回调永远不会被触发: - val f = future { + val f = Future { 2 / 0 } @@ -128,7 +128,7 @@ onComplete方法一般在某种意义上它允许客户处理future计算出的 回到前面查找某个关键字第一次出现的例子,我们想要在屏幕上打印出此关键字的位置: - val firstOccurrence: Future[Int] = future { + val firstOccurrence: Future[Int] = Future { val source = scala.io.Source.fromFile("myText.txt") source.toSeq.indexOfSlice("myKeyword") } @@ -149,7 +149,7 @@ onComplete方法一般在某种意义上它允许客户处理future计算出的 @volatile var totalA = 0 - val text = future { + val text = Future { "na" * 16 + "BATMAN!!!" } @@ -183,12 +183,12 @@ onComplete方法一般在某种意义上它允许客户处理future计算出的 尽管前文所展示的回调机制已经足够把future的结果和后继计算结合起来的,但是有些时候回调机制并不易于使用,且容易造成冗余的代码。我们可以通过一个例子来说明。假设我们有一个用于进行货币交易服务的API,我们想要在有盈利的时候购进一些美元。让我们先来看看怎样用回调来解决这个问题: - val rateQuote = future { + val rateQuote = Future { connection.getCurrentValue(USD) } rateQuote onSuccess { case quote => - val purchase = future { + val purchase = Future { if (isProfitable(quote)) connection.buy(amount, quote) else throw new Exception("not profitable") } @@ -208,7 +208,7 @@ onComplete方法一般在某种意义上它允许客户处理future计算出的 让我们用map的方法来重构一下前面的例子: - val rateQuote = future { + val rateQuote = Future { connection.getCurrentValue(USD) } @@ -231,8 +231,8 @@ onComplete方法一般在某种意义上它允许客户处理future计算出的 让我们假设我们想把一些美元兑换成瑞士法郎。我们必须为这两种货币报价,然后再在这两个报价的基础上确定交易。下面是一个在for-comprehensions中使用flatMap和withFilter的例子: - val usdQuote = future { connection.getCurrentValue(USD) } - val chfQuote = future { connection.getCurrentValue(CHF) } + val usdQuote = Future { connection.getCurrentValue(USD) } + val chfQuote = Future { connection.getCurrentValue(CHF) } val purchase = for { usd <- usdQuote @@ -281,12 +281,12 @@ purchase只有当usdQuote和chfQuote都完成计算以后才能完成-- 它以 fallbackTo组合器生成的future对象可以在该原future成功完成计算时返回结果,如果原future失败或异常返回future参数对象的成功值。在原future和参数future都失败的情况下,新future对象会完成并返回原future对象抛出的异常。正如下面的例子中,本想打印美元的汇率,但是在获取美元汇率失败的情况下会打印出瑞士法郎的汇率: - val usdQuote = future { + val usdQuote = Future { connection.getCurrentValue(USD) } map { usd => "Value: " + usd + "$" } - val chfQuote = future { + val chfQuote = Future { connection.getCurrentValue(CHF) } map { chf => "Value: " + chf + "CHF" @@ -316,14 +316,14 @@ fallbackTo组合器生成的future对象可以在该原future成功完成计算 为了确保for解构(for-comprehensions)能够返回异常,futures也提供了投影(projections)。如果原future对象失败了,失败的投影(projection)会返回一个带有Throwable类型返回值的future对象。如果原Future成功了,失败的投影(projection)会抛出一个NoSuchElementException异常。下面就是一个在屏幕上打印出异常的例子: - val f = future { + val f = Future { 2 / 0 } for (exc <- f.failed) println(exc) 下面的例子不会在屏幕上打印出任何东西: - val f = future { + val f = Future { 4 / 2 } for (exc <- f.failed) println(exc) @@ -342,7 +342,7 @@ fallbackTo组合器生成的future对象可以在该原future成功完成计算 import scala.concurrent.duration._ def main(args: Array[String]) { - val rateQuote = future { + val rateQuote = Future { connection.getCurrentValue(USD) } @@ -388,19 +388,19 @@ ExecutionException-当因为一个未处理的中断异常、错误或者`scala. 考虑下面的生产者 - 消费者的例子,其中一个计算产生一个值,并把它转移到另一个使用该值的计算。这个传递中的值通过一个promise来完成。 - import scala.concurrent.{ future, promise } + import scala.concurrent.{ Future, Promise } import scala.concurrent.ExecutionContext.Implicits.global - val p = promise[T] + val p = Promise[T]() val f = p.future - val producer = future { + val producer = Future { val r = produceSomething() p success r continueDoingSomethingUnrelated() } - val consumer = future { + val consumer = Future { startDoingSomething() f onSuccess { case r => doSomethingWithResult() @@ -416,7 +416,7 @@ ExecutionException-当因为一个未处理的中断异常、错误或者`scala. val p = promise[T] val f = p.future - val producer = future { + val producer = Future { val r = someComputation if (isInvalid(r)) p failure (new IllegalStateException) @@ -438,7 +438,7 @@ Promises也能通过一个complete方法来实现,这个方法采用了一个` completeWith方法将用另外一个future完成promise计算。当该future结束的时候,该promise对象得到那个future对象同样的值,如下的程序将打印1: - val f = future { 1 } + val f = Future { 1 } val p = promise[Int] p completeWith f