-
Notifications
You must be signed in to change notification settings - Fork 451
/
Copy pathSTM.kt
1596 lines (1540 loc) · 43.6 KB
/
STM.kt
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package arrow.fx.stm
import arrow.fx.stm.internal.STMTransaction
import arrow.fx.stm.internal.alterHamtWithHash
import arrow.fx.stm.internal.lookupHamtWithHash
/**
* # Consistent and safe concurrent state updates
*
* Software transactional memory, or STM, is an abstraction for concurrent state modification.
* With [STM] one can write code that concurrently accesses state and that can easily be composed without
* exposing details of how it ensures safety guarantees.
* Programs running within an [STM] transaction will neither deadlock nor have race-conditions.
*
* > The api of [STM] is based on the haskell package [stm](https://hackage.haskell.org/package/stm) and the implementation is based on the GHC implementation for fine-grained locks.
*
* The base building blocks of [STM] are [TVar]'s and the primitives [retry], [orElse] and [catch].
*
* ## STM Datastructures
*
* There are several datastructures built on top of [TVar]'s already provided out of the box:
* - [TQueue]: A transactional mutable queue
* - [TMVar]: A mutable transactional variable that may be empty
* - [TSet], [TMap]: Transactional Set and Map
* - [TArray]: Array of [TVar]'s
* - [TSemaphore]: Transactional semaphore
* - [TVar]: A transactional mutable variable
*
* All of these structures (excluding [TVar]) are built upon [TVar]'s and the [STM] primitives and implementing other
* datastructures with [STM] can be done by composing the existing structures.
*
* ## Reading and writing to concurrent state:
*
* In order to modify transactional datastructures we have to be inside the [STM] context. This is achieved either by defining our
* functions with [STM] as the receiver or using [stm] to create lambda functions with [STM] as the receiver.
*
* Running a transaction is then done using [atomically]:
*
* ```kotlin
* import arrow.fx.stm.atomically
* import arrow.fx.stm.TVar
* import arrow.fx.stm.STM
*
* //sampleStart
* fun STM.transfer(from: TVar<Int>, to: TVar<Int>, amount: Int): Unit {
* withdraw(from, amount)
* deposit(to, amount)
* }
*
* fun STM.deposit(acc: TVar<Int>, amount: Int): Unit {
* val current = acc.read()
* acc.write(current + amount)
* // or the shorthand acc.modify { it + amount }
* }
*
* fun STM.withdraw(acc: TVar<Int>, amount: Int): Unit {
* val current = acc.read()
* if (current - amount >= 0) acc.write(current - amount)
* else throw IllegalStateException("Not enough money in the account!")
* }
* //sampleEnd
*
* suspend fun main() {
* val acc1 = TVar.new(500)
* val acc2 = TVar.new(300)
* println("Balance account 1: ${acc1.unsafeRead()}")
* println("Balance account 2: ${acc2.unsafeRead()}")
* println("Performing transaction")
* atomically { transfer(acc1, acc2, 50) }
* println("Balance account 1: ${acc1.unsafeRead()}")
* println("Balance account 2: ${acc2.unsafeRead()}")
* }
* ```
* <!--- KNIT example-stm-01.kt -->
* This example shows a banking service moving money from one account to the other with [STM].
* Should the first account not have enough money we throw an exception. This code is guaranteed to never deadlock and to never
* produce an invalid state by committing after the read state has changed concurrently.
*
* > Note: A transaction that sees an invalid state (a [TVar] that was read has been changed concurrently) will restart and try again.
* This usually means we rerun the function entirely, therefore it is recommended to keep transactions small and to never use code that
* has side-effects inside. However no kotlin interface can actually keep you from doing side effects inside STM.
* Using side-effects such as access to resources, logging or network access comes with severe disadvantages:
* - Transactions may be aborted at any time so accessing resources may never trigger finalizers
* - Transactions may rerun an arbitrary amount of times before finishing and thus all effects will rerun.
*
* ## Retrying manually
*
* It is sometimes beneficial to manually abort the current transaction if, for example, an invalid state has been read. E.g. a [TQueue] had no elements to read.
* The aborted transaction will automatically restart once any previously accessed variable has changed.
*
* This is achieved by the primitive [retry]:
*
* ```kotlin
* import arrow.fx.stm.atomically
* import arrow.fx.stm.TVar
* import arrow.fx.stm.STM
* import kotlinx.coroutines.runBlocking
* import kotlinx.coroutines.async
* import kotlinx.coroutines.delay
*
* //sampleStart
* fun STM.transfer(from: TVar<Int>, to: TVar<Int>, amount: Int): Unit {
* withdraw(from, amount)
* deposit(to, amount)
* }
*
* fun STM.deposit(acc: TVar<Int>, amount: Int): Unit {
* val current = acc.read()
* acc.write(current + amount)
* // or the shorthand acc.modify { it + amount }
* }
*
* fun STM.withdraw(acc: TVar<Int>, amount: Int): Unit {
* val current = acc.read()
* if (current - amount >= 0) acc.write(current - amount)
* else retry() // we now retry if there is not enough money in the account
* // this can also be achieved by using `check(current - amount >= 0); acc.write(it + amount)`
* }
* //sampleEnd
*
* fun main(): Unit = runBlocking {
* val acc1 = TVar.new(0)
* val acc2 = TVar.new(300)
* println("Balance account 1: ${acc1.unsafeRead()}")
* println("Balance account 2: ${acc2.unsafeRead()}")
* async {
* println("Sending money - Searching")
* delay(2000)
* println("Sending money - Found some")
* atomically { acc1.write(100_000_000) }
* }
* println("Performing transaction")
* atomically {
* println("Trying to transfer")
* transfer(acc1, acc2, 50)
* }
* println("Balance account 1: ${acc1.unsafeRead()}")
* println("Balance account 2: ${acc2.unsafeRead()}")
* }
* ```
* <!--- KNIT example-stm-02.kt -->
*
* Here in this (silly) example we changed `withdraw` to use [retry] and thus wait until enough money is in the account, which after
* a few seconds just happens to be the case.
*
* [retry] can be used to implement a lot of complex transactions and many datastructures like [TMVar] or [TQueue] use to to great effect.
*
* ## Branching with [orElse]
*
* [orElse] is another important primitive which allows a user to detect if a branch called [retry] and then use a fallback instead.
* If the fallback retries as well the whole transaction retries.
*
* ```kotlin
* import kotlinx.coroutines.runBlocking
* import arrow.fx.stm.atomically
* import arrow.fx.stm.TVar
* import arrow.fx.stm.STM
* import arrow.fx.stm.stm
*
* //sampleStart
* fun STM.transaction(v: TVar<Int>): Int? =
* stm {
* val result = v.read()
* check(result in 0..10)
* result
* } orElse { null }
* //sampleEnd
*
* fun main(): Unit = runBlocking {
* val v = TVar.new(100)
* println("Value is ${v.unsafeRead()}")
* atomically { transaction(v) }
* .also { println("Transaction returned $it") }
* println("Set value to 5")
* println("Value is ${v.unsafeRead()}")
* atomically { v.write(5) }
* atomically { transaction(v) }
* .also { println("Transaction returned $it") }
* }
* ```
* <!--- KNIT example-stm-03.kt -->
*
* This example uses [stm] which is a helper just like the stdlib function [suspend] to ease use of an infix function like [orElse].
* In this transaction, when the value inside the variable is not in the correct range, the transaction retries (due to [check] calling [retry]).
* If it is in the correct range it simply returns the value. [orElse] here intercepts a call to [retry] and executes the alternative which simply returns null.
*
* ## Exceptions
*
* Throwing inside [STM] will let the exception bubble up to either a [catch] handler or to [atomically] which will rethrow it.
*
* > Note: Using `try {...} catch (e: Exception) {...}` is not encouraged because any state change inside `try` will not be undone when
* an exception occurs! The recommended way of catching exceptions is to use [catch] which properly rolls back the transaction!
*
* Further reading:
* - [Composable memory transactions, by Tim Harris, Simon Marlow, Simon Peyton Jones, and Maurice Herlihy, in ACM Conference on Principles and Practice of Parallel Programming 2005.](https://www.microsoft.com/en-us/research/publication/composable-memory-transactions/)
*/
// TODO Explore this https://dl.acm.org/doi/pdf/10.1145/2976002.2976020 when benchmarks are set up
public interface STM {
/**
* Abort and retry the current transaction.
*
* Aborts the transaction and suspends until any of the accessed [TVar]'s changed, after which the transaction will restart.
* Since all other datastructures are built upon [TVar]'s this automatically extends to those structures as well.
*
* The main use for this is to abort once the transaction has hit an invalid state or otherwise needs to wait for changes.
*
* ```kotlin
* import arrow.fx.stm.atomically
* import arrow.fx.stm.stm
*
* suspend fun main() {
* //sampleStart
* val result = atomically {
* stm { retry() } orElse { "Alternative" }
* }
* //sampleEnd
* println("Result $result")
* }
* ```
* <!--- KNIT example-stm-04.kt -->
*/
public fun retry(): Nothing
/**
* Run the given transaction and fallback to the other one if the first one calls [retry].
*
* ```kotlin
* import arrow.fx.stm.atomically
* import arrow.fx.stm.stm
*
* suspend fun main() {
* //sampleStart
* val result = atomically {
* stm { retry() } orElse { "Alternative" }
* }
* //sampleEnd
* println("Result $result")
* }
* ```
* <!--- KNIT example-stm-05.kt -->
*/
public infix fun <A> (STM.() -> A).orElse(other: STM.() -> A): A
/**
* Run [f] and handle any exception thrown with [onError].
*
* ```kotlin
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val result = atomically {
* catch({ throw Throwable() }) { _ -> "caught" }
* }
* //sampleEnd
* println("Result $result")
* }
* ```
* <!--- KNIT example-stm-06.kt -->
*/
public fun <A> catch(f: STM.() -> A, onError: STM.(Throwable) -> A): A
/**
* Read the value from a [TVar].
*
* ```kotlin
* import arrow.fx.stm.TVar
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tvar = TVar.new(10)
* val result = atomically {
* tvar.read()
* }
* //sampleEnd
* println(result)
* }
* ```
* <!--- KNIT example-stm-07.kt -->
*
* This comes with a few guarantees:
* - Any given [TVar] is only ever read once during a transaction.
* - When committing the transaction the value read has to be equal to the current value otherwise the
* transaction will retry
*/
public fun <A> TVar<A>.read(): A
/**
* Set the value of a [TVar].
*
* ```kotlin
* import arrow.fx.stm.TVar
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tvar = TVar.new(10)
* val result = atomically {
* tvar.write(20)
* }
* //sampleEnd
* println(result)
* }
* ```
* <!--- KNIT example-stm-08.kt -->
*
* Similarly to [read] this comes with a few guarantees:
* - For multiple writes to the same [TVar] in a transaction only the last will actually be performed
* - When committing the value inside the [TVar], at the time of calling [write], has to be the
* same as the current value otherwise the transaction will retry
*/
public fun <A> TVar<A>.write(a: A): Unit
/**
* Modify the value of a [TVar]
*
* ```kotlin
* import arrow.fx.stm.TVar
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tvar = TVar.new(10)
* val result = atomically {
* tvar.modify { it * 2 }
* }
* //sampleEnd
* println(result)
* }
* ```
* <!--- KNIT example-stm-09.kt -->
*
* `modify(f) = write(f(read()))`
*/
public fun <A> TVar<A>.modify(f: (A) -> A): Unit = write(f(read()))
/**
* Swap the content of the [TVar]
*
* ```kotlin
* import arrow.fx.stm.TVar
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tvar = TVar.new(10)
* val result = atomically {
* tvar.swap(20)
* }
* //sampleEnd
* println("Result $result")
* println("New value ${tvar.unsafeRead()}")
* }
* ```
* <!--- KNIT example-stm-10.kt -->
*
* @return The previous value stored inside the [TVar]
*/
public fun <A> TVar<A>.swap(a: A): A = read().also { write(a) }
/**
* Create a new [TVar] inside a transaction, because [TVar.new] is not possible inside [STM] transactions.
*/
public fun <A> newTVar(a: A): TVar<A> = TVar(a)
// -------- TMVar
/**
* Read the value from a [TMVar] and empty it.
*
* ```kotlin
* import arrow.fx.stm.TMVar
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tmvar = TMVar.new(10)
* val result = atomically {
* tmvar.take()
* }
* //sampleEnd
* println("Result $result")
* println("New value ${atomically { tmvar.tryTake() } }")
* }
* ```
* <!--- KNIT example-stm-11.kt -->
*
* This retries if the [TMVar] is empty and leaves the [TMVar] empty if it succeeded.
*
* @see TMVar.tryTake for a version that does not retry.
* @see TMVar.read for a version that does not remove the value after reading.
*/
public fun <A> TMVar<A>.take(): A = when (val ret = v.read()) {
is Option.Some -> ret.a.also { v.write(Option.None) }
Option.None -> retry()
}
/**
* Put a value into an empty [TMVar].
*
* ```kotlin
* import arrow.fx.stm.TMVar
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tmvar = TMVar.empty<Int>()
* atomically {
* tmvar.put(20)
* }
* //sampleEnd
* println("New value ${atomically { tmvar.tryTake() } }")
* }
* ```
* <!--- KNIT example-stm-12.kt -->
*
* This retries if the [TMVar] is not empty.
*
* For a version of [TMVar.put] that does not retry see [TMVar.tryPut]
*/
public fun <A> TMVar<A>.put(a: A): Unit = when (v.read()) {
is Option.Some -> retry()
Option.None -> v.write(Option.Some(a))
}
/**
* Read a value from a [TMVar] without removing it.
*
* ```kotlin
* import arrow.fx.stm.TMVar
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tmvar = TMVar.new(30)
* val result = atomically {
* tmvar.read()
* }
* //sampleEnd
* println("Result $result")
* println("New value ${atomically { tmvar.tryTake() } }")
* }
* ```
* <!--- KNIT example-stm-13.kt -->
*
* This retries if the [TMVar] is empty but does not take the value out if it succeeds.
*
* @see TMVar.tryRead for a version that does not retry.
* @see TMVar.take for a version that leaves the [TMVar] empty after reading.
*/
public fun <A> TMVar<A>.read(): A = when (val ret = v.read()) {
is Option.Some -> ret.a
Option.None -> retry()
}
/**
* Same as [TMVar.take] except it returns null if the [TMVar] is empty and thus never retries.
*
* ```kotlin
* import arrow.fx.stm.TMVar
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tmvar = TMVar.empty<Int>()
* val result = atomically {
* tmvar.tryTake()
* }
* //sampleEnd
* println("Result $result")
* println("New value ${atomically { tmvar.tryTake() } }")
* }
* ```
* <!--- KNIT example-stm-14.kt -->
*/
public fun <A> TMVar<A>.tryTake(): A? = when (val ret = v.read()) {
is Option.Some -> ret.a.also { v.write(Option.None) }
Option.None -> null
}
/**
* Same as [TMVar.put] except that it returns true or false if was successful or it retried.
*
* ```kotlin
* import arrow.fx.stm.TMVar
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tmvar = TMVar.new(20)
* val result = atomically {
* tmvar.tryPut(30)
* }
* //sampleEnd
* println("Result $result")
* println("New value ${atomically { tmvar.tryTake() } }")
* }
* ```
* <!--- KNIT example-stm-15.kt -->
*
* This function never retries.
*
* @see TMVar.put for a function that retries if the [TMVar] is not empty.
*/
public fun <A> TMVar<A>.tryPut(a: A): Boolean = when (v.read()) {
is Option.Some -> false
Option.None -> true.also { v.write(Option.Some(a)) }
}
/**
* Same as [TMVar.read] except that it returns null if the [TMVar] is empty and thus never retries.
*
* ```kotlin
* import arrow.fx.stm.TMVar
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tmvar = TMVar.empty<Int>()
* val result = atomically {
* tmvar.tryRead()
* }
* //sampleEnd
* println("Result $result")
* }
* ```
* <!--- KNIT example-stm-16.kt -->
*
* @see TMVar.read for a function that retries if the [TMVar] is empty.
* @see TMVar.tryTake for a function that leaves the [TMVar] empty after reading.
*/
public fun <A> TMVar<A>.tryRead(): A? = when (val ret = v.read()) {
is Option.Some -> ret.a
Option.None -> null
}
/**
* Check if a [TMVar] is empty. This function never retries.
*
* ```kotlin
* import arrow.fx.stm.TMVar
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tmvar = TMVar.empty<Int>()
* val result = atomically {
* tmvar.isEmpty()
* }
* //sampleEnd
* println("Result $result")
* }
* ```
* <!--- KNIT example-stm-17.kt -->
*
* > Because the state of a transaction is constant there can never be a race condition between checking if a `TMVar` is empty and subsequent
* reads in the *same* transaction.
*/
public fun <A> TMVar<A>.isEmpty(): Boolean = v.read() is Option.None
/**
* Check if a [TMVar] is not empty. This function never retries.
*
* ```kotlin
* import arrow.fx.stm.TMVar
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tmvar = TMVar.empty<Int>()
* val result = atomically {
* tmvar.isNotEmpty()
* }
* //sampleEnd
* println("Result $result")
* }
* ```
* <!--- KNIT example-stm-18.kt -->
*
* > Because the state of a transaction is constant there can never be a race condition between checking if a `TMVar` is empty and subsequent
* reads in the *same* transaction.
*/
public fun <A> TMVar<A>.isNotEmpty(): Boolean =
isEmpty().not()
/**
* Swap the content of a [TMVar] or retry if it is empty.
*
* ```kotlin
* import arrow.fx.stm.TMVar
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tmvar = TMVar.new(30)
* val result = atomically {
* tmvar.swap(40)
* }
* //sampleEnd
* println("Result $result")
* println("New value ${atomically { tmvar.tryTake() } }")
* }
* ```
* <!--- KNIT example-stm-19.kt -->
*/
public fun <A> TMVar<A>.swap(a: A): A = when (val ret = v.read()) {
is Option.Some -> ret.a.also { v.write(Option.Some(a)) }
Option.None -> retry()
}
// -------- TSemaphore
/**
* Returns the currently available number of permits in a [TSemaphore].
*
* ```kotlin
* import arrow.fx.stm.TSemaphore
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tsem = TSemaphore.new(5)
* val result = atomically {
* tsem.available()
* }
* //sampleEnd
* println("Result $result")
* println("Permits remaining ${atomically { tsem.available() }}")
* }
* ```
* <!--- KNIT example-stm-20.kt -->
*
* This function never retries.
*/
public fun TSemaphore.available(): Int =
v.read()
/**
* Acquire 1 permit from a [TSemaphore].
*
* ```kotlin
* import arrow.fx.stm.TSemaphore
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tsem = TSemaphore.new(5)
* atomically {
* tsem.acquire()
* }
* //sampleEnd
* println("Permits remaining ${atomically { tsem.available() }}")
* }
* ```
* <!--- KNIT example-stm-21.kt -->
*
* This function will retry if there are no permits available.
*
* @see TSemaphore.tryAcquire for a version that does not retry.
*/
public fun TSemaphore.acquire(): Unit =
acquire(1)
/**
* Acquire [n] permit from a [TSemaphore].
*
* ```kotlin
* import arrow.fx.stm.TSemaphore
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tsem = TSemaphore.new(5)
* atomically {
* tsem.acquire(3)
* }
* //sampleEnd
* println("Permits remaining ${atomically { tsem.available() }}")
* }
* ```
* <!--- KNIT example-stm-22.kt -->
*
* This function will retry if there are less than [n] permits available.
*
* @see TSemaphore.tryAcquire for a version that does not retry.
*/
public fun TSemaphore.acquire(n: Int): Unit {
val curr = v.read()
check(curr - n >= 0)
v.write(curr - n)
}
/**
* Like [TSemaphore.acquire] except that it returns whether or not acquisition was successful.
*
* ```kotlin
* import arrow.fx.stm.TSemaphore
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tsem = TSemaphore.new(0)
* val result = atomically {
* tsem.tryAcquire()
* }
* //sampleEnd
* println("Result $result")
* println("Permits remaining ${atomically { tsem.available() }}")
* }
* ```
* <!--- KNIT example-stm-23.kt -->
*
* This function never retries.
*
* @see TSemaphore.acquire for a version that retries if there are not enough permits.
*/
public fun TSemaphore.tryAcquire(): Boolean =
tryAcquire(1)
/**
* Like [TSemaphore.acquire] except that it returns whether or not acquisition was successful.
*
* ```kotlin
* import arrow.fx.stm.TSemaphore
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tsem = TSemaphore.new(0)
* val result = atomically {
* tsem.tryAcquire(3)
* }
* //sampleEnd
* println("Result $result")
* println("Permits remaining ${atomically { tsem.available() }}")
* }
* ```
* <!--- KNIT example-stm-24.kt -->
*
* This function never retries.
*
* @see TSemaphore.acquire for a version that retries if there are not enough permits.
*/
public fun TSemaphore.tryAcquire(n: Int): Boolean =
stm { acquire(n); true } orElse { false }
/**
* Release a permit back to the [TSemaphore].
*
* ```kotlin
* import arrow.fx.stm.TSemaphore
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tsem = TSemaphore.new(5)
* atomically {
* tsem.release()
* }
* //sampleEnd
* println("Permits remaining ${atomically { tsem.available() }}")
* }
* ```
* <!--- KNIT example-stm-25.kt -->
*
* This function never retries.
*/
public fun TSemaphore.release(): Unit =
v.write(v.read() + 1)
/**
* Release [n] permits back to the [TSemaphore].
*
* ```kotlin
* import arrow.fx.stm.TSemaphore
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tsem = TSemaphore.new(5)
* atomically {
* tsem.release(2)
* }
* //sampleEnd
* println("Permits remaining ${atomically { tsem.available() }}")
* }
* ```
* <!--- KNIT example-stm-26.kt -->
*
* [n] must be non-negative.
*
* This function never retries.
*/
public fun TSemaphore.release(n: Int): Unit = when (n) {
0 -> Unit
1 -> release()
else ->
if (n < 0) throw IllegalArgumentException("Cannot decrease permits using release(n). n was negative: $n")
else v.write(v.read() + n)
}
// TQueue
/**
* Append an element to the [TQueue].
*
* ```kotlin
* import arrow.fx.stm.TQueue
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tq = TQueue.new<Int>()
* atomically {
* tq.write(2)
* }
* //sampleEnd
* println("Items in queue ${atomically { tq.flush() }}")
* }
* ```
* <!--- KNIT example-stm-27.kt -->
*
* This function never retries.
*/
public fun <A> TQueue<A>.write(a: A): Unit =
writes.modify { it.cons(a) }
/**
* Append an element to the [TQueue]. Alias for [STM.write].
*
* ```kotlin
* import arrow.fx.stm.TQueue
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tq = TQueue.new<Int>()
* atomically {
* tq += 2
* }
* //sampleEnd
* println("Items in queue ${atomically { tq.flush() }}")
* }
* ```
* <!--- KNIT example-stm-28.kt -->
*
* This function never retries.
*/
public operator fun <A> TQueue<A>.plusAssign(a: A): Unit = write(a)
/**
* Remove the front element from the [TQueue] or retry if the [TQueue] is empty.
*
* ```kotlin
* import arrow.fx.stm.TQueue
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tq = TQueue.new<Int>()
* val result = atomically {
* tq.write(2)
* tq.read()
* }
* //sampleEnd
* println("Result $result")
* println("Items in queue ${atomically { tq.flush() }}")
* }
* ```
* <!--- KNIT example-stm-29.kt -->
*
* @see TQueue.tryRead for a version that does not retry.
* @see TQueue.peek for a version that does not remove the element.
*/
public fun <A> TQueue<A>.read(): A {
val xs = reads.read()
return if (xs.isNotEmpty()) reads.write(xs.tail()).let { xs.head() }
else {
val ys = writes.read()
if (ys.isEmpty()) retry()
else {
writes.write(PList.Nil)
val reversed = ys.reverse()
reads.write(reversed.tail())
reversed.head()
}
}
}
/**
* Same as [TQueue.read] except it returns null if the [TQueue] is empty.
*
* ```kotlin
* import arrow.fx.stm.TQueue
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tq = TQueue.new<Int>()
* val result = atomically {
* tq.tryRead()
* }
* //sampleEnd
* println("Result $result")
* println("Items in queue ${atomically { tq.flush() }}")
* }
* ```
* <!--- KNIT example-stm-30.kt -->
*
* This function never retries.
*/
public fun <A> TQueue<A>.tryRead(): A? =
(stm { read() } orElse { null })
/**
* Drains all entries of a [TQueue] into a single list.
*
* ```kotlin
* import arrow.fx.stm.TQueue
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tq = TQueue.new<Int>()
* val result = atomically {
* tq.write(2)
* tq.write(4)
*
* tq.flush()
* }
* //sampleEnd
* println("Result $result")
* println("Items in queue ${atomically { tq.flush() }}")
* }
* ```
* <!--- KNIT example-stm-31.kt -->
*
* This function never retries.
*/
public fun <A> TQueue<A>.flush(): List<A> {
val xs = reads.read().also { if (it.isNotEmpty()) reads.write(PList.Nil) }
val ys = writes.read().also { if (it.isNotEmpty()) writes.write(PList.Nil) }
return xs.toList() + ys.reverse().toList()
}
/**
* Read the front element of a [TQueue] without removing it.
*
* ```kotlin
* import arrow.fx.stm.TQueue
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tq = TQueue.new<Int>()
* val result = atomically {
* tq.write(2)
*
* tq.peek()
* }
* //sampleEnd
* println("Result $result")
* println("Items in queue ${atomically { tq.flush() }}")
* }
* ```
* <!--- KNIT example-stm-32.kt -->
*
* This function retries if the [TQueue] is empty.
*
* @see TQueue.read for a version that removes the front element.
* @see TQueue.tryPeek for a version that does not retry.
*/
public fun <A> TQueue<A>.peek(): A =
read().also { writeFront(it) }
/**
* Same as [TQueue.peek] except it returns null if the [TQueue] is empty.
*
* ```kotlin
* import arrow.fx.stm.TQueue
* import arrow.fx.stm.atomically
*
* suspend fun main() {
* //sampleStart
* val tq = TQueue.new<Int>()
* val result = atomically {
* tq.tryPeek()
* }
* //sampleEnd
* println("Result $result")
* println("Items in queue ${atomically { tq.flush() }}")
* }
* ```
* <!--- KNIT example-stm-33.kt -->
*
* This function never retries.
*
* @see TQueue.tryRead for a version that removes the front element
* @see TQueue.peek for a version that retries if the [TQueue] is empty.
*/
public fun <A> TQueue<A>.tryPeek(): A? =
tryRead()?.also { writeFront(it) }