<@U8NMFHUGJ> Sorry for strange question about test...
# kotlin-native
m
@kpgalligan Sorry for strange question about test 🙂 I undestand your example about the User factory. But I 'm not finding usecase for detach object feature and can't undestand this feature fully. My naive thoughts is below in code 🙂. I had provided some comments about that. Looks like I need to write some production code to see concurrent patterns in Kotlin.
a
Unfortunately it does not work this way. There must be 0 references left when transferring an object. Consider the following code:
Copy code
data class User(val age: Int)

fun foo() {
    val worker = Worker.start()

    val user = AtomicReference(User(42).freeze())

    user.update { it.copy(age = 24).freeze() }

    val future = worker.execute(TransferMode.SAFE, { user }) { input ->
        input.update { it.copy(age = 31).freeze() }
        println("User inside worker thread ${input.value}")
        return@execute input
    }

    future.consume {
        
    }
}

inline fun <T> AtomicReference<T>.getAndUpdate(update: (T) -> T): T {
    var prev: T
    do {
        prev = value
    } while (!compareAndSet(prev, update(prev)))

    return prev
}

inline fun <T> AtomicReference<T>.update(update: (T) -> T) {
    getAndUpdate(update)
👍 1
k
DetachedObjectGraph { user }
Is a constructor that takes a producer,
{user}
. That producer, a function, is executed, and the returned result is checked to see that there are no other references to it. The context from which you’re creating
DetachedObjectGraph
still has a reference to user, so DetachedObjectGraph’s constructor will fail.
“I’m ready to take a Runtime error if I will mutate user in Main thread”. It doesn’t work that way. Passing state between threads is when it checks.
In any case, part of learning how to work in KN is getting used to not passing around a lot of mutable state. It’s a source of much trouble. Obviously it’s good to learn these concepts, but I don’t pass around detached state much because changing from multiple threads is tricky. Also, the detach operation is not free. That’s something else to keep in mind.