Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Value classes don't work on native #291

Closed
DRSchlaubi opened this issue Apr 5, 2023 · 5 comments
Closed

Value classes don't work on native #291

DRSchlaubi opened this issue Apr 5, 2023 · 5 comments
Assignees
Labels

Comments

@DRSchlaubi
Copy link

DRSchlaubi commented Apr 5, 2023

Currently this update call never finishes

public value class Value(public val value: Int)

public fun main() {
    val atomic = atomic(Value(1))
    println(atomic)
    atomic.update { Value(2) }
    println(atomic)
}

Might be fixed by #261

@mvicsokolova
Copy link
Collaborator

AtomicRef<T>.update function has the following implementation under the hood:

inline fun <T> AtomicRef<T>.update(function: (T) -> T) {
    while (true) {
        val cur = value
        val upd = function(cur)
        if (compareAndSet(cur, upd)) return // compareAndSet never succeeds
    }
}

However, for value classes this invocation of compareAndSet never succeeds due to the design of value classes: Value(1) === Value(1) is false.

It's better to avoid using AtomicReference to value classes and this will be prohibited in the next versions of the plugin. Instead, in this case you may use AtomicInt.

@mvicsokolova
Copy link
Collaborator

Furthermore, please note that the atomicfu plugin can only perform transformations of atomic values declared as properties. It won't be able to perform transformations on atomic values declared as local variables. For example, the code below is correct:

private val atomic = atomic(1)

public fun main() {
    println(atomic)
    atomic.update { 2 }
    println(atomic)
}

@DRSchlaubi
Copy link
Author

How is this not a bug?

@DRSchlaubi
Copy link
Author

If the plugin does not support this behavior it should at least fail at compile time instead of causing a deadlock at runtime

@mvicsokolova
Copy link
Collaborator

This behaviour will be prohibited in the compiler plugin: KT-61584

lukellmann added a commit to kordlib/kord that referenced this issue Sep 3, 2023
The use of value classes for the Reset class has already caused issues
implementing #855. However, it was isolated to native platforms.
Unfortunately, this behavior will become a compiler error soon, so we
need to change it. This can be achieved by simply using the backing
Instant instead of Reset with AtomicRef.

Related Issues:
#855
#69
Kotlin/kotlinx-atomicfu#291
https://youtrack.jetbrains.com/issue/KT-61584

Co-authored-by: lukellmann <lukellmann@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants