0
# Atomic Operations
1
2
Core atomic variables and operations for thread-safe programming with automatic compile-time optimization to platform-specific implementations.
3
4
## Capabilities
5
6
### Atomic Reference Factory Functions
7
8
Creates atomic reference variables for any type with optional tracing support.
9
10
```kotlin { .api }
11
/**
12
* Creates atomic reference with a given initial value.
13
* Can only be used to initialize private read-only properties.
14
*/
15
fun <T> atomic(initial: T): AtomicRef<T>
16
17
/**
18
* Creates atomic reference with tracing support for debugging.
19
*/
20
fun <T> atomic(initial: T, trace: TraceBase): AtomicRef<T>
21
```
22
23
**Usage Examples:**
24
25
```kotlin
26
import kotlinx.atomicfu.*
27
28
class DataStore {
29
private val currentData = atomic<String?>(null)
30
private val config = atomic(emptyMap<String, Any>())
31
32
fun setData(data: String?) {
33
currentData.value = data
34
}
35
36
fun getData(): String? = currentData.value
37
38
fun updateConfig(key: String, value: Any) {
39
val currentConfig = config.value
40
config.value = currentConfig + (key to value)
41
}
42
}
43
```
44
45
### Atomic Integer Factory Functions
46
47
Creates atomic integer variables with arithmetic operations support.
48
49
```kotlin { .api }
50
/**
51
* Creates atomic Int with a given initial value.
52
* Can only be used to initialize private read-only properties.
53
*/
54
fun atomic(initial: Int): AtomicInt
55
56
/**
57
* Creates atomic Int with tracing support for debugging.
58
*/
59
fun atomic(initial: Int, trace: TraceBase): AtomicInt
60
```
61
62
**Usage Examples:**
63
64
```kotlin
65
import kotlinx.atomicfu.*
66
67
class Counter {
68
private val count = atomic(0)
69
private val maxSeen = atomic(Int.MIN_VALUE)
70
71
fun increment(): Int {
72
val newValue = count.incrementAndGet()
73
// Update max atomically
74
while (true) {
75
val currentMax = maxSeen.value
76
if (newValue <= currentMax || maxSeen.compareAndSet(currentMax, newValue)) {
77
break
78
}
79
}
80
return newValue
81
}
82
83
fun add(delta: Int): Int = count.addAndGet(delta)
84
85
fun get(): Int = count.value
86
87
fun getMax(): Int = maxSeen.value
88
}
89
```
90
91
### Atomic Long Factory Functions
92
93
Creates atomic long variables with arithmetic operations support.
94
95
```kotlin { .api }
96
/**
97
* Creates atomic Long with a given initial value.
98
* Can only be used to initialize private read-only properties.
99
*/
100
fun atomic(initial: Long): AtomicLong
101
102
/**
103
* Creates atomic Long with tracing support for debugging.
104
*/
105
fun atomic(initial: Long, trace: TraceBase): AtomicLong
106
```
107
108
**Usage Examples:**
109
110
```kotlin
111
import kotlinx.atomicfu.*
112
113
class Accumulator {
114
private val total = atomic(0L)
115
private val operations = atomic(0L)
116
117
fun add(value: Long) {
118
total += value
119
operations.incrementAndGet()
120
}
121
122
fun getAverage(): Double {
123
val currentTotal = total.value
124
val currentOps = operations.value
125
return if (currentOps > 0) currentTotal.toDouble() / currentOps else 0.0
126
}
127
}
128
```
129
130
### Atomic Boolean Factory Functions
131
132
Creates atomic boolean variables for flag and state management.
133
134
```kotlin { .api }
135
/**
136
* Creates atomic Boolean with a given initial value.
137
* Can only be used to initialize private read-only properties.
138
*/
139
fun atomic(initial: Boolean): AtomicBoolean
140
141
/**
142
* Creates atomic Boolean with tracing support for debugging.
143
*/
144
fun atomic(initial: Boolean, trace: TraceBase): AtomicBoolean
145
```
146
147
**Usage Examples:**
148
149
```kotlin
150
import kotlinx.atomicfu.*
151
152
class ServiceState {
153
private val isRunning = atomic(false)
154
private val isInitialized = atomic(false)
155
156
fun start(): Boolean {
157
if (!isInitialized.value) {
158
throw IllegalStateException("Service not initialized")
159
}
160
return isRunning.compareAndSet(false, true)
161
}
162
163
fun stop(): Boolean {
164
return isRunning.compareAndSet(true, false)
165
}
166
167
fun initialize(): Boolean {
168
return isInitialized.compareAndSet(false, true)
169
}
170
171
fun isRunning(): Boolean = isRunning.value
172
}
173
```
174
175
### AtomicRef Operations
176
177
Generic atomic reference with volatile reads/writes and atomic operations.
178
179
```kotlin { .api }
180
/**
181
* Property delegate from kotlin.reflect for property-based access
182
*/
183
typealias KProperty<*> = kotlin.reflect.KProperty<*>
184
185
class AtomicRef<T> {
186
/** Volatile property for reading/writing the atomic value */
187
var value: T
188
189
/** Property delegate getter */
190
operator fun getValue(thisRef: Any?, property: KProperty<*>): T
191
192
/** Property delegate setter */
193
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T)
194
195
/** Maps to AtomicReferenceFieldUpdater.lazySet */
196
fun lazySet(value: T)
197
198
/** Maps to AtomicReferenceFieldUpdater.compareAndSet */
199
fun compareAndSet(expect: T, update: T): Boolean
200
201
/** Maps to AtomicReferenceFieldUpdater.getAndSet */
202
fun getAndSet(value: T): T
203
}
204
```
205
206
### AtomicInt Operations
207
208
Atomic integer with volatile reads/writes and atomic arithmetic operations.
209
210
```kotlin { .api }
211
class AtomicInt {
212
/** Volatile property for reading/writing the atomic value */
213
var value: Int
214
215
/** Property delegate operations */
216
operator fun getValue(thisRef: Any?, property: KProperty<*>): Int
217
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Int)
218
219
/** Basic atomic operations */
220
fun lazySet(value: Int)
221
fun compareAndSet(expect: Int, update: Int): Boolean
222
fun getAndSet(value: Int): Int
223
224
/** Atomic arithmetic operations */
225
fun getAndIncrement(): Int
226
fun getAndDecrement(): Int
227
fun getAndAdd(delta: Int): Int
228
fun addAndGet(delta: Int): Int
229
fun incrementAndGet(): Int
230
fun decrementAndGet(): Int
231
232
/** Operator overloads for atomic arithmetic */
233
operator fun plusAssign(delta: Int)
234
operator fun minusAssign(delta: Int)
235
}
236
```
237
238
### AtomicLong Operations
239
240
Atomic long with volatile reads/writes and atomic arithmetic operations.
241
242
```kotlin { .api }
243
class AtomicLong {
244
/** Volatile property for reading/writing the atomic value */
245
var value: Long
246
247
/** Property delegate operations */
248
operator fun getValue(thisRef: Any?, property: KProperty<*>): Long
249
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Long)
250
251
/** Basic atomic operations */
252
fun lazySet(value: Long)
253
fun compareAndSet(expect: Long, update: Long): Boolean
254
fun getAndSet(value: Long): Long
255
256
/** Atomic arithmetic operations */
257
fun getAndIncrement(): Long
258
fun getAndDecrement(): Long
259
fun getAndAdd(delta: Long): Long
260
fun addAndGet(delta: Long): Long
261
fun incrementAndGet(): Long
262
fun decrementAndGet(): Long
263
264
/** Operator overloads for atomic arithmetic */
265
operator fun plusAssign(delta: Long)
266
operator fun minusAssign(delta: Long)
267
}
268
```
269
270
### AtomicBoolean Operations
271
272
Atomic boolean with volatile reads/writes and atomic operations.
273
274
```kotlin { .api }
275
class AtomicBoolean {
276
/** Volatile property for reading/writing the atomic value */
277
var value: Boolean
278
279
/** Property delegate operations */
280
operator fun getValue(thisRef: Any?, property: KProperty<*>): Boolean
281
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean)
282
283
/** Basic atomic operations */
284
fun lazySet(value: Boolean)
285
fun compareAndSet(expect: Boolean, update: Boolean): Boolean
286
fun getAndSet(value: Boolean): Boolean
287
}
288
```
289
290
### Extension Functions
291
292
Higher-level atomic operations built on top of basic compare-and-swap operations.
293
294
```kotlin { .api }
295
/** Infinite loop that reads atomic variable and performs action on its value */
296
fun <T> AtomicRef<T>.loop(action: (T) -> Unit): Nothing
297
fun AtomicInt.loop(action: (Int) -> Unit): Nothing
298
fun AtomicLong.loop(action: (Long) -> Unit): Nothing
299
fun AtomicBoolean.loop(action: (Boolean) -> Unit): Nothing
300
301
/** Updates variable atomically using the specified function */
302
fun <T> AtomicRef<T>.update(function: (T) -> T)
303
fun AtomicInt.update(function: (Int) -> Int)
304
fun AtomicLong.update(function: (Long) -> Long)
305
fun AtomicBoolean.update(function: (Boolean) -> Boolean)
306
307
/** Updates variable atomically and returns old value */
308
fun <T> AtomicRef<T>.getAndUpdate(function: (T) -> T): T
309
fun AtomicInt.getAndUpdate(function: (Int) -> Int): Int
310
fun AtomicLong.getAndUpdate(function: (Long) -> Long): Long
311
fun AtomicBoolean.getAndUpdate(function: (Boolean) -> Boolean): Boolean
312
313
/** Updates variable atomically and returns new value */
314
fun <T> AtomicRef<T>.updateAndGet(function: (T) -> T): T
315
fun AtomicInt.updateAndGet(function: (Int) -> Int): Int
316
fun AtomicLong.updateAndGet(function: (Long) -> Long): Long
317
fun AtomicBoolean.updateAndGet(function: (Boolean) -> Boolean): Boolean
318
```
319
320
**Usage Examples:**
321
322
```kotlin
323
import kotlinx.atomicfu.*
324
325
class Statistics {
326
private val values = atomic<List<Double>>(emptyList())
327
private val sum = atomic(0.0)
328
329
fun addValue(value: Double) {
330
// Update list atomically
331
values.update { currentList -> currentList + value }
332
333
// Update sum atomically
334
sum.update { currentSum -> currentSum + value }
335
}
336
337
fun getAverage(): Double {
338
val currentValues = values.value
339
return if (currentValues.isNotEmpty()) sum.value / currentValues.size else 0.0
340
}
341
342
fun clear() {
343
values.update { emptyList() }
344
sum.update { 0.0 }
345
}
346
}
347
```
348
349
## Implementation Notes
350
351
### Usage Constraints
352
353
- Atomic fields **must** be declared as `private` or `internal` `val` properties
354
- Format: `private val field = atomic(initialValue)`
355
- Cannot be used with `var` properties or `public` fields
356
- Atomic operations are transformed at compile-time for optimal performance
357
358
### JVM Optimizations
359
360
- Uses `AtomicXxxFieldUpdater` for optimal performance
361
- VarHandle support for Java 9+ when available
362
- Zero runtime overhead through bytecode transformation
363
- Direct mapping to JVM atomic operations