scala mailbox size limit

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?


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.


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.

链接地址: http://www.djcxy.com/p/21502.html

上一篇: 设计模式/建立演员的最佳做法

下一篇: scala邮箱大小限制