'Is it good idea to use atomic boolean in kotlin?
Hey I am learning in atomic in kotlin. I am wondering is this good idea to use atomic boolean in my scenario? Can someone suggest, how to do in atomic way.
Scenario 1 Not for first time call
var isFirstTime = true
fun notForFirstTime(){
if(!isFirstTime){
jobDone()
}
isFirstTime = false
}
Scenario 2 only for first time
var isFirstTime = true
fun onlyForFirstTime(){
if(isFirstTime){
jobDone()
}
isFirstTime = false
}
Can I do this in atomic way? Also is this good idea?
Solution 1:[1]
It depends on what you're trying to achieve.
For scenario 2, most of the time what you want is a value that's computed once and reused later. For this use-case, you can use lazy delegates like this:
class MyClass {
// will be computed the first time it's accessed, and then reused
val value by lazy { computeExpensiveValue() }
}
fun computeExpensiveValue(): Int {
// some complex stuff
return 42
}
I never encountered scenario 1, but in cases where lazy is not sufficient you could indeed use atomic booleans for CAS approaches, or locks. Check for instance kotlinx.atomicfu.
If you're using Kotlin coroutines, you might want to check other synchronization primitives like Mutex and Semaphore. But in general it's preferable to make coroutines communicate over channels rather than sharing mutable state.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
