Question

Can I set maximum size for an actor's mailbox in Scala?

Take the Producer-Consumer problem. With threads I can block the producers when the buffer fills up. I saw a couple of producer-consumer examples written in Scala and they all use actors with mailboxes used as a "buffer". Can I set mailbox size to cause producers to wait until a consumer is ready? Any other elegant solution to avoid uncontrollable growth of mailboxes?

Was it helpful?

Solution

You can create an actor that acts as a buffer between the producer and consumer. The buffer checks out its mailbox to its loop data. It sends back an "overload" message to the producer when the number of buffered products is too high; and sends a "clear" message once everything is back in order. In case of too many messages it simply drops incoming ones (or oldest ones).

The consumer actively requests for products from the buffer, which in turn sends back one product. If the buffer is empty, the consumer keeps waiting for the input.

The producer sends products to the buffer actor. If it receives an "overload" message it can stop production, or it can continue producing, knowing the fact that the products might get dropped.

Of course this logic could directly be implemented into the producer or consumer itself, but a separate buffer will allow you to introduce multiple producers and/or consumers more easily.

OTHER TIPS

The Actor.mailboxSize method returns the number of pending messages in the Actor's mailbox.

This can be used for throttling the producer in various ways.

For example, one possibility could be,

The producer checks if the consumer's mailboxSize is greater than some threshold. If it is, then it sends a SpecialMessage to the consumer, and blocks on a semaphore. When the consumer receives this SpecialMessage it releases the semaphore. The producer can now merrily continue it's business.

This avoids polling as well as any dropped messages.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top