Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Writing complex actors #87

Open
fvasco opened this issue Jul 22, 2017 · 35 comments

Comments

Projects
None yet
7 participants
@fvasco
Copy link
Contributor

commented Jul 22, 2017

I need to create a complex actor using some private methods to update the internal state, but I cannot find any useful base class to implement ActorJob.

What is the best practice in such case?

@elizarov

This comment has been minimized.

Copy link
Member

commented Jul 22, 2017

I'd do something along these lines:

class MyActor {
    // your private state here
    suspend fun onReceive(msg: MyMsg) {
        // ... your code here ...
    }
}

fun myActorJob(): ActorJob<MyMsg> = actor(CommonPool) {
    with(MyActor()) {
        for (msg in channel) onReceive(msg)
    }
}

You can also pass actor's channel to MyActor constructor if it needs access to it.

@fvasco

This comment has been minimized.

Copy link
Contributor Author

commented Jul 23, 2017

Hi @elizarov,
hi solved this issue in the same way, but an helper class looks like a miss of abstraction.

I want propose to introduce a dedicated interface for actor, something like:

interface Actor : ActorScope {
    fun invoke() : Unit
}

and the new function

fun launch(context: CoroutineContext, ..., actorBuild: (CoroutineContext) -> Actor) : ActorJob

I want to propose a draft implementation in the next week, what do you think about it?

@elizarov

This comment has been minimized.

Copy link
Member

commented Jul 24, 2017

The key design consideration here is how a typical actor's code is going to look like. It is not clear in your example. The goal should be to minimize the amount of boilerplate that users of this library code are forced to write. I was thinking about something along the following lines:

abstract class Actor<T>(scope: ActorScope<T>): ActorScope<T> by scope {
    abstract suspend fun onReceive(msg: T)
}

An abstract class lets us share some common state among all actor implementations (in this case, the fact that ActorScope is provided to all the functions defined inside an actor impl). It also makes sense to share "for messages" loop, as every typical actor is going to have one, and leave only onReceive for override.

With this bases class, the specific actor implementation looks like this:

class MyActor(scope: ActorScope<MyMsg>): Actor<MyMsg>(scope) {
    // your private state here
    override suspend fun onReceive(msg: MyMsg) {
        // ... your code here ...
    }
}

There is still some boiler-plate (MyMsg and scope are mentioned twice), but it is not clear how to further reduce it.

Now, you can define a generic actorOf function to start any kind of actor:

fun <T> actorOf(
    context: CoroutineContext,
    init: (ActorScope<T>) -> Actor<T>
): ActorJob<T> = actor<T>(context) {
        val instance = init(this@actor)
        for (msg in channel) instance.onReceive(msg)
    }

Using this function you can start your custom actor with a natural-looking and easy-to-read invocation actorOf(CommonPool, ::MyActor) with ability to further customize construction of your actor impl by providing an explicit lambda for an init block.

@fvasco

This comment has been minimized.

Copy link
Contributor Author

commented Jul 24, 2017

onReceive method is comfortable to use, but I want to expose you my concerns.

The actor function uses the iterable pattern, instead the Actor class use visitor pattern. Personally I consider the iterator pattern a better choice becouse it is possible to detect actor termination (end of iteration).

Using the explicit itaration in Actor makes it cut-and-paste compatible with the actor function.

I suggest to mantain Actor as public interface and to provide a comfortable implementation

public abstract class ActorBase<E>(actorScope: ActorScope<E>) : Actor<E>, ActorScope<E> by actorScope {

    override suspend fun invoke() {
        for (message in channel)
            onReceive(message)
    }

    public abstract suspend fun onReceive(message: E)
}

Finally actorOf misses of some parameters, we should keep this one, an extended version:

public fun <E> actorOf(
        context: CoroutineContext,
        capacity: Int = 0,
        start: CoroutineStart = CoroutineStart.DEFAULT,
        builder: (ActorScope<E>) -> Actor<E>
): ActorJob<E> = actor(context, capacity, start) {
    val actor = builder(this)
    actor.invoke()
}

or both?

@elizarov

This comment has been minimized.

Copy link
Member

commented Jul 24, 2017

Makes sense. I'd keep an extended version. Maybe rename actor.invoke() to actor.run() (similar to Thread's run method). I'm not sure that an actor base class should be called ActorBase. I'd either keep it an Actor to be short or name it AbstractActor.

@elizarov

This comment has been minimized.

Copy link
Member

commented Jul 24, 2017

Let me voice my concern that adding such functionality to the core is a start of a slippery road of turning it in into an actor-based programming framework. There are lots of issues to be addressed in a large-scale actor-based programming and the corresponding support libraries are only bound to grow over time. Maybe we should think-through what other things needs to be added, beyond an actor base-class and a construction function, and have a separate module to support all of that.

@elizarov

This comment has been minimized.

Copy link
Member

commented Jul 24, 2017

Also, if we are starting on a path of generic actor-based programming, then we are inevitably going to be compared with other actor-based frameworks, including comparisons on the basis of performance. It does not mean that we have to worry about performance up-front, but we have to keep our designs, at least, optimizable in the future.

That is my concern for overridable invoke/run method and other potential design decisions. Let me elaborate. A generic actor can, for example, start multiple concurrent actors to process a single mailbox concurrently if the actor's logic is stateless by itself. However, a stateful actor is must typically process its mailbox in serial fashion, e.g. it is a single consumer of its mailbox.

Current implementation of Channel is multi-consumer/multi-producer queue which makes it widely-applicable (it can do both use-cases), but it inevitably costs some performance. One might implement an optimized version of channel for single-producer case to support stateful-actor use-case with better performance, but then we have to ensure that it is not possible for an actor to accidentally launch additional coroutines to read from its mailbox (to make the design less error-prone and more fool-proof). It means that we should actually hide actor's ReceiveChannel from the actor itself.

@fvasco

This comment has been minimized.

Copy link
Contributor Author

commented Jul 24, 2017

At this time of development, a stateless concurrent actor can be implemented using a BroadcastChannel to create a different ActorScope for each worker actor.

However your concern sounds right to me, but I suggest to mantain an uniformity of actor function and Actor class

public interface Actor<in E> : CoroutineScope {
    public suspend fun onReceive(message: E)
}

public fun <E> actor(
        context: CoroutineContext,
        capacity: Int = 0,
        start: CoroutineStart = CoroutineStart.DEFAULT,
        onReceive: suspend CoroutineScope.(E) -> Unit
): ActorJob<E>

In such case we deprecate ActorScope in favour of Actor.

@elizarov

This comment has been minimized.

Copy link
Member

commented Jul 24, 2017

The idea of concurrent stateless actor is to have multiple instance working on the same mailbox in round-robin fashion as opposed to broadcasting messages to all actors. I actually considered adding an additional concurrency: Int = 1 optional parameter to actor builder to cover this use-case, so that you can launch multiple actors under the umbrella of a single ActorJob. However, it is not that really straight-forward as it does require us to start dabbling into supervision strategies, because multiple running coroutines do make it urgent to figure out what you are going to do when one of them crashes.

@fvasco

This comment has been minimized.

Copy link
Contributor Author

commented Jul 24, 2017

Yes obviously, I was wrong.

As you proposed above I consider preferable a different module for actor supervisor and so on.
In my opinion this module should offer a common pool of interfaces for asynchronous programming, an "actor" module should implement more complex use cases, but I hope that the "core" module can interoperate well with existent solutions like Quasar or Akka.

So in my limited scope of view this "core" module shoud propose an "Actor" as a "Producer" dual, all other implementation should extends core's interfaces and provides its own builders.

@elizarov

This comment has been minimized.

Copy link
Member

commented Apr 11, 2018

Let me record here a draft design that I current have with respect to complex actors. The idea is to radically reduce boiler-plate that is required for writing actors that accept multiple message types by providing a handy facility that totally avoids the need to write sealed class for messages by following this pattern:

class MyActor : Actor() {
    // actor state is here, must be private

    init {
        // optional state initialization code
    }

    // public actor operation without result
    suspend fun operationA(someParams...) = act {
        // logic here
    }

    // public actor operation with result
    suspend fun operationB(otherParams...): Result = actAndReply {
        // logic here
    }

    private fun helper() { /* regular code, can access state */ }
}

The idea is that all public functions defined on actor must be suspend and must invoke a special function (tentatively called act here) that captures "message parameters" (function parameters) and stores the message in the actor's inbox for processing. When response to the caller is needed, then a separate function (tentatively called actAndReply here) is used.

We can have IDE inspections to help avoid "sharing" pitfalls to verify that all of the actor's state is private and all the public functions are properly written using act pattern. IDE inspection can also help to ensure that only immutable types are passed in/out of actor or the proper defensive copies are made on mutable data (the latter is hard to ensure, though, without complicated reference capability annotations akin to the ones used in Pony language).

The reference to MyActor instance serves as a type-safe reference to an actor and should implement a Job interface. The actor is started lazily on the first invocation of any of its public (acting) functions or by explicitly invoking start(). Lazy start feature prevents races when systems of communicating actors are written like this:

class MySystem { 
    private val actorA = object : Actor() {
         // somewhere sends message to actorB
    }

    private val actorB = object : Actor() {
        // somewhere sends message to actorA
    }

    suspend fun facadeOperation() { actorA.doSomethig() }
}

We shall also consider changing default to CoroutineStart.LAZY for a simple actor { ... } builder, too.

@fvasco

This comment has been minimized.

Copy link
Contributor Author

commented Apr 13, 2018

Hi @elizarov
I wish expose some consideration about your -interesting- proposal.

Actor, as intended until now, is the dual of Producer, so your design does not help to write complex actor.

Your proposal looks like a fully synchronized, non blocking class, which is equally interesting.
I wrote a dummy implementation using your requirement plus one: avoid abstract superclass; so I wrote an task synchronization helper (TaskQueue here) and a case of use.

class TaskQueue(
        val context: CoroutineContext = DefaultDispatcher,
        val mutex: Mutex = Mutex(),
        lazyInit: (suspend CoroutineScope.() -> Unit)? = null
) {

    private var lazyInit: Deferred<Unit>?

    init {
        this.lazyInit = lazyInit?.let {
            async(context, start = CoroutineStart.LAZY, block = it)
        }
    }

    /**
     * Force lazy initialization
     */
    suspend fun init() {
        lazyInit?.run {
            await()
            lazyInit = null
        }
    }

    suspend operator fun <T> invoke(block: () -> T): T {
        init()
        return mutex.withLock(this) {
            withContext(context) {
                block()
            }
        }
    }
}

class HttpSession {

    val start = Instant.now()

    private lateinit var state: MutableMap<String, String>

    private val taskQueue = TaskQueue {
        state = mutableMapOf()
    }

    suspend fun get(key: String) = taskQueue {
        state[key]
    }

    suspend fun set(key: String, value: String) {
        taskQueue {
            state[key] = value
        }
    }
}

Plus: using this implementation and issue #94 makes easy to implement a read task queue and a write task queue.

@elizarov

This comment has been minimized.

Copy link
Member

commented Apr 13, 2018

@fvasco Indeed, it does look like a "like a fully synchronized, non blocking class", but it is not one. There are lots of similarities between monitor-based synchronization (like synchronized methods in Java) and actor-based programming model (like behavior functions in Pony). But there are important differences, too. Let me cite Pony documentation here:

A behaviour is like a function, except that functions are synchronous and behaviours are asynchronous.

Let's take a look at it in the context of Kotlin. First of all, we don't need new primitive for a "fully synchronized class". We already have Mutex. So, a fully synchronized class can be written like this:

class HttpSessionSync {
    private val mutex = Mutex()
    // state initialization does not have to happen under lock
    private var state: MutableMap<String, String> = mutableMapOf()
   
    suspend fun set(key: String, value: String) = mutex.withLock {
        state[key] = value
    }

    // etc
}

Notice the boilerplate here. We have to define private val mutex = Mutex() every time we use this pattern, so some kind of out-of-the box Mutex abstract base class might help. Shall we make Mutex open? Anyway, we don't want to promote this pattern, so we will not further discuss it in this thread.

You've made an interesting observation that requiring base class for complex actors is not good idea, so while, IMHO, we should give an option of using one, it should not be a requirement. Let's sketch implementation of a complex actor without having to use a base class:

class HttpSessionActor {
    private val actor = Actor()
    // state initialization does not have to happen under lock
    private var state: MutableMap<String, String> = mutableMapOf()
   
    suspend fun set(key: String, value: String) = actor.act {
        state[key] = value
    }

    // etc
}

What is the difference here as compared to Mutex-based version? The difference is that an Actor has an inbox channel and sending messaged to an actor can be decoupled from their execution. When HttpSessionActor.set is invoked, the invoker can go on with it own work while HttpSessionActor is busy, unless actor's mailbox capacity is exhausted. In the latter case, the invoker will have to wait until mailbox has capacity to store a message, but not longer. This starts to be important for scalability when actors perform long-running asynchronous activities.

@fvasco

This comment has been minimized.

Copy link
Contributor Author

commented Apr 13, 2018

@elizarov thanks for explanation,
in some sense a Mutex act like an actor with capacity = 0 and without coroutine context.

I fix my draft, but I sure that it is possible to implement a better one.

class TaskChannel(
        context: CoroutineContext = DefaultDispatcher,
        capacity: Int = 0,
        lazyInit: (suspend CoroutineScope.() -> Unit)? = null
) {

    private val tasks = Channel<Task<*>>(capacity)

    private var lazyInit: Deferred<*>? = async(context, start = CoroutineStart.LAZY) {
        lazyInit?.invoke(this)

        launch(coroutineContext) {
            tasks.consumeEach { it() }
        }
    }

    /**
     * Force lazy initialization
     */
    suspend fun init() {
        lazyInit?.run {
            await()
            lazyInit = null
        }
    }

    suspend fun <T> act(block: suspend () -> T): Deferred<T> {
        init()
        val task = Task(block)
        tasks.send(task)
        return task
    }

    suspend fun <T> actAndReply(block: suspend () -> T): T = act(block).await()

    private class Task<T>(block: suspend () -> T) : CompletableDeferred<T> by CompletableDeferred() {
        private var block: (suspend () -> T)? = block

        suspend operator fun invoke() {
            try {
                complete(block!!())
            } catch (t: Throwable) {
                completeExceptionally(t)
            } finally {
                block = null
            }
        }
    }
}
@elizarov

This comment has been minimized.

Copy link
Member

commented Apr 15, 2018

Even with capacity = 0 the Actor is asynchronous. You can send a message to an Actor and continue working on your code, while actor processes your message concurrently with your code. The Mutex, on the other hand, is always synchronous. No concurrency. That is, conceptually, why solutions based on Mutex/synchronized do not scale well.

@qwwdfsad qwwdfsad self-assigned this May 23, 2018

@fvasco

This comment has been minimized.

Copy link
Contributor Author

commented Jun 15, 2018

Even with capacity = 0 the Actor is asynchronous
The Mutex ... is always synchronous.

@elizarov can you confirm the follow code snippet?

suspend fun operationB(otherParams...): Result = actAndReply {
    // logic here
}

Is the functions's return typeResult and not Deferred<Result>?

Accordly with #261 it is pretty easy write the act function on top of a single private executor.

@elizarov

This comment has been minimized.

Copy link
Member

commented Jun 15, 2018

@fvasco Yes, when you ask and actor and want a result back the proper design would be to have a suspend fun with a normal (non-deferred) Result. However, please note that this whole ask & wait pattern is an anti-pattern in actor-based systems, since it limits scalability. Well-designed actor-based system do not work that way.

Internally, actors are still implemented on top of channels.

qwwdfsad added a commit that referenced this issue Aug 9, 2018

twyatt added a commit to JuulLabs-OSS/able that referenced this issue Oct 8, 2018

Remove Messenger actor and use withContext instead
Inspired by Kotlin/kotlinx.coroutines/87 [comment] by elizarov on Jun 15:

> when you ask and actor and want a result back the proper design would
> be to have a `suspend fun` with a normal (non-deferred) `Result`.
> However, please note that this whole ask & wait pattern is an
> anti-pattern in actor-based systems, since it limits scalability.

Kotlin/kotlinx.coroutines#87 (comment)

twyatt added a commit to JuulLabs-OSS/able that referenced this issue Oct 8, 2018

Remove Messenger actor and use withContext instead
Inspired by [Kotlin/kotlinx.coroutines/87] [comment] by elizarov on Jun 15:

> when you ask and actor and want a result back the proper design would
> be to have a `suspend fun` with a normal (non-deferred) `Result`.
> However, please note that this whole ask & wait pattern is an
> anti-pattern in actor-based systems, since it limits scalability.

[comment]: Kotlin/kotlinx.coroutines#87 (comment)

twyatt added a commit to JuulLabs-OSS/able that referenced this issue Oct 8, 2018

Remove Messenger actor and use withContext instead
Inspired by Kotlin/kotlinx.coroutines#87 [comment] by elizarov on Jun 15:

> when you ask and actor and want a result back the proper design would
> be to have a `suspend fun` with a normal (non-deferred) `Result`.
> However, please note that this whole ask & wait pattern is an
> anti-pattern in actor-based systems, since it limits scalability.

[comment]: Kotlin/kotlinx.coroutines#87 (comment)

twyatt added a commit to JuulLabs-OSS/able that referenced this issue Oct 8, 2018

Remove Messenger actor and use withContext instead
Inspired by [comment] by elizarov (on Jun 15) in
Kotlin/kotlinx.coroutines#87:

> when you ask and actor and want a result back the proper design would
> be to have a `suspend fun` with a normal (non-deferred) `Result`.
> However, please note that this whole ask & wait pattern is an
> anti-pattern in actor-based systems, since it limits scalability.

[comment]: Kotlin/kotlinx.coroutines#87 (comment)

twyatt added a commit to JuulLabs-OSS/able that referenced this issue Oct 17, 2018

Remove Messenger actor and use withContext instead
Inspired by [comment] by elizarov (on Jun 15) in
Kotlin/kotlinx.coroutines#87:

> when you ask and actor and want a result back the proper design would
> be to have a `suspend fun` with a normal (non-deferred) `Result`.
> However, please note that this whole ask & wait pattern is an
> anti-pattern in actor-based systems, since it limits scalability.

[comment]: Kotlin/kotlinx.coroutines#87 (comment)
@fvasco

This comment has been minimized.

Copy link
Contributor Author

commented Oct 28, 2018

Hi @elizarov

We can have IDE inspections to help avoid "sharing" pitfalls to verify that all of the actor's state is private and all the public functions are properly written using act pattern.

I considering a lot this phrase, I wish to avoid this type of language support (workaround) around as much is possible.

To enforce this we can encapsulate the actor's state, so the programmer is forced to invoke the act function.

I try to explain better myself: an actor requires: a queue, some message types and an optional state.
I encapsulate the state in a ActorState type, and I can operate on it using some functions, like update (names are only examples).

The follow interface can encapsulate the state

interface ActorState<T> : CoroutineScope {

    suspend fun update(block: T.() -> Unit)
}

so we define a simple builder (may requires more parameters):

fun <T> actorState(state: T): ActorState<T> = TODO()

Finally an actor's example

class Counter /* no superclass required */ {

    private var state = actorState(object {
        var count = 0
    })

    suspend fun increment(amount: Int = 1) = state.update { count += amount }

}

That's all, I cannot more avoid the queue.

twyatt added a commit to JuulLabs-OSS/able that referenced this issue Oct 29, 2018

Remove Messenger actor and use withContext instead
Inspired by [comment] by elizarov (on Jun 15) in
Kotlin/kotlinx.coroutines#87:

> when you ask and actor and want a result back the proper design would
> be to have a `suspend fun` with a normal (non-deferred) `Result`.
> However, please note that this whole ask & wait pattern is an
> anti-pattern in actor-based systems, since it limits scalability.

[comment]: Kotlin/kotlinx.coroutines#87 (comment)

twyatt added a commit to JuulLabs-OSS/able that referenced this issue Oct 29, 2018

Remove Messenger actor and use withContext instead
Inspired by [comment] by elizarov (on Jun 15) in
Kotlin/kotlinx.coroutines#87:

> when you ask and actor and want a result back the proper design would
> be to have a `suspend fun` with a normal (non-deferred) `Result`.
> However, please note that this whole ask & wait pattern is an
> anti-pattern in actor-based systems, since it limits scalability.

[comment]: Kotlin/kotlinx.coroutines#87 (comment)

twyatt added a commit to JuulLabs-OSS/able that referenced this issue Oct 29, 2018

Remove Messenger actor and use withContext instead
Inspired by [comment] by elizarov (on Jun 15) in
Kotlin/kotlinx.coroutines#87:

> when you ask and actor and want a result back the proper design would
> be to have a `suspend fun` with a normal (non-deferred) `Result`.
> However, please note that this whole ask & wait pattern is an
> anti-pattern in actor-based systems, since it limits scalability.

[comment]: Kotlin/kotlinx.coroutines#87 (comment)

twyatt added a commit to JuulLabs-OSS/able that referenced this issue Nov 12, 2018

Remove Messenger actor and use withContext instead
Inspired by [comment] by elizarov (on Jun 15) in
Kotlin/kotlinx.coroutines#87:

> when you ask and actor and want a result back the proper design would
> be to have a `suspend fun` with a normal (non-deferred) `Result`.
> However, please note that this whole ask & wait pattern is an
> anti-pattern in actor-based systems, since it limits scalability.

[comment]: Kotlin/kotlinx.coroutines#87 (comment)
@adam-arold

This comment has been minimized.

Copy link

commented Nov 23, 2018

What is your suggestion for those who want to use actors in the meantime (until actors come out of the experimental stage)? I'm currently working on a multiplatform library, so using coroutines to enable concurrency is very convenient, but I'm a bit puzzled about the best way (currently) to go about implementing something like a complex actor in your examples (A class which has suspending functions which work on shared mutable state).

@vemilyus

This comment has been minimized.

Copy link

commented Dec 30, 2018

I've created an implementation of such an "ActorState" (as described by @fvasco)

Maybe it can be of some use, or you could also tell me how it is complete crap ;)

https://gist.github.com/vemilyus/c19f5d75525a37b33c4640bfd61158fe

@fvasco

This comment has been minimized.

Copy link
Contributor Author

commented Jan 1, 2019

you could also tell me how it is complete crap

I am really tempted :)

You should use only a read-write mutex (#94), or a regular channel or mutex.

twyatt added a commit to JuulLabs-OSS/able that referenced this issue Mar 3, 2019

Remove Messenger actor and use withContext instead
Inspired by [comment] by elizarov (on Jun 15) in
Kotlin/kotlinx.coroutines#87:

> when you ask and actor and want a result back the proper design would
> be to have a `suspend fun` with a normal (non-deferred) `Result`.
> However, please note that this whole ask & wait pattern is an
> anti-pattern in actor-based systems, since it limits scalability.

[comment]: Kotlin/kotlinx.coroutines#87 (comment)
@gortiz

This comment has been minimized.

Copy link

commented Apr 23, 2019

The elizarov's proposal looks great in paper, but I would not delegate the sharing check responsibility on the IDE.

I prefer the Akka Typed approach where sharing is forbidden by the compiler and the separation between the channel/mailbox and the behavior is explicit.

@elizarov

This comment has been minimized.

Copy link
Member

commented Apr 23, 2019

@gortiz At this point we are looking at pure library/IDE solution. Langauge-level changes are out the question for now. As for the explicit separation of behaviour, our goal here is to reduce the amount of boilerplate one need to write to define an actor, not increase it.

@gortiz

This comment has been minimized.

Copy link

commented Apr 24, 2019

I have been working with Kotlin actors for months and I think they have very low boilerplate in comparison with untyped Akka actors (where usually you need to extend a class if using the Java dsl, the only one I can use from Kotlin). But with the introduction of Akka Typed, the boilerplate was reduced a lot and they are almost as compact as Kotlin actors.

When I found Kotlin actors problematic is when you try to go beyond the most trivial use cases. I understand that I may have a bias towards Akka because I'm most use of it, but I find quite complex to implement in Kotlin some common actor patterns like send a message to yourself, create a ticker/scheduler, create an adaptor or receive messages from different type hierarchies. Guys from Akka have been trying to solve this problems for 10 years after three attempts, it seems that they have found a nice API that is at the same quite time safe at compile, easy to use and quite compact.

Simple Akka Typed actors are written as a function in a way that is almost equal to current Kotlin actors and the most complex patterns are delegated on a object call ActorContext that is obtained as a parameter.

Akka Typed is not perfect either. There are some use cases that are not easy to implement. For example the common case on which you want to stage all messages received by an actor until some message arrives. On Akka Typed you need to create a behavior to do that. On Kotlin we can implement the ask pattern using suspending functions, suspending the actor until the answer is found.

The Akka Typed has some flaws that make it not completely secure at compile time. For example some functions on ActorContext can be called from any thread but most of them can only be called from the actor thread. That is clearly explain on the javadoc of each method, but it is easy to forget. I have been working on a small Akka Typed Kotlin DSL where can be called from any thread are normal methods, but the others are suspending methods that are executed on the actor thread by using the ask pattern.

I'm not saying Kotlin should copy the Akka Typed API, just learn from it and improve it. There are still problems that are difficult to solve by Akka where Kotlin has a big advantage.

The way to use the actor proposed by Elizarov has its advantages, but I would prefer to have an ActorRef/Channel to send messages and then create extensions functions that call act/tell or actWithReply/ask and being able to define actors (even complex actors!) with behaviors/functions instead of creating classes.

@elizarov

This comment has been minimized.

Copy link
Member

commented Apr 24, 2019

@gortiz All valid points. However, we do not plan to turn kotlinx.coroutines into an actor-based framework with actor refs, actor systems, actor contexts, replies, etc. In terms of kotlinx.coroutines actor is just a code organization pattern -- a coroutine plus an incoming channel. Nothing more. Something more than that has to be living in a separate library.

@adam-arold

This comment has been minimized.

Copy link

commented Apr 24, 2019

@elizarov does this mean that I should not wait for improvements to the current actor? The documentation points to this issue and states that the current actor is obsolete and they will get replaced with the introduction of complex actors.

@elizarov

This comment has been minimized.

Copy link
Member

commented Apr 24, 2019

@adam-arold The plan roughly outlined here (for "writing complex actor") is approximately how far it will go as a part of kotinx.coroutines in a foreseeable future. If you want more, I'd suggest to start writing your own coroutine-based actor framework. I'm sure it'll be quite popular if you make it open source.

@adam-arold

This comment has been minimized.

Copy link

commented Apr 24, 2019

@elizarov I'll do that! I'm going to wait until your final solution is released then I'll build on top of that. @gortiz do you have plans for doing something similar?

@gortiz

This comment has been minimized.

Copy link

commented Apr 25, 2019

The more I use actors, the more necessary I find frameworks specially created to deal with the common actor patterns. I don't think we should create another actor framework but to make easier to integrate the amazing kotlin functionalities with the frameworks we already have.

And there are already two mature frameworks on the JVM world: Akka and Quasar. I didn't use Quasar, but as it uses their own coroutines, they seem to be closer to the Kotlin aproach. I have more experience with Akka, where actors suspendable actors should be useful when dealing with blocking code (because of IO or high computation costs).

My plan right now is to develop a Akka Typed Kotlin DSL that makes easier and nicer to call the Scala/Java APIs from Kotlin. That is not very ambitious and in fact it can be done with a very small project. It is very easy to create suspendable actors that stage messages while the actor is suspended. The main problem there is that it may be not very efficient. What I would really like is to create an Akka Actor System that is able to execute suspendable actors natively, but:

  1. Doesn't seem easy.
  2. Is more related to Akka itself than Kotlin

By the way, I want to emphasize that Kotlin actors are fantastic for most cases. Frameworks like Akka are needed once you want do more complex things like scheduling (although it wouldn't be difficult to implement in Kotlin actors), clustering (using location transparency) or persistence (for event source systems, for example). I'm thinking on migrate the application I wrote using Kotlin actors to Akka just because of the last two features, but Kotlin actors allow me to rapidly create the first version of it and most importantly it was very easy to think on concurrency and error management on a higher level and I'm sure that by using Kolin actors the application is more resilent that it would be if it was implemented on other non-actor based frameworks .

@adam-arold

This comment has been minimized.

Copy link

commented Apr 25, 2019

I'm planning to work on a Kotlin approach (not a wrapper) because I'm going to write common code which will work on all Kotlin-supported platforms. For this reason, Akka and Quasar are not applicable in my use case.

@adam-arold

This comment has been minimized.

Copy link

commented Apr 25, 2019

@elizarov do you have a rough ETA on the final version of this Issue?

@elizarov

This comment has been minimized.

Copy link
Member

commented Apr 25, 2019

Not yet. We are busy with Kotlin Flow for now, which is a higher-priority for us to finish.

@adam-arold

This comment has been minimized.

Copy link

commented Apr 25, 2019

Kotlin Flow is gonna be awesome. I'll keep myself busy with something else in the meantime.

@ZakTaccardi

This comment has been minimized.

Copy link

commented May 17, 2019

Once complex actors are implemented, what happens to the existing actor? Is it going to be removed?

Would it be possible to release the existing actor as a separate artifact for legacy support? I'm asking because I would like to get my company to adopt actor usage (I think it's an awesome way to build/update state), but the @ObsoleteApi causes a bit of hesitancy for us to adopt within our company.

One approach we've considered is completely re-implementing the actor ourselves, but I think that risks some subtle bugs around concurrency and exception handling

@elizarov

This comment has been minimized.

Copy link
Member

commented May 23, 2019

No decision yet on current actors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.