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

Matej Drobnič

01/10/2020, 6:11 AM
Are there any coroutines constructs that would help me with creation of "global, stoppable, restartable actor"? Basically an actor that is running on global scope (shared logic used between multiple modules), but it can be stopped and restarted as needed. Something like this:
Copy code
private var actorChannel = Channel(Capacity.UNLIMITED)
private var actorJob : Job? = null

fun performSomeOtherCommand() {
    if (actorJob?.isActive != true) {
        restartActor()
    }

    actor.offer(...)
}

suspend fun stopActor() {
    actor.offer(StopCommand)

    actorJob?.join()
}

private fun restartActor() {
    actorJob = GlobalScope.launch {
        actorChannel.consumeEach {
            ...

            if (it == StopCommand) {
                return@launch
            }
        }
    }
}
But the problem with above example is that it is not thread safe. One thread could call
performSomeOtherCommand()
while the actor is still being stopped by
stopActor()
. Easiest solution would be to just not stop the actor and let it live forever, but since it's in
GlobalScope
, it would never be garbage collected when not needed. I could use mutexes and synchronized blocks but I feel that this kinda ruins the point of having an actor.
u

uli

01/10/2020, 7:05 AM
An actor itself should be really light weight. Gc could become relevant if the actor holds lots of state. In that case I'd suggest to keep it running and only tell it to free it's resources
b

bob

01/10/2020, 8:30 AM
Why do you need to stop and restart the actor? Would it be enough to pause/resume?
m

Matej Drobnič

01/10/2020, 8:33 AM
I basically want to remove it from memory when not needed, but @uli might have a point here - actor itself does not really use that much memory.
b

bob

01/10/2020, 8:34 AM
I would probably take some inspiration here: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/actor.html I know it’s obsolete and will be removed in respect of a more complex actor. But it’s still worth checking out.
m

Matej Drobnič

01/10/2020, 9:05 AM
Yes that is what I would use normally (when there is no requirement to stop the actor)
3 Views