https://kotlinlang.org logo
#coroutines
Title
# coroutines
z

zjuhasz

01/13/2019, 5:41 AM
I found I was using actor a lot just to get concurrency safe access to some arbitrary mutable data but there’s a lot of boilerplate for even this very simple application of actor. So I made a general purpose actor for this and I was hoping someone could tell me if you see any obvious oversights in it. Like for example does passing the whole function to the actor as opposed to just some parameters cause significant performance degradation or something like that. Here is the code: https://gitlab.com/snippets/1797360
d

Dico

01/13/2019, 6:09 AM
I think this particular application of actor could effectively be replaced with using a
Mutex
in most cases
Which doesn't enforce same thread access, but it is non blocking lock
As for whether using the lambda makes a difference, I'd say probably minuscule but it should be tested
You could test whether the performance is better if you crossinline the lambda into an abstract function of execute, which would save an allocation, but it really shouldn't make a difference
z

zjuhasz

01/13/2019, 6:26 AM
If
Mutex
doesn’t enforce same thread access can’t you still run into cache issues on multicore processors?
Where changes aren’t seen from certain threads.
Or does it synchronize memory like a Java
Lock
g

gildor

01/13/2019, 9:18 AM
Mutex does thing similar to Java lock, but doesn't block thread
It shouldn't be any cache issues, because mutex provides happens-before point under the hood
d

Dico

01/13/2019, 9:20 AM
Well if you think about how the mutex works, cache should already be synchronized but I'm no expert
Happens-before point?
Mutex uses atomic operations under the hood, so this solves problem with publication of changes
d

Dico

01/13/2019, 9:32 AM
It does use atomic operations, threads are racing for a CAS, which is atomic in Jvm because it is implemented using sun/misc/Unsafe
So does that mean the remainder of the cache is also safe because the cpu will publish all changes at once?
g

groostav

01/14/2019, 6:04 PM
Yes. If it didn't it wouldn't solve the use case of using a mutex to guard some kind of resource, because a Mutex has no idea where that resource might be in a CPU's cache.
also @zjuhasz this seems like a neat idea, thinking about it theres a couple places where I could probably use it. Regarding performance, and this stuff only matters if you're looking at > 100,000 messages/sec, you could replace
CompletableDeferred
with something like
Copy code
Inline class Execute(val backing: Continuation<R>)
Then you can wrap
resume
to something like
complete
👍 1
3 Views