Tags down


How to use actors while retaining the ability to do structured concurrency in Kotlin?

By : sri logan
Date : August 30 2020, 09:00 PM
I wish did fix the issue. actor processes items in the same order as they were added, and does it sequentially in a single coroutine. It means that inner transform will be processed AFTER completion of outer transform, and you can't change it while you are using actor (in actor we can't launch more coroutines, because we confine our state to a single thread, otherwise recurrent processing order would be possible). Trying to join the job of inner transform in body of outer transform (if we mark transform as suspended function) will just cause deadlock.
Are you OK with such behaviour? If not, don't use either actors or nested transforms. If yes, please provide some use cases where creating a nested transform that will be processed after outer transform makes any sense.
code :
private sealed class RefOperation<T>
private class Get<T : Any>(val deferred: CompletableDeferred<T>) : RefOperation<T>()
private class Transform<T : Any>(val transformer: TransformStub<T>.(T) -> T, val stub: TransformStub<T>, val job: CompletableJob) : RefOperation<T>()

interface Ref<T : Any> {

    fun get(): T

    fun transform(transformer: TransformStub<T>.(T) -> T): Job


interface TransformStub<T : Any> {
    fun transform(transformer: TransformStub<T>.(T) -> T): Job

private class TransformStubImpl<T : Any>(
        val actor: SendChannel<RefOperation<T>>,
        val scope: CoroutineScope
) : TransformStub<T> {

    override fun transform(transformer: TransformStub<T>.(T) -> T): Job {
        return scope.launch {
            val childJob: CompletableJob = Job()
            val childStub = TransformStubImpl(actor, this)
            actor.send(Transform(transformer, childStub, childJob))


class RefImpl<T : Any>(initialValue: T) : Ref<T> {

    private val actorJob = Job()
    private val actorScope = CoroutineScope(actorJob)
    private val actor = actorScope.actor<RefOperation<T>> {
        var value: T = initialValue
        for (msg in channel) {
            when (msg) {
                is Get -> {
                    println("Get! $value")
                is Transform -> {
                    with(msg) {
                        val newValue = stub.transformer(value)
                        println("Transform! $value -> $newValue")
                        value = newValue

    override fun get(): T = runBlocking {
        val deferred = CompletableDeferred<T>()

    override fun transform(transformer: TransformStub<T>.(T) -> T): Job {
        val stub = TransformStubImpl(actor, GlobalScope)
        return stub.transform(transformer)


fun main() = runBlocking<Unit> {
    val ref: Ref<Int> = RefImpl(0)
    val transformJob = ref.transform {
        transform { 8 }

Share : facebook icon twitter icon

How to limit concurrency when using actors in Scala?

By : Faizan Rana
Date : March 29 2020, 07:55 AM
I hope this helps you . You can override the system properties actors.maxPoolSize and actors.corePoolSize which limit the size of the actor thread pool and then throw as many jobs at the pool as your actors can handle. Why do you think you need to throttle your reactions?

Indeterministic behavior of actors in concurrency example

By : user2774353
Date : March 29 2020, 07:55 AM

Concurrency Actors and Traits in Scala

By : GoldinaWeb
Date : March 29 2020, 07:55 AM
will help you I did a blog post up on this problem and the compromise that I've found for solving the problem.

Concurrency within actors using Futures

By : user3354835
Date : March 29 2020, 07:55 AM
Hope this helps I am wondering if there is a better way to handle async initialization of values within an Actor. Actors of course are thread safe when inside the actor, but using Futures throws a wrinkle in that (and you have to make sure you don't close over context or sender) Consider the following: , You actually don't need futures to handle multi-part response:
code :
var x: Option[Int] = None
var y: Option[Int] = None

def receive = {
  case Request1.Response(x) => x = Some(x); checkParts
  case Request2.Response(y) => y = Some(y); checkParts

def checkParts = for {
   xx <- x
   yy <- y
} parent ! xx + yy
case class Resp1(x: Int)
case class Resp2(y: Int)
case class State(x: Option[Int], y: Option[Int])

class Worker(parent: ActorRef) extends Actor {
  def receive = process(State(None, None))

  def process(s: State): Receive = edge(s) andThen { sn => 
    context become process(sn)
    for {
       xx <- sn.x
       yy <- sn.y
    } parent ! xx + yy //action

  def edge(s: State): PartialFunction[Any, State] = { //managing state
    case Resp1(x) => s.copy(x = Some(x))
    case Resp2(y) => s.copy(y = Some(y))


Concurrency among multiple actors

By : user2213968
Date : March 29 2020, 07:55 AM
will help you It should be okay with this approach, there just a few caveats to keep in mind:
Related Posts Related Posts :
  • Kotlin, unresolved reference on everything in VSCode
  • brief function code for null check in kotlin
  • How to capture an argument that was passed to a mocked function and return it?
  • Issue when trying to import Jacoco code coverage to SonarQube: Cannot import coverage information for file, coverage dat
  • Proposed change of `equals` to `==` can't be applied to Char and String?
  • How to use kotlin's default parameter only if the input is not null?
  • Please Explain to me this kotlin statement?
  • How to check if a string is a valid email in android?
  • This annotation is not applicable to target member property without backing field or delegate
  • How to split on unicode whitespace in kotlin
  • How can Kotlin's Set be covariant when contains() takes E?
  • Kotlin inline class in JUnit tests
  • Lambda as a function parameter -> accept methods only from particular class
  • Kotlin - How do I concatenate a String to an Int value?
  • Why I Cannot Access to this function?
  • Kotlin test, how to run BeforeEach with DescribeSpec test style
  • Convince Kotlin compiler map has a key
  • how do you declare static property in kotlin?
  • How can i call an interface in kotlin?
  • Check if any array item is not empty
  • kotlin, where the return from inside the let go
  • Kotlin: Should mutableList be declared as Val or Var?
  • Convert Long to String in Kotlin
  • Extension property inside class: Unresolved reference: errorResponse
  • How to extend enums in Kotlin?
  • Idiomatic way in kotlin to transform/append to a list?
  • How to avoid nest 「null check」by "?.let"?
  • How to simply add another source to MediatorLiveData in kotlin?
  • Convert Set<Int> to varargs efficiently in Kotlin
  • Getting an error Using 'body(): ResponseBody?' is an error. moved to val with okhttp
  • Kotlin String to Int or zero (default value)
  • Return value only of the faster coroutine
  • Is there a Kotlin Coroutines Channel equivalent of RxJava's onDispose?
  • Create fat jar from kotlin multiplatform project
  • Short circuiting operation in Kotlin sequences
  • How to output deprecation warnings for Kotlin code?
  • Why does generated getter method have dollar signs in it?
  • For a final class why does when complain?
  • Reference value of constant with KDoc
  • How to create this coroutines in kotlin?
  • OkHttp: NoSuchMethodError copyInto in TlsUtil
  • Why do unreachable statements method not result in a compilation error?
  • Static/Const map key check at compile time
  • Escaping double quotes inside backticks
  • Does Kotlin have primitive types?
  • What is exactly null in kotlin and why i can't cause NPE with it?
  • Why would you use a Kotlin companion object rather than an initializer block for creation?
  • how to use operator overloading in Kotlin to divide a number by a numeric vector
  • How to use get() with backing fields in kotlin
  • How to map string to function and call it later
  • Kotlin enum constructor argument 'must be initialized' with companion object constant without qualifier name
  • Please explain to me class delegation in Kotlin
  • Error:(1, 41) Kotlin: Symbol is declared in module 'jdk.internal.opt' which does not export package 'jdk.i
  • How to properly make blocking service calls with Kotlin coroutines?
  • Gson SerializedName in a Kotlin interface
  • Kotlin convert FileTime to day, month, year
  • Kotlin how to move a file to a other directory?
  • If first param is true, then must pass second param in function
  • MutableLiveData for collections
  • How to replace long chain of forEach{} statements in Kotlin?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk