How to share a resource among Actors


(Ignatius) #1

Hi,

How can one share a resource, such as a connection, among multiple actors?

I understand the situation if I have a connection pool - then I can make an actor that can pass connections to other actors.

But what if the resource only allows one connection in total, but multiple actors need to access it? This seems to violate the paradigm of “no shared mutable state”. But what if I need it?

I have been considering

  • putting the connection into an Akka Extensions, so that multiple actors have access to it
  • passing the connection to an actor at creation time

Let’s say for this discussion that the connection object is thread-safe (extra points for a solution that works on non-threadsafe connections)

Thanks!


(Ivano Pagano) #2

The shared resource might be located in a single actor instance that will receive messages from every other actor needing such resource.

The main consideration remains the same, though: the resource (e.g. connection) should be exclusively used by the “owning” actor, and not be passed around… lest facing the same problem of knowing when it’s safe to use the connection.

Instead you can build an API (or more precisely a message protocol) to speak with the owner, that will process requests and eventually reply with the answer.
The actor can then adopt any internal lock or lock-free solution that it needs to process the requests on limited-access resources.

This is not so different from sending a job description to a job scheduler, and waiting for job completion. The scheduler takes care of thread handling and job queueing.

Consider that this is only the general idea, there’s much more to be figured out, starting from resource pooling (usually done for connections), thread handling (accessing the resource is usually a blocking I/O operation, so the owner actor should run on a separate dispatcher probably), …


(Ignatius) #3

Thanks, makes a lot of sense. So basically you encapsulate the resource with an actor, and that actors responsibility is to make the functionality related to the resource available to all other actors via messages.


(Ivano Pagano) #4

This is my first thoughts on how I’d approach the problem.

It might well be that someone explored the possibilities and found even better solutions.