Created
January 15, 2014 09:56
-
-
Save ryoppy/8433643 to your computer and use it in GitHub Desktop.
Scalaでスレッドセーフのメモ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 複数スレッドで++していくとスレッドセーフでないので値がおかしくなる | |
var a = 0 | |
(0 until 10000).par.foreach { _ => a += 1 } | |
println(a) // 6772 | |
// synchronizedを使っても可。 | |
var b = 0 | |
(0 until 10000).par.foreach { _ => synchronized { b += 1 } } | |
println(b) // 10000 | |
// Atomicにしてくれるクラスを使うと正しくなる。 | |
var c = new AtomicInteger(0) | |
(0 until 10000).par.foreach { _ => c.addAndGet(1) } | |
println(c) // 10000 | |
// そもそもimmutableだと大丈夫 | |
val d = 0 | |
val r = (0 until 10000).par.foldLeft(d) { (d, _) => d + 1 } | |
println(r) // 10000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment