FSM vs become/unbecome in Akka

五迷三道 提交于 2021-02-05 19:59:39

问题


Akka provides two somewhat overlapping ways to manage actor states, Finite State Machines and unbecome/become. What are their respective benefits/drawbacks? When should one of them be chosen over the other?


回答1:


FSM is a DSL that allows you to build more sophisticated, readable state machines than would be possible using the core actor API. You could potentially show the FSM code to a business person and they could validate the business rules.

The FSM DSL allows you to compose things together more cleanly. For example transitions allow you to factor out logic that would have to be duplicated across actor become behaviors. Also you can subscribe other actors to be notified of transitions which helps with decoupling and testing.

Also timers are integrated nicely into the DSL and things like cancellation are handled cleanly. Coding timeout messages using the scheduler has a number of gotchas.

The down side to FSM is that it's a DSL and a new syntax for other team members to digest. The up side is that it's a DSL and a much higher level abstraction. I think agilesteel's threshold of 2 states is a good one. But once you get past 2 states the benefits of FSM are really compelling.

Definitely read the FSM docs and the accompanying examples contrasting become and FSM.

One note re: "popping" a behavior using unbecome - the default behavior is to not use the behavior stacking. It is only relevant in a small number of use cases (ie, usually not state machines).




回答2:


Become/Unbecome are very lightweight in contrast to FSMs. So unless you have more than 2 states (on/off for example) and/or complex state change policies I wouldn't convert Become/Unbecome to a full blown FSM. Other then that, I think there are only minor differences...Like for example FSMs give you a nice built in timer DSL:

setTimer("TimerName", msg, 5 seconds, repeat = true)
// ...
cancelTimer("TimerName")

Or for instance I'm not sure if it's possible in an FSM to "go back" to the previous state, there is only "go forward", since you have to explicitly specify which state to go to. Whereas unbecome gives you exactly that.



来源:https://stackoverflow.com/questions/17110045/fsm-vs-become-unbecome-in-akka

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!