Scala actors - worst practices? [closed]
Solution 1:
Avoid
!?
wherever possible. You will get a locked system!-
Always send a message from an Actor-subsystem thread. If this means creating a transient Actor via the
Actor.actor
method then so be it:case ButtonClicked(src) => Actor.actor { controller ! SaveTrade(trdFld.text) }
-
Add an "any other message" handler to your actor's reactions. Otherwise it is impossible to figure out if you are sending a message to the wrong actor:
case other => log.warning(this + " has received unexpected message " + other
-
Don't use
Actor.actor
for your primary actors, sublcassActor
instead. The reason for this is that it is only by subclassing that you can provide a sensibletoString
method. Again, debugging actors is very difficult if your logs are littered with statements like:12:03 [INFO] Sending RequestTrades(2009-10-12) to scala.actors.Actor$anonfun$1
Document the actors in your system, explicitly stating what messages they will receive and precisely how they should calculate the response. Using actors results in the conversion of a standard procedure (normally encapsulated within a method) to become logic spread across multiple actor's reactions. It is easy to get lost without good documentation.
Always make sure you can communicate with your actor outside of its
react
loop to find its state. For example, I always declare a method to be invoked via anMBean
which looks like the following code snippet. It can otherwise be very difficult to tell if your actor is running, has shut down, has a large queue of messages etc.
.
def reportState = {
val _this = this
synchronized {
val msg = "%s Received request to report state with %d items in mailbox".format(
_this, mailboxSize)
log.info(msg)
}
Actor.actor { _this ! ReportState }
}
Link your actors together and use
trapExit = true
- otherwise they can fail silently meaning your program is not doing what you think it is and will probably go out of memory as messages remain in the actor's mailbox.I think that some other interesting choices around design-decisions to be made using actors have been highlighted here and here
Solution 2:
I know this doesn't really answer the question, but you should at least take heart in the fact that message-based concurrency is much less prone to wierd errors than shared-memory-thread-based concurrency.
I presume you have seen the actor guidelines in Programming in Scala, but for the record:
- Actors should not block while processing a message. Where you might want to block try to arrange to get a message later instead.
- Use
react {}
rather thanreceive {}
when possible. - Communicate with actors only via messages.
- Prefer immutable messages.
- Make messages self-contained.