Monday, August 11, 2008

Asynchronous, Functional and automatically Concurrent

The following code fragment is from an earlier post on using Scala actors and AMQP. I thought I would bring this snippet up once again to highlight some of the goodness that functional Scala offers in modeling actor model of concurrent computation.


import scala.actors.Actor

case class Trade(id: Int, security: String, principal: Int, commission: Int)
case class TradeMessage(message: Trade)
case class AddListener(a: Actor)

class TradingService extends Actor {

  def act = loop(Nil)

  def loop(traders: List[Actor]) {
    react {
    case AddListener(a) => loop(:: traders)
    case msg@TradeMessage(t) => traders.foreach(! msg); loop(traders)
    case _ => loop(traders)
    }
  }
}



An implementation of the Observer design pattern using message passing. Interested traders can register as observers and observe every trade that takes place. But without any mutable state for maintaining the list of observers. Not a very familiar paradigm to the programmers of an imperative language. The trick is to have the list of observers as an argument to the loop() function which is tail called.

Nice .. asynchronous, referentially transparent, side-effect-free functional code. No mutable state, no need of explicit synchronization, no fear of race conditions or deadlocks, since no shared data are being processed concurrently by multiple threads of execution.

7 comments:

Peter said...

Hey, did you ever benchmark Rabbit MQ against other contenders? ActiveMQ, Qpid?

James Iry said...

Just a small quibble, but the code is not really referentially transparent since it depends on the side effected react. React takes a partial function as a parameter and passes to it a message which is neither a parameter to react nor a value in the lexical scope.

That's not to say anything bad about the code. This kind of "state via recursion" programming is a great way to keep actors nice and clean.

It's just to recognize that message passing concurrency, and indeed most forms of concurrency that aren't simple parallel computation like data flow variables/futures, are inherently side effected.

sanjiv said...

Sir,
Just wondered what you thought of this :
http://apocalisp.wordpress.com/2008/07/28/threadless-concurrency-with-actors/
and the package on which it is based :
http://functionaljava.org/

The above to me looks more approachalbe instead of abandoning the Java language (if i take up Scala) or the entire eco-system (if I take up Erlang).

Regards,

Unknown said...

@James: Thanks for pointing it out. I have posted a small update here.

Unknown said...

@AnActor: I have not yet looked at Functional Java in detail. But why bend Java to do something which it was not designed for. Scala offers a much cleaner programming model - a neat actor implementation in a library, with much usable syntax (thanks to its better type system). And above all it's all on the JVM !

jherber said...

@anactor - though functional java looks quite brilliant, it still relies on closures, which are not yet shipping with java. in the recent neil grafter interview (up on infoQ), neil says he does not think closures will make it into java7. i'm not sure what ramifications that would entail should functional java's notion and dependency on a particular closure model get out of sync with what actually ships.

if you are stuck on java and need an actor framework, kilim might also be worth investigating. it appears very performant and well thought out.

or... scala is here now. the book will probably hit the press within next 30 days, and buzz will surely abound.

sanjiv said...

@JHerber: Thank you for the directives. Yes I intend to give Kilim a try one of these days.

Its not that I am stuck with Java but just exploring the options. I am trying to soften the communication I would need to deliver to management and still try out FP. If I pitch Scala or Erlang, for sure I would face understandable questions like :

1. Why the heck are we spending so much moolah trying to get our programmers competent on the Java platform ?
2. So we are not going to tap into the wealth of experience and competence gained on the Java ecosystem ?
3. Uhh so would we miss deadlines and therefore revenue targets for the next quarter because of this new stuff ?
4. How are you going to get your teams of young programmers (3-4 yrs of experience) to shift to a totally different way of programming/thinking - not just a new language, and finally deliver performant, maintainable, production quality systems that need to replace well established existing ones ?
5. Are you sure Scala or Erlang are not nitch players and would become mainstream and we would not need to pay a bomb just to hire/retain a bunch of average programmers ?