-
Notifications
You must be signed in to change notification settings - Fork 105
/
Atomic.scala
133 lines (100 loc) · 2.66 KB
/
Atomic.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package org.learningconcurrency
package ch3
object AtomicUid extends App {
import java.util.concurrent.atomic._
private val uid = new AtomicLong(0L)
def getUniqueId(): Long = uid.incrementAndGet()
execute {
log(s"Got a unique id asynchronously: ${getUniqueId()}")
}
log(s"Got a unique id: ${getUniqueId()}")
}
object AtomicUidCAS extends App {
import java.util.concurrent.atomic._
import scala.annotation.tailrec
private val uid = new AtomicLong(0L)
@tailrec def getUniqueId(): Long = {
val oldUid = uid.get
val newUid = oldUid + 1
if (uid.compareAndSet(oldUid, newUid)) newUid
else getUniqueId()
}
execute {
log(s"Got a unique id asynchronously: $getUniqueId")
}
log(s"Got a unique id: $getUniqueId")
}
object AtomicLock extends App {
import java.util.concurrent.atomic._
private val lock = new AtomicBoolean(false)
def mySynchronized(body: =>Unit): Unit = {
while (!lock.compareAndSet(false, true)) {}
try body
finally lock.set(false)
}
var count = 0
for (i <- 0 until 10) execute {
mySynchronized { count += 1 }
}
Thread.sleep(1000)
log(s"Count is: $count")
}
object AtomicStack {
import java.util.concurrent.atomic._
import scala.concurrent._
import scala.annotation.tailrec
trait Stack
case class Node(head: Int, tail: Stack) extends Stack
case object Bottom extends Stack
private val stack = new AtomicReference[Stack](Bottom)
@tailrec def push(x: Int) {
val oldTop = stack.get()
val newTop = Node(x, oldTop)
if (!stack.compareAndSet(oldTop, newTop)) push(x)
}
@tailrec def pop(): Option[Int] = {
stack.get() match {
case Bottom => None
case oldTop @ Node(head, newTop) =>
if (stack.compareAndSet(oldTop, newTop)) Some(head)
else pop()
}
}
def main(args: Array[String]) {
execute {
@tailrec def poll() {
pop() match {
case Some(-1) =>
log("Got -1. Done!")
case Some(x) =>
log(s"Got $x")
poll()
case None =>
poll()
}
}
poll()
}
push(1)
push(2)
push(3)
Thread.sleep(100)
push(-1)
}
}
object AtomicArrays extends App {
import java.util.concurrent.atomic._
import scala.concurrent._
private val counts = new AtomicIntegerArray(4)
def lowerBound(): Int = {
var cnt = 0
for (i <- 0 until counts.length) cnt += counts.get(i)
cnt
}
for (i <- 0 until counts.length) execute {
for (_ <- 0 until 200) counts.incrementAndGet(i)
}
log(s"Count lower bound: ${lowerBound()}")
log(s"Count lower bound: ${lowerBound()}")
log(s"Count lower bound: ${lowerBound()}")
}