scala mailbox size limit

前端 未结 2 1083
刺人心
刺人心 2020-12-16 14:53

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

相关标签:
2条回答
  • 2020-12-16 14:58

    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.

    0 讨论(0)
  • 2020-12-16 14:59

    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.

    0 讨论(0)
提交回复
热议问题