-
Notifications
You must be signed in to change notification settings - Fork 509
/
Ref.scala
269 lines (234 loc) · 7.92 KB
/
Ref.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/*
* Copyright (c) 2017-2018 The Typelevel Cats-effect Project Developers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cats
package effect
package concurrent
import cats.data.State
import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}
import scala.annotation.tailrec
/**
* An asynchronous, concurrent mutable reference.
*
* Provides safe concurrent access and modification of its content, but no
* functionality for synchronisation, which is instead handled by [[Deferred]].
* For this reason, a `Ref` is always initialised to a value.
*
* The default implementation is nonblocking and lightweight, consisting essentially
* of a purely functional wrapper over an `AtomicReference`.
*/
abstract class Ref[F[_], A] {
/**
* Obtains the current value.
*
* Since `Ref` is always guaranteed to have a value, the returned action
* completes immediately after being bound.
*/
def get: F[A]
/**
* Sets the current value to `a`.
*
* The returned action completes after the reference has been successfully set.
*
* Satisfies:
* `r.set(fa) *> r.get == fa`
*/
def set(a: A): F[Unit]
/**
* Eventually sets the current value to the `a`.
*
* The returned action completes after the reference has been lazily set.
*/
def lazySet(a: A): F[Unit]
/**
* Replaces the current value with `a`, returning the previous value.
*/
def getAndSet(a: A): F[A]
/**
* Sets the value to `newValue` if the current value is `expected`.
* Note: reference equality is used here.
*/
def compareAndSet(expected: A, newValue: A): F[Boolean]
/**
* Obtains a snapshot of the current value, and a setter for updating it.
* The setter may noop (in which case `false` is returned) if another concurrent
* call to `access` uses its setter first.
*
* Once it has noop'd or been used once, a setter never succeeds again.
*
* Satisfies:
* `r.access.map(_._1) == r.get`
* `r.access.flatMap { case (v, setter) => setter(f(v)) } == r.tryUpdate(f).map(_.isDefined)`
*/
def access: F[(A, A => F[Boolean])]
/**
* Attempts to modify the current value once, returning `false` if another
* concurrent modification completes between the time the variable is
* read and the time it is set.
*/
def tryUpdate(f: A => A): F[Boolean]
/**
* Like `tryUpdate` but allows the update function to return an output value of
* type `B`. The returned action completes with `None` if the value is not updated
* successfully and `Some(b)` otherwise.
*/
def tryModify[B](f: A => (A, B)): F[Option[B]]
/**
* Modifies the current value using the supplied update function. If another modification
* occurs between the time the current value is read and subsequently updated, the modification
* is retried using the new value. Hence, `f` may be invoked multiple times.
*
* Satisfies:
* `r.update(_ => a) == r.set(a)`
*/
def update(f: A => A): F[Unit]
/**
* Like `tryModify` but does not complete until the update has been successfully made.
*/
def modify[B](f: A => (A, B)): F[B]
/**
* Update the value of this ref with a state computation.
*
* The current value of this ref is used as the initial state and the computed output state
* is stored in this ref after computation completes. If a concurrent modification occurs,
* `None` is returned.
*/
def tryModifyState[B](state: State[A, B]): F[Option[B]]
/**
* Like [[tryModifyState]] but retries the modification until successful.
*/
def modifyState[B](state: State[A, B]): F[B]
}
object Ref {
/**
* Builds a `Ref` value for data types that are [[Sync]]
*
* This builder uses the
* [[https://typelevel.org/cats/guidelines.html#partially-applied-type-params Partially-Applied Type]]
* technique.
*
* {{{
* Ref[IO].of(10) <-> Ref.of[IO, Int](10)
* }}}
*
* @see [[of]]
*/
def apply[F[_]](implicit F: Sync[F]): ApplyBuilders[F] = new ApplyBuilders(F)
/**
* Creates an asynchronous, concurrent mutable reference initialized to the supplied value.
*
* {{{
* import cats.effect.IO
* import cats.effect.concurrent.Ref
*
* for {
* intRef <- Ref.of[IO, Int](10)
* ten <- intRef.get
* } yield ten
* }}}
*
*/
def of[F[_], A](a: A)(implicit F: Sync[F]): F[Ref[F, A]] = F.delay(unsafe(a))
/**
* Like `apply` but returns the newly allocated ref directly instead of wrapping it in `F.delay`.
* This method is considered unsafe because it is not referentially transparent -- it allocates
* mutable state.
*
* This method uses the [[http://typelevel.org/cats/guidelines.html#partially-applied-type-params Partially Applied Type Params technique]],
* so only effect type needs to be specified explicitly.
*
* A care must be taken to preserve referential transparency:
*
* {{{
* import cats.effect.IO
* import cats.effect.concurrent.Ref
*
* class Counter private () {
* private val count = Ref.unsafe[IO](0)
*
* def increment: IO[Unit] = count.modify(_ + 1)
* def total: IO[Int] = count.get
* }
*
* object Counter {
* def apply(): IO[Counter] = IO(new Counter)
* }
* }}}
*
* Such usage is safe, as long as class constructor is not accessible and public one suspends creation in IO
*
* The recommended alternative is accepting a `Ref[F, A]` as a parameter:
*
* {{{
* class Counter (count: Ref[IO, Int]) {
* // same body
* }
*
* object Counter {
* def apply(): IO[Counter] = Ref[IO](0).map(new Counter(_))
* }
* }}}
*/
def unsafe[F[_], A](a: A)(implicit F: Sync[F]): Ref[F, A] = new SyncRef[F, A](new AtomicReference[A](a))
final class ApplyBuilders[F[_]](val F: Sync[F]) extends AnyVal {
/**
* Creates an asynchronous, concurrent mutable reference initialized to the supplied value.
*
* @see [[Ref.of]]
*/
def of[A](a: A): F[Ref[F, A]] = Ref.of(a)(F)
}
private final class SyncRef[F[_], A](ar: AtomicReference[A])(implicit F: Sync[F]) extends Ref[F, A] {
def get: F[A] = F.delay(ar.get)
def set(a: A): F[Unit] = F.delay(ar.set(a))
def lazySet(a: A): F[Unit] = F.delay(ar.lazySet(a))
def getAndSet(a: A): F[A] = F.delay(ar.getAndSet(a))
def compareAndSet(expected: A, newValue: A): F[Boolean] = F.delay(ar.compareAndSet(expected, newValue))
def access: F[(A, A => F[Boolean])] = F.delay {
val snapshot = ar.get
val hasBeenCalled = new AtomicBoolean(false)
def setter = (a: A) => F.delay(hasBeenCalled.compareAndSet(false, true) && ar.compareAndSet(snapshot, a))
(snapshot, setter)
}
def tryUpdate(f: A => A): F[Boolean] =
F.map(tryModify(a => (f(a), ())))(_.isDefined)
def tryModify[B](f: A => (A, B)): F[Option[B]] = F.delay {
val c = ar.get
val (u, b) = f(c)
if (ar.compareAndSet(c, u)) Some(b)
else None
}
def update(f: A => A): F[Unit] =
modify(a => (f(a), ()))
def modify[B](f: A => (A, B)): F[B] = {
@tailrec
def spin: B = {
val c = ar.get
val (u, b) = f(c)
if (!ar.compareAndSet(c, u)) spin
else b
}
F.delay(spin)
}
def tryModifyState[B](state: State[A, B]): F[Option[B]] = {
val f = state.runF.value
tryModify(a => f(a).value)
}
def modifyState[B](state: State[A, B]): F[B] = {
val f = state.runF.value
modify(a => f(a).value)
}
}
}