Why is this "advice" as a compilation error when a...
# getting-started
n
Why is this "advice" as a compilation error when assigning
atomic(...)
to a local variable (which is later passed to a lambda)?
* Refrain from invoking atomic operations on local variables:
```
val top = atomic<Node?>(null)
val tmp = top
tmp.compareAndSet(null, Node(1)) // DON'T DO THIS
```
Thanks.
s
AtomicFU works by transforming the code at compile time. An
Atomic<T>
will actually be transformed into a plain
T
, and access to it will be turned into direct atomic updates of the underlying field. In other words, at runtime, the
Atomic
object itself is gone. So you can't pass it around between different variables and functions.
n
Hm, thanks. I thought it will be transformed to
AtomicReference
,
AtomicInteger
, etc. 😮
s
The exact implementation varies by platform, but it's designed to avoid boxing. You can see the details in the docs here. On JVM for example:
an atomic value is represented as a plain value atomically updated with
java.util.concurrent.atomic.AtomicXxxFieldUpdater
from the Java standard library.
today i learned 1
If you want boxed atomics you don't have to use AtomicFU, you can just use
AtomicReference
instead
👍 1