forked from sergeych/crypto2
fixed tests. better atomic operations
This commit is contained in:
1 parent
ce8cfe8e3d
commit
b86c7a853e
6 files changed
+51
-13
No files matched your search
@@ -1,10 +1,6 @@
|
||||
package net.sergeych.tools
|
||||
|
||||
@Suppress("unused")
|
||||
class AtomicCounter(initialValue: Long = 0) {
|
||||
private val op = ProtectedOp()
|
||||
var value: Long = initialValue
|
||||
private set
|
||||
|
||||
fun incrementAndGet(): Long = op { ++value }
|
||||
class AtomicCounter(initialValue: Long = 0) : AtomicValue<Long>(initialValue) {
|
||||
fun incrementAndGet(): Long = mutate { it+1 }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package net.sergeych.tools
|
||||
|
||||
/**
|
||||
* Multiplatform (JS and battery included) atomically mutable value.
|
||||
* Actual value can be either changed in a block of [mutuate] when
|
||||
* new value _depends on the current value_ or use a same [value]
|
||||
* property that is thread-safe where there are threads and just safe
|
||||
* otherwise ;)
|
||||
*/
|
||||
open class AtomicValue<T>(initialValue: T) {
|
||||
var actualValue = initialValue
|
||||
val op = ProtectedOp()
|
||||
|
||||
/**
|
||||
* Change the value: get the current and set to the returned, all in the
|
||||
* atomic operation. All other mutating requests including assigning to [value]
|
||||
* will be blocked and queued.
|
||||
* @return result of the mutation. Note that immediate call to property [value]
|
||||
* could already return modified bu some other thread value!
|
||||
*/
|
||||
fun mutate(mutator: (T) -> T): T = op {
|
||||
actualValue = mutator(actualValue)
|
||||
actualValue
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomic get or set the value. Atomic get means if there is a [mutate] in progress
|
||||
* it will wait until the mutation finishes and then return the correct result.
|
||||
*/
|
||||
var value: T
|
||||
get() = op { actualValue }
|
||||
set(value) {
|
||||
mutate { value }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user