mansonheart
05/26/2019, 7:17 PMArkadii Ivanov
05/26/2019, 7:52 PMdata 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)
kpgalligan
05/26/2019, 8:32 PMDetachedObjectGraph { 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.kpgalligan
05/26/2019, 8:33 PMkpgalligan
05/26/2019, 8:35 PM