Fabien Benoit-Koch
Fabien Benoit-Koch

Reputation: 2841

Thread safety of actors running future callbacks

The akka documentation states:

(...) you can just write your actor code without worrying about concurrency at all.

Behind the scenes Akka will run sets of actors on sets of real threads, where typically many actors share one thread, and subsequent invocations of one actor may end up being processed on different threads. Akka ensures that this implementation detail does not affect the single-threadedness of handling the actor’s state.

But let's say i'm building a Future, and pipe it to a callback, in the event-handling thread. For example, using the ask pattern:

ask(someActor, new SomeRequest(), timeout)
            .onSuccess(new OnSuccess<Object>() {
                @Override
                public void onSuccess(Object answer) throws Throwable {

                  // Modify actor state

                }
            }, getContext().system().dispatcher());

Does this means the callback will never be executed concurrently with the event-handling thread ? And thus, can safely modify the actor state without worrying about synchronization?

Upvotes: 1

Views: 265

Answers (2)

Jatin
Jatin

Reputation: 31724

Does this means the callback will never be executed concurrently with the event-handling thread

In your case No. The callback can be executed concurrently.

To explain: Thread safety of actors comes from confinement. i.e. Akka guarantees that your actor body will only be executed by a single thread at once when actor receives a message.

Now in the mean time, if you spawn a thread and that tries mutating some internal state (like a variable or something), then akka has no control over it. The message consumption and future body execution by a thread can both happen in parallel.

And thus, can safely modify the actor state without worrying about synchronization?

If your future blocks deals with variables that are never used by body, then you probably dont need synchronization. In case it does, then you need it.

Upvotes: 3

Leo Bufi Barrameda
Leo Bufi Barrameda

Reputation: 359

When you mean by "// Modify actor state" is doing a bang (!) to self then it should be okey, but if it's really modify the Actor state then it's a NOK.

The threadsafe property of Actor is due to it's mailbox and actor properties that it only process one message at a time. If you don't use the mailbox of an Actor to modify it's state then you need to do your own locking/synchronizing of those mutable state. (for better explanation please refer to this link: http://doc.akka.io/docs/akka/snapshot/general/jmm.html#Actors_and_the_Java_Memory_Model)

Upvotes: 0

Related Questions