Junior — Middle
How can a lock mechanism responsible for single state switching be created at the programming code level?
sobes.tech AI
Answer from AI
To create a lock mechanism that allows a one-time state switch, you can use atomic operations or synchronization primitives, such as AtomicBoolean in Java/Kotlin. This approach guarantees that the state switch occurs only once, even in multithreaded access.
Example in Kotlin:
import java.util.concurrent.atomic.AtomicBoolean
class OneTimeSwitcher {
private val switched = AtomicBoolean(false)
fun switch(): Boolean {
// Attempt to switch the state from false to true
return switched.compareAndSet(false, true)
}
}
fun main() {
val switcher = OneTimeSwitcher()
println(switcher.switch()) // true - switch occurred
println(switcher.switch()) // false - switch has already occurred
}
In this example, the switch() method returns true only on the first call, indicating a successful switch. All subsequent calls will return false, preventing repeated switching.