LoginSignup
1
1

More than 5 years have passed since last update.

parの中でAwaitする場合と、重い処理を書く場合は気をつける

Last updated at Posted at 2015-06-22

最初謎挙動って書いてましたが、謎ではないと指摘された(たしかに)ので、修正。

parの中でAwait

予期しないタイミングでタイムアウトします。

import java.util.Date, scala.concurrent._, scala.concurrent.duration._, scala.concurrent.ExecutionContext.Implicits.global

def elapsed(f: => Unit) = { val s = (new Date).getTime; f; println(((new Date).getTime - s) + "ms") }

(1 to 10).par.foreach { _ => 
  Await.result(Future(elapsed { Thread.sleep(1000) }), 3.seconds)
}

1秒の処理なのに、3秒のタイムアウトに...

scala> import java.util.Date, scala.concurrent._, scala.concurrent.duration._, s 
cala.concurrent.ExecutionContext.Implicits.global
import java.util.Date
import scala.concurrent._
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

scala> def elapsed(f: => Unit) = { val s = (new Date).getTime; f; println(((new  
Date).getTime - s) + "ms") }
elapsed: (f: => Unit)Unit

scala> (1 to 10).par.foreach { _ => Await.result(Future(elapsed { Thread.sleep(1 
000) }), 3.seconds) }
1000ms
1001ms
1000ms
1000ms
1000ms
1000ms
1000ms
1000ms
1000ms
java.util.concurrent.TimeoutException: Futures timed out after [3 seconds]

( ゚д゚)

(つд⊂)ゴシゴシ

(;゚д゚) ・・・ !?

説明はこちら

parの中で重い処理

一つの処理が急に重くなります。

scala> import java.util.Date
import java.util.Date

scala> def f = (1 to 1000000).map(_ + 1)
f: scala.collection.immutable.IndexedSeq[Int]

scala> def elapsed(f: => Unit) = { val s = (new Date).getTime; f; println(((new  
Date).getTime - s) + "ms") }
elapsed: (f: => Unit)Unit

scala> elapsed(f)
738ms

scala> (1 to 20).foreach { _ => elapsed(f) }
38ms
47ms
49ms
40ms
40ms
41ms
41ms
40ms
39ms
40ms
39ms
38ms
37ms
38ms
39ms
40ms
42ms
30ms
32ms
33ms

scala> (1 to 20).par.foreach { _ => elapsed(f) }
3579ms
4842ms
5292ms
6006ms
6443ms
6444ms
6445ms
6801ms
6756ms
6822ms
6242ms
7121ms
1937ms
808ms
1594ms
1161ms
785ms
808ms
801ms
187ms

( ゚д゚)

(つд⊂)ゴシゴシ

(;゚д゚) ・・・ !?

parじゃなくても並列だとこうなるっぽい。
メモリをかなり食うような重い処理で起きるっぽいです。
100倍とか時間かかるので、10秒の処理だと1000秒(16分)とかなって破綻するもよう。実際、破綻したので並列やめたことがあった。

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1