I would like to use Akka to implement a multiple-readers / one-writer pattern on a data structure, but I am stuck in the design of the actor model.
My initial thought was to have a supervisor actor which would receive external requests (read or write). Read requests would be forwarded to reader actors for asynchronous processing. Write requests would wait for all readers to finish and then be processed synchronously.
My problem is how to implement the “wait for all readers to finish” part.
I first thought of keeping a counter at the supervisor. The counter would be incremented every time the supervisor forwards a message to a reader. The reader would then send an “I am done” message back to the supervisor when it finished, which would then decrease the counter. However, I think this would lead to deadlocks, since the “I am done” messages would go to the same mailbox as the external requests. If the supervisor was processing a write request synchronously then the “I am done” would never reach it.
I am really stuck with the design. Any help would be appreciated.
Per the comments above.
Add a queue to your supervisor actor to queue incoming requests. When the readers send back the finished message, take a task off the queue and give it to the readers.