<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
 
 <title>Jonas Bon&#233;r</title>
 <link href="http://jonasboner.com/atom.xml" rel="self"/>
 <link href="http://jonasboner.com/"/>
 <updated>2010-05-12T09:47:23+02:00</updated>
 <id>http://jonasboner.com/</id>
 <author>
   <name>Jonas Bon&#233;r</name>
   <email>info AT jonasboner DOT com</email>
 </author>

 
 <entry>
   <title>Introducing Akka - Simpler Scalability, Fault-Tolerance, Concurrency &amp; Remoting through Actors</title>
   <link href="http://jonasboner.com/2010/01/04/introducing-akka.html"/>
   <updated>2010-01-04T00:00:00+01:00</updated>
   <id>http://jonasboner.com/2010/01/04/introducing-akka</id>
   <content type="html">&lt;h1&gt;Introducing Akka &amp;#8211; Simpler Scalability, Fault-Tolerance, Concurrency &amp;amp; Remoting through Actors&lt;/h1&gt;
&lt;p class=&quot;meta&quot;&gt;4 Jan 2010&lt;/p&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;Writing correct concurrent, fault-tolerant and scalable applications is too hard. Most of the time it&amp;#8217;s because we are using the wrong tools and the wrong level of abstraction.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://akkasource.org&quot;&gt;Akka&lt;/a&gt; is an attempt to change that.&lt;/p&gt;
&lt;p&gt;Akka uses the Actor Model together with Software Transactional Memory to raise the abstraction level and provide a better platform to build correct concurrent and scalable applications.&lt;/p&gt;
&lt;p&gt;For fault-tolerance Akka adopts the &amp;#8220;Let it crash&amp;#8221;, also called &amp;#8220;Embrace failure&amp;#8221;, model which have been used with great success in the telecom industry to build applications that self-heals, systems that never stop.&lt;/p&gt;
&lt;p&gt;Actors also provides the abstraction for transparent distribution and the basis for truly scalable and fault-tolerant applications.&lt;/p&gt;
&lt;p&gt;Akka is Open Source and available under the Apache 2 License.&lt;/p&gt;
&lt;p&gt;In this article we will introduce you to Akka and see how we can utilize it to build a highly concurrent, scalable and fault-tolerant network server.&lt;/p&gt;
&lt;p&gt;But first let&amp;#8217;s take a step back and discuss what Actors really are and what they are useful for.&lt;/p&gt;
&lt;h1&gt;Actors&lt;/h1&gt;
&lt;p&gt;&lt;a href=&quot;http://en.wikipedia.org/wiki/Actor_model&quot;&gt;The Actor Model&lt;/a&gt; provides a higher level of abstraction for writing concurrent and distributed systems. It alleviates the developer from having to deal with explicit locking and thread management. It makes it easier to write correct concurrent and parallel systems. Actors are really nothing new, they were defined in the 1963 paper by Carl Hewitt and have been popularized by the Erlang language which emerged in the mid 80s. It has been used by for example at Ericsson with great success to build highly concurrent and extremely reliable (99.9999999 % availability &amp;#8211; 31 ms/year downtime) telecom systems.&lt;/p&gt;
&lt;p&gt;Actors encapsulates state and behavior into a lightweight process/thread. In a sense they are like OO objects but with a major semantic difference; they &lt;strong&gt;do not&lt;/strong&gt; share state with any other Actor. Each Actor have their own view of the world and can only have impact on other Actors by sending messages to them. Messages are sent asynchronously and non-blocking in a so-called &amp;#8220;fire-and-forget&amp;#8221; manner where the Actor sends off a message to some other Actor and then do not wait for a reply but goes off doing other things or are suspended by the runtime. Each Actor has a mailbox (ordered message queue) in which incoming messages are processed one by one. Since all processing is done asynchronously and Actors do not block and consume any resources while waiting for messages, Actors tend to  give very good concurrency and scalability characteristics and are excellent for building event-based systems.&lt;/p&gt;
&lt;h1&gt;Creating Actors&lt;/h1&gt;
&lt;p&gt;Akka has both a &lt;a href=&quot;http://doc.akkasource.org/actors&quot;&gt;Scala &lt;span class=&quot;caps&quot;&gt;API&lt;/span&gt;&lt;/a&gt; and a &lt;a href=&quot;http://doc.akkasource.org/active-objects&quot;&gt;Java &lt;span class=&quot;caps&quot;&gt;API&lt;/span&gt;&lt;/a&gt;. In this article we will only look at the Scala &lt;span class=&quot;caps&quot;&gt;API&lt;/span&gt; since that is the most expressive one. The article assumes some basic Scala knowledge, but even if you don&amp;#8217;t know Scala I don&amp;#8217;t think it will not be too hard to follow along anyway.&lt;/p&gt;
&lt;p&gt;Akka has adopted the same style of writing Actors as Erlang in which each Actor has an explicit message handler which does pattern matching to match on the incoming messages.&lt;/p&gt;
&lt;p&gt;Actors can be created either by:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Extending the &amp;#8216;Actor&amp;#8217; class and implementing the &amp;#8216;receive&amp;#8217; method.&lt;/li&gt;
	&lt;li&gt;Create an anonymous Actor using one of the &amp;#8216;actor&amp;#8217; methods.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here is a little example before we dive into a more interesting one.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
class MyActor extends Actor {
  def receive = {
    case &quot;test&quot; =&amp;gt; println(&quot;received test&quot;)
    case _ =&amp;gt;      println(&quot;received unknown message&quot;)
  }
}

val myActor = new MyActor
myActor.start
&lt;/pre&gt;
&lt;p&gt;Here is the same Actor with the anonymous syntax. Anonymous Actors are implicitly started:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
val myActor = actor { 
  case &quot;test&quot; =&amp;gt; println(&quot;received test&quot;)
  case _ =&amp;gt;      println(&quot;received unknown message&quot;)
}
&lt;/pre&gt;
&lt;p&gt;Akka Actors are extremely lightweight. Each Actor consume ~600 bytes, which means that you can create 6.5 million on 4 G &lt;span class=&quot;caps&quot;&gt;RAM&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;Messages are sent using the &amp;#8216;!&amp;#8217; operator:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
myActor ! &quot;test&quot;
&lt;/pre&gt;
&lt;h1&gt;Sample application&lt;/h1&gt;
&lt;p&gt;We will try to write a simple chat/IM system. It is client-server based and uses remote Actors to implement remote clients. Even if it is not likely that you will ever write a chat system I think that it can be a useful exercise since it uses patterns and idioms found in many other use-cases and domains.&lt;/p&gt;
&lt;p&gt;We will use many of the features of Akka along the way. In particular; Actors, fault-tolerance using Actor supervision, remote Actors, Software Transactional Memory (&lt;span class=&quot;caps&quot;&gt;STM&lt;/span&gt;) and persistence.&lt;/p&gt;
&lt;p&gt;But let&amp;#8217;s start by defining the messages that will flow in our system.&lt;/p&gt;
&lt;h1&gt;Creating messages&lt;/h1&gt;
&lt;p&gt;It is very important that all messages that will be sent around in the system are immutable. The Actor model relies on the simple fact that no state is shared between Actors and the only way to guarantee that is to make sure we don&amp;#8217;t pass mutable state around as part of the messages.&lt;/p&gt;
&lt;p&gt;In Scala we have something called &lt;a href=&quot;http://www.scala-lang.org/node/107&quot;&gt;case classes&lt;/a&gt;. These make excellent messages since they are both immutable and great to pattern match on.&lt;/p&gt;
&lt;p&gt;Let&amp;#8217;s now start by creating the messages that will flow in our system.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
/**
 * ChatServer's internal events.
 */
sealed trait Event

case class Login(username: String) extends Event
case class Logout(username: String) extends Event

case class ChatMessage(fromUser: String, message: String) extends Event

case class GetChatLog(fromUser: String) extends Event
case class ChatLog(messages: List[String]) extends Event
&lt;/pre&gt;
&lt;p&gt;As you can see with these messages we can log in and out, send a chat message and ask for and get a reply with all the messages in the chat log so far.&lt;/p&gt;
&lt;h1&gt;Client: Sending messages&lt;/h1&gt;
&lt;p&gt;Our client wraps each message send in a function, making it a bit easier to use. Here we assume that we have a reference to the chat service so we can communicate with it by sending messages. Messages are sent with the &amp;#8216;!&amp;#8217; operator (pronounced &amp;#8220;bang&amp;#8221;). This sends a message of asynchronously and do not wait for a reply.&lt;/p&gt;
&lt;p&gt;Sometimes however, there is a need for sequential logic, sending a message and wait for the reply before doing anything else. In Akka we can achieve that using the &amp;#8216;!!&amp;#8217; (&amp;#8220;bangbang&amp;#8221;) operator. When sending a message with &amp;#8216;!!&amp;#8217; we do not return immediately but wait for a reply using a &lt;a href=&quot;http://en.wikipedia.org/wiki/Futures_and_promises&quot;&gt;Future&lt;/a&gt;. A &amp;#8216;Future&amp;#8217; is a promise that we will get a result later but with the difference from regular method dispatch that the OS thread we are running on is put to sleep while waiting and that we can set a time-out for how long we wait before bailing out, retrying or doing something else. The &amp;#8216;!!&amp;#8217; function returns a &lt;a href=&quot;http://www.codecommit.com/blog/scala/the-option-pattern&quot;&gt;scala.Option&lt;/a&gt; which implements the &lt;a href=&quot;http://en.wikipedia.org/wiki/Null_Object_pattern&quot;&gt;Null Object pattern&lt;/a&gt;. It has two subclasses; &amp;#8216;None&amp;#8217; which means no result and &amp;#8216;Some(value)&amp;#8217; which means that we got a reply. The &amp;#8216;Option&amp;#8217; class has a lot of great methods to work with the case of not getting a defined result. F.e. as you can see below we are using the &amp;#8216;getOrElse&amp;#8217; method which will try to return the result and if there is no result defined invoke the &amp;#8220;&amp;#8230;OrElse&amp;#8221; statement.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
/**
 * Chat client.
 */
class ChatClient(val name: String) { 
  import Actor.Sender.Self
  def login =                 ChatService ! Login(name) 
  def logout =                ChatService ! Logout(name)  
  def post(message: String) = ChatService ! ChatMessage(name, name + &quot;: &quot; + message)  
  def chatLog: ChatLog = {
    val option = ChatService !! (GetChatLog(name), 1000) // timeout 1000 ms
    option.getOrElse(throw new Exception(&quot;Couldn't get the chat log&quot;))	
  }
}
&lt;/pre&gt;
&lt;h1&gt;Session: Receiving messages&lt;/h1&gt;
&lt;p&gt;Now we are done with the client side and let&amp;#8217;s dig into the server code. We start by creating a user session. The session is an Actor and is defined by extending the &amp;#8216;Actor&amp;#8217; trait. This trait has one abstract method that we have to define; &amp;#8216;receive&amp;#8217; which implements the message handler for the Actor.&lt;/p&gt;
&lt;p&gt;In our example the session has state in the form of a &amp;#8216;List&amp;#8217; with all the messages sent by the user during the session. In takes two parameters in its constructor; the user name and a reference to an Actor implementing the persistent message storage. For both of the messages it responds to, &amp;#8216;ChatMessage&amp;#8217; and &amp;#8216;GetChatLog&amp;#8217;, it passes them on to the storage Actor.&lt;/p&gt;
&lt;p&gt;If you look closely (in the code below) you will see that when passing on the &amp;#8216;GetChatLog&amp;#8217; message we are not using &amp;#8216;!&amp;#8217; but &amp;#8216;forward&amp;#8217;. This is similar to &amp;#8216;!&amp;#8217; but with the important difference that it passes the original sender reference, in this case to the storage Actor. This means that the storage can use this reference to reply to the original sender (our client) directly.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
/**
 * Internal chat client session.
 */
class Session(user: String, storage: Actor) extends Actor {
  private val loginTime = System.currentTimeMillis
  private var userLog: List[String] = Nil

  log.info(&quot;New session for user [%s] has been created at [%s]&quot;, user, loginTime)

  def receive = {
    case event: ChatMessage =&amp;gt; 
      userLog ::= event.message
      storage ! event

    case event: GetChatLog =&amp;gt; 
      storage forward event
  }
}
&lt;/pre&gt;
&lt;h1&gt;Let it crash: Implementing fault-tolerance&lt;/h1&gt;
&lt;p&gt;Akka&amp;#8217;s &lt;a href=&quot;http://doc.akkasource.org/fault-management&quot;&gt;approach to fault-tolerance&lt;/a&gt;; the &amp;#8220;let it crash&amp;#8221; model, is implemented by linking Actors. It is very different to what Java and most non-concurrency oriented languages/frameworks have adopted. It’s a way of dealing with failure that is designed for concurrent and distributed systems.&lt;/p&gt;
&lt;p&gt;If we look at concurrency first. Now let’s assume we are using non-linked Actors. Throwing an exception in concurrent code, will just simply blow up the thread that currently executes the Actor. There is no way to find out that things went wrong (apart from see the stack trace in the log). There is nothing you can do about it. Here linked Actors provide a clean way of both getting notification of the error so you know what happened, as well as the Actor that crashed, so you can do something about it.&lt;/p&gt;
&lt;p&gt;Linking Actors allow you to create sets of Actors where you can be sure that either:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;All are dead&lt;/li&gt;
	&lt;li&gt;All are alive&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This is very useful when you have hundreds of thousands of concurrent Actors. Some Actors might have implicit dependencies and together implement a service, computation, user session etc. for these being able to group them is very nice.&lt;/p&gt;
&lt;p&gt;Akka encourages non-defensive programming. Don’t try to prevent things from go wrong, because they will, whether you want it or not. Instead; expect failure as a natural state in the life-cycle of your app, crash early and let someone else (that sees the whole picture), deal with it.&lt;/p&gt;
&lt;p&gt;Now let’s look at distributed Actors. As you probably know, you can’t build a fault-tolerant system with just one single node, but you need at least two. Also, you (usually) need to know if one node is down and/or the service you are talking to on the other node is down. Here Actor supervision/linking is a critical tool for not only monitoring the health of remote services, but to actually manage the service, do something about the problem if the Actor or node is down. This could be restarting him on the same node or on another node.&lt;/p&gt;
&lt;p&gt;To sum things up, it is a very different way of thinking but a way that is very useful (if not critical) to building fault-tolerant highly concurrent and distributed applications.&lt;/p&gt;
&lt;h1&gt;Supervisor hierarchies&lt;/h1&gt;
&lt;p&gt;A supervisor is a regular Actor that is responsible for starting, stopping and monitoring its child Actors. The basic idea of a supervisor is that it should keep its child Actors alive by restarting them when necessary. This makes for a completely different view on how to write fault-tolerant servers. Instead of trying all things possible to prevent an error from happening, this approach embraces failure. It shifts the view to look at errors as something natural and something that will happen and instead of trying to prevent it; embrace it. Just &amp;#8220;let it crash&amp;#8221; and reset the service to a stable state through restart.&lt;/p&gt;
&lt;p&gt;Akka has two different restart strategies; All-For-One and One-For-One.&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;OneForOne: Restart only the component that has crashed.&lt;/li&gt;
	&lt;li&gt;AllForOne: Restart all the components that the supervisor is managing, including the one that have crashed.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The latter strategy should be used when you have a certain set of components that are coupled in some way that if one is crashing they all need to be reset to a stable state before continuing.&lt;/p&gt;
&lt;h1&gt;Chat server: Supervision, Traits and more&lt;/h1&gt;
&lt;p&gt;There are two ways you can define an Actor to be a supervisor; declaratively and dynamically. In this example we use the dynamic approach. There are two things we have to do:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Define the fault handler by setting the &amp;#8216;faultHandler&amp;#8217; member field to the strategy we want.&lt;/li&gt;
	&lt;li&gt;Define the exceptions we want to &amp;#8220;trap&amp;#8221;, e.g. which exceptions should be handled according to the fault handling strategy we have defined. This in done by setting the &amp;#8216;trapExit&amp;#8217; member field to a &amp;#8216;List&amp;#8217; with all exceptions we want to trap.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The last thing we have to do to supervise Actors (in our example the storage Actor) is to &amp;#8216;link&amp;#8217; the Actor. Invoking &amp;#8216;link(actor)&amp;#8217; will create a link between the Actor passed as argument into &amp;#8216;link&amp;#8217; and ourselves. This means that we will now get a notification if the linked Actor is crashing and if the cause of the crash, the exception, matches one of the exceptions in our &amp;#8216;trapExit&amp;#8217; list then the crashed Actor is restarted according the the fault handling strategy defined in our &amp;#8216;faultHandler&amp;#8217;. We also have the &amp;#8216;unlink(actor)&amp;#8217; function which disconnects the linked Actor from the supervisor.&lt;/p&gt;
&lt;p&gt;In our example we are using a method called &amp;#8216;startLink(actor)&amp;#8217; which starts the Actor and links him in an atomic operation. The linking and unlinking is done in &amp;#8216;init&amp;#8217; and &amp;#8216;shutdown&amp;#8217; callback methods which are invoked by the runtime when the Actor is started and shut down (shutting down is done by invoking &amp;#8216;actor.stop&amp;#8217;). In these methods we initialize our Actor, by starting and linking the storage Actor and clean up after ourselves by shutting down all the user session Actors and the storage Actor.&lt;/p&gt;
&lt;p&gt;That is it. Now we have implemented the supervising part of the fault-tolerance for the storage Actor. But before we dive into the &amp;#8216;ChatServer&amp;#8217; code there are some more things worth mentioning about its implementation.&lt;/p&gt;
&lt;p&gt;It defines an abstract member field holding the &amp;#8216;ChatStorage&amp;#8217; implementation the server wants to use. We do not define that in the &amp;#8216;ChatServer&amp;#8217; directly since we want to decouple it from the actual storage implementation.&lt;/p&gt;
&lt;p&gt;The &amp;#8216;ChatServer&amp;#8217; is a &amp;#8216;trait&amp;#8217;, which is Scala&amp;#8217;s version of mixins. A mixin can be seen as an interface with an implementation and is a very powerful tool in Object-Oriented design that makes it possible to design the system into small, reusable, highly cohesive, loosely coupled parts that can be composed into larger object and components structures.&lt;/p&gt;
&lt;p&gt;I&amp;#8217;ll try to show you how we can make use Scala&amp;#8217;s mixins to decouple the Actor implementation from the business logic of managing the user sessions, routing the chat messages and storing them in the persistent storage. Each of these separate parts of the server logic will be represented by its own trait; giving us four different isolated mixins; &amp;#8216;Actor&amp;#8217;, &amp;#8216;SessionManagement&amp;#8217;, &amp;#8216;ChatManagement&amp;#8217; and &amp;#8216;ChatStorageFactory&amp;#8217; This will give us as loosely coupled system with high cohesion and reusability. At the end of the article I&amp;#8217;ll show you how you can compose these mixins into a the complete runtime component we like.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
/**
 * Chat server. Manages sessions and redirects all 
 * other messages to the Session for the client.
 */
trait ChatServer extends Actor {
  faultHandler = Some(OneForOneStrategy(5, 5000))
  trapExit = List(classOf[Exception])

  val storage: ChatStorage

  log.info(&quot;Chat service is starting up...&quot;)

  // actor message handler
  def receive = sessionManagement orElse chatManagement

  // abstract methods to be defined somewhere else
  protected def chatManagement: PartialFunction[Any, Unit]
  protected def sessionManagement: PartialFunction[Any, Unit]   
  protected def shutdownSessions: Unit

  override def init = startLink(storage)

  override def shutdown = { 
    log.info(&quot;Chat server is shutting down...&quot;)
    shutdownSessions
    unlink(storage)
    storage.stop
  }
}
&lt;/pre&gt;
&lt;p&gt;If you look at the &amp;#8216;receive&amp;#8217; message handler function you can see that we have defined it but instead of adding our logic there we are delegating to two different functions; &amp;#8216;sessionManagement&amp;#8217; and &amp;#8216;chatManagement&amp;#8217;, chaining them with &amp;#8216;orElse&amp;#8217;. These two functions are defined as abstract in our &amp;#8216;ChatServer&amp;#8217; which means that they have to be provided by some another mixin or class when we instantiate our &amp;#8216;ChatServer&amp;#8217;. Naturally we will put the &amp;#8216;sessionManagement&amp;#8217; implementation in the &amp;#8216;SessionManagement&amp;#8217; trait and the &amp;#8216;chatManagement&amp;#8217; implementation in the &amp;#8216;ChatManagement&amp;#8217; trait. First let&amp;#8217;s create the &amp;#8216;SessionManagement&amp;#8217; trait.&lt;/p&gt;
&lt;p&gt;Chaining partial functions like this is a great way of composing functionality in Actors. You can for example put define one default message handle handling generic messages in the base Actor and then let deriving Actors extend that functionality by defining additional message handlers. There is a section on how that is done &lt;a href=&quot;http://doc.akkasource.org/actors&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h1&gt;Session management&lt;/h1&gt;
&lt;p&gt;The session management is defined in the &amp;#8216;SessionManagement&amp;#8217; trait in which we implement the two abstract methods in the &amp;#8216;ChatServer&amp;#8217;; &amp;#8216;sessionManagement&amp;#8217; and &amp;#8216;shutdownSessions&amp;#8217;.&lt;/p&gt;
&lt;p&gt;The &amp;#8216;SessionManagement&amp;#8217; trait holds a &amp;#8216;HashMap&amp;#8217; with all the session Actors mapped by user name as well as a reference to the storage (to be able to pass it in to each newly created &amp;#8216;Session&amp;#8217;).&lt;/p&gt;
&lt;p&gt;The &amp;#8216;sessionManagement&amp;#8217; function performs session management by responding to the &amp;#8216;Login&amp;#8217; and &amp;#8216;Logout&amp;#8217; messages. For each &amp;#8216;Login&amp;#8217; message it creates a new &amp;#8216;Session&amp;#8217; Actor, starts it and puts it in the &amp;#8216;sessions&amp;#8217; Map and for each &amp;#8216;Logout&amp;#8217; message it does the opposite; shuts down the user&amp;#8217;s session and removes it from the &amp;#8216;sessions&amp;#8217; Map.&lt;/p&gt;
&lt;p&gt;The &amp;#8216;shutdownSessions&amp;#8217; function simply shuts all the sessions Actors down. That completes the user session management.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
/**
 * Implements user session management.
 * &amp;lt;p/&amp;gt;
 * Uses self-type annotation 'this: Actor =&amp;gt;'
 * to declare that it needs to be mixed in with an Actor.
 */
trait SessionManagement { this: Actor =&amp;gt; 

  val storage: ChatStorage // needs someone to provide the ChatStorage
  val sessions = new HashMap[String, Actor]

  protected def sessionManagement: PartialFunction[Any, Unit] = {
    case Login(username) =&amp;gt; 
      log.info(&quot;User [%s] has logged in&quot;, username)
      val session = new Session(username, storage)
      session.start
      sessions += (username -&amp;gt; session)

    case Logout(username) =&amp;gt;        
      log.info(&quot;User [%s] has logged out&quot;, username)
      val session = sessions(username)
      session.stop
      sessions -= username 
  }  

  protected def shutdownSessions = 
    sessions.foreach { case (_, session) =&amp;gt; session.stop }  
}
&lt;/pre&gt;
&lt;h1&gt;Chat message management&lt;/h1&gt;
&lt;p&gt;Chat message management is implemented by the &amp;#8216;ChatManagement&amp;#8217; trait. It has an abstract &amp;#8216;HashMap&amp;#8217; session member field with all the sessions. Since it is abstract it needs to be mixed in with someone that can provide this reference. If this dependency is not resolved when composing the final component, you will get a compilation error.&lt;/p&gt;
&lt;p&gt;It implements the &amp;#8216;chatManagement&amp;#8217; function which responds to two different messages; &amp;#8216;ChatMessage&amp;#8217; and &amp;#8216;GetChatLog&amp;#8217;. It simply gets the session for the user (the sender of the message) and routes the message to this session. Here we also use the &amp;#8216;forward&amp;#8217; function to make sure the original sender reference is passed along to allow the end receiver to reply back directly.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
/**
 * Implements chat management, e.g. chat message dispatch.
 * &amp;lt;p/&amp;gt;
 * Uses self-type annotation 'this: Actor =&amp;gt;'
 * to declare that it needs to be mixed in with an Actor.
 */
trait ChatManagement { this: Actor =&amp;gt;
  val sessions: HashMap[String, Actor] // someone needs to provide the Session map

  protected def chatManagement: PartialFunction[Any, Unit] = {
    case msg @ ChatMessage(from, _) =&amp;gt; sessions(from) ! msg
    case msg @ GetChatLog(from) =&amp;gt;     sessions(from) forward msg
  }
}
&lt;/pre&gt;
&lt;p&gt;Using an Actor as a message broker, as in this example, is a very common pattern with many variations; load-balancing, master/worker, map/reduce, replication, logging etc. It becomes even more useful with remote Actors when we can use it to route messages to different nodes.&lt;/p&gt;
&lt;h1&gt;&lt;span class=&quot;caps&quot;&gt;STM&lt;/span&gt; and Transactors&lt;/h1&gt;
&lt;p&gt;Actors are excellent for solving problems where you have many independent processes that can work in isolation and only interact with other Actors through message passing. This model fits many problems. But the Actor model is unfortunately a terrible model for implementing truly shared state. E.g. when you need to have consensus and a stable view of state across many components. The classic example is the bank account where clients can deposit and withdraw, in which each operation needs to be atomic. For detailed discussion on the topic see this &lt;a href=&quot;http://www.slideshare.net/jboner/state-youre-doing-it-wrong-javaone-2009&quot;&gt;presentation&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://en.wikipedia.org/wiki/Software_transactional_memory&quot;&gt;Software Transactional Memory&lt;/a&gt; (&lt;span class=&quot;caps&quot;&gt;STM&lt;/span&gt;) on the other hand is excellent for problems where you need consensus and a stable view of the state by providing compositional transactional shared state. Some of the really nice traits of &lt;span class=&quot;caps&quot;&gt;STM&lt;/span&gt; are that transactions compose and that it raises the abstraction level from lock-based concurrency.&lt;/p&gt;
&lt;p&gt;Akka has a &lt;a href=&quot;http://doc.akkasource.org/stm&quot;&gt;&lt;span class=&quot;caps&quot;&gt;STM&lt;/span&gt; implementation&lt;/a&gt; that is based on the same ideas as found in the &lt;a href=&quot;http://clojure.org/&quot;&gt;Clojure language&lt;/a&gt;; Managed References working with immutable data.&lt;/p&gt;
&lt;p&gt;Akka allows you to combine Actors and &lt;span class=&quot;caps&quot;&gt;STM&lt;/span&gt; into what we call &lt;a href=&quot;http://doc.akkasource.org/transactors&quot;&gt;Transactors&lt;/a&gt; (short for Transactional Actors), these allow you to optionally combine Actors and &lt;span class=&quot;caps&quot;&gt;STM&lt;/span&gt; provides &lt;span class=&quot;caps&quot;&gt;IMHO&lt;/span&gt; the best of the Actor model (simple concurrency and asynchronous event-based programming) and &lt;span class=&quot;caps&quot;&gt;STM&lt;/span&gt; (compositional transactional shared state) by providing transactional, compositional, asynchronous, event-based message flows. You don&amp;#8217;t need Transactors all the time but when you do need them then you &lt;strong&gt;really need&lt;/strong&gt; them.&lt;/p&gt;
&lt;p&gt;Akka currently provides three different transactional abstractions; &amp;#8216;Map&amp;#8217;, &amp;#8216;Vector&amp;#8217; and &amp;#8216;Ref&amp;#8217;. They can be shared between multiple Actors and they are managed by the &lt;span class=&quot;caps&quot;&gt;STM&lt;/span&gt;. You are not allowed to modify them outside a transaction, if you do so, an exception will be thrown.&lt;/p&gt;
&lt;p&gt;What you get is transactional memory in which multiple Actors are allowed to read and write to the same memory concurrently and if there is a clash between two transactions then both of them are aborted and retried. Aborting a transaction means that the memory is rolled back to the state it were in when the transaction was started.&lt;/p&gt;
&lt;p&gt;In database terms &lt;span class=&quot;caps&quot;&gt;STM&lt;/span&gt; gives you &amp;#8216;&lt;span class=&quot;caps&quot;&gt;ACI&lt;/span&gt;&amp;#8217; semantics; &amp;#8216;Atomicity&amp;#8217;, &amp;#8216;Consistency&amp;#8217; and &amp;#8216;Isolation&amp;#8217;. The &amp;#8216;D&amp;#8217; in &amp;#8216;&lt;span class=&quot;caps&quot;&gt;ACID&lt;/span&gt;&amp;#8217;; &amp;#8216;Durability&amp;#8217;, you can&amp;#8217;t get with an &lt;span class=&quot;caps&quot;&gt;STM&lt;/span&gt; since it is in memory. This however is addressed by the persistence module in Akka.&lt;/p&gt;
&lt;h1&gt;Persistence: Storing the chat log&lt;/h1&gt;
&lt;p&gt;Akka provides the possibility of taking the transactional data structures we discussed above and making them persistent. It is an extension to the &lt;span class=&quot;caps&quot;&gt;STM&lt;/span&gt; which guarantees that it has the same semantics.&lt;/p&gt;
&lt;p&gt;The &lt;a href=&quot;http://doc.akkasource.org/persistence&quot;&gt;persistence module&lt;/a&gt; has pluggable storage back-ends. At the time of the writing it has three different storage back-ends:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;&lt;a href=&quot;http://wiki.apache.org/cassandra/&quot;&gt;Cassandra&lt;/a&gt; &amp;#8211; A distributed structured storage database.&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://www.mongodb.org/display/DOCS/Home&quot;&gt;MongoDB&lt;/a&gt; &amp;#8211; A high performance schema-free, document oriented data store with &lt;span class=&quot;caps&quot;&gt;SQL&lt;/span&gt; like query facilities.&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://code.google.com/p/redis/&quot;&gt;Redis&lt;/a&gt; &amp;#8211; An advanced key-value store, also called a data structure server, with lists, ordered sets etc.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;They all implement persistent &amp;#8216;Map&amp;#8217;, &amp;#8216;Vector&amp;#8217; and &amp;#8216;Ref&amp;#8217;. Which can be created and retrieved by id through one of the storage modules.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
val map =    RedisStorage.newMap(id)
val vector = CassandraStorage.newVector(id)
val ref =    MongoStorage.newRef(id)
&lt;/pre&gt;
&lt;h1&gt;Chat storage: Backed by Redis&lt;/h1&gt;
&lt;p&gt;Now let&amp;#8217;s implement the persistent storage. We start by creating a &amp;#8216;ChatStorage&amp;#8217; trait allowing us to have multiple different storage backend. For example one in-memory and one persistent.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
/**
 * Abstraction of chat storage holding the chat log.
 */
trait ChatStorage extends Actor
&lt;/pre&gt;
&lt;p&gt;Let&amp;#8217;s use Redis to implementation the persistent storage. Redis is an excellent storage backend, blazingly fast with a rich data model.&lt;/p&gt;
&lt;p&gt;Our &amp;#8216;RedisChatStorage&amp;#8217; extends the &amp;#8216;ChatStorage&amp;#8217; trait. The only state it holds is the &amp;#8216;chatLog&amp;#8217; which is a &amp;#8216;Vector&amp;#8217; managed by Redis. We give it an explicit id (the String &amp;#8220;akka.chat.log&amp;#8221;) to be able to retrieve the same vector across remote nodes and/or through server restarts.&lt;/p&gt;
&lt;p&gt;It responds to two different messages; &amp;#8216;ChatMessage&amp;#8217; and &amp;#8216;GetChatLog&amp;#8217;. The &amp;#8216;ChatMessage&amp;#8217; message handler takes the &amp;#8216;message&amp;#8217; attribute and appends it to the &amp;#8216;chatLog&amp;#8217; vector. Here you can see  that we are using the &amp;#8216;atomic { &amp;#8230; }&amp;#8217; block to run the vector operation in a transaction. Redis works with binary data so we need to convert the message into a binary representation. Since we are using Strings we just have to invoke &amp;#8216;message.getBytes(&amp;#8220;&lt;span class=&quot;caps&quot;&gt;UTF&lt;/span&gt;-8&amp;#8221;)&amp;#8217;, but if we would have had a richer message that we wanted to persist then we would have had to use one of the Akka&amp;#8217;s serialization traits or serializers. You can read more about that &lt;a href=&quot;http://doc.akkasource.org/serialization&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The &amp;#8216;GetChatLog&amp;#8217; message handler retrieves all the messages in the chat log storage inside an atomic block, iterates over them using the &amp;#8216;map&amp;#8217; combinator transforming them from &amp;#8216;Array[Byte] to &amp;#8217;String&amp;#8217;. Then it invokes the &amp;#8216;reply(message)&amp;#8217; function that will send the chat log to the original sender; the &amp;#8216;ChatClient&amp;#8217;.&lt;/p&gt;
&lt;p&gt;You might rememeber that the &amp;#8216;ChatServer&amp;#8217; was supervising the &amp;#8216;ChatStorage&amp;#8217; actor. When we discussed that we showed you the supervising Actor&amp;#8217;s view. Now is the time for the supervised Actor&amp;#8217;s side of things. First, a supervised Actor need to define a life-cycle in which it declares if it should be seen as a:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;&amp;#8216;Permanent&amp;#8217;: which means that the actor will always be restarted.&lt;/li&gt;
	&lt;li&gt;&amp;#8216;Temporary&amp;#8217;: which means that the actor will not be restarted, but it will be shut down through the regular shutdown process so the &amp;#8216;shutdown&amp;#8217; callback function will called.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We define the &amp;#8216;RedisChatStorage&amp;#8217; as &amp;#8216;Permanent&amp;#8217; by setting the &amp;#8216;lifeCycle&amp;#8217; member field to &amp;#8216;Some(LifeCycle(Permanent))&amp;#8217;.&lt;/p&gt;
&lt;p&gt;The idea with this crash early style of designing your system is that the services should just crash and then they should be restarted and reset into a stable state and continue from there. The definition of &amp;#8220;stable state&amp;#8221; is domain specific and up to the application developer to define. Akka provides two callback functions; &amp;#8216;preRestart&amp;#8217; and &amp;#8216;postRestart&amp;#8217; that are called right &lt;strong&gt;before&lt;/strong&gt; and right &lt;strong&gt;after&lt;/strong&gt; the Actor is restarted. Both of these functions take a &amp;#8216;Throwable&amp;#8217;, the reason for the crash, as argument. In our case we just need to implement the &amp;#8216;postRestart&amp;#8217; hook and there re-initialize the &amp;#8216;chatLog&amp;#8217; member field with a fresh persistent &amp;#8216;Vector&amp;#8217; from Redis.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
/**
 * Redis-backed chat storage implementation.
 */
class RedisChatStorage extends ChatStorage {
  lifeCycle = Some(LifeCycle(Permanent))    

  private var chatLog = RedisStorage.getVector(&quot;akka.chat.log&quot;)

  log.info(&quot;Redis-based chat storage is starting up...&quot;)

  def receive = {
    case msg @ ChatMessage(from, message) =&amp;gt; 
      log.debug(&quot;New chat message [%s]&quot;, message)
      atomic { 
        chatLog + message.getBytes(&quot;UTF-8&quot;)
      }

    case GetChatLog(_) =&amp;gt; 
      val messageList = atomic {
       chatLog.map(bytes =&amp;gt; new String(bytes, &quot;UTF-8&quot;)).toList
      }
      reply(ChatLog(messageList))
  }

  override def postRestart(reason: Throwable) = 
    chatLog = RedisStorage.getVector(&quot;akka.chat.log&quot;)  
}
&lt;/pre&gt;
&lt;p&gt;The last thing we need to do in terms of persistence is to create a &amp;#8216;RedisChatStorageFactory&amp;#8217; that will take care of instantiating and resolving the &amp;#8216;val storage: ChatStorage&amp;#8217; field in the &amp;#8216;ChatServer&amp;#8217; with a concrete implementation of our persistence Actor.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
/**
 * Creates and a RedisChatStorage.
 */
trait RedisChatStorageFactory {
  val storage: ChatStorage = new RedisChatStorage
}
&lt;/pre&gt;
&lt;h1&gt;Composing the full Chat Service&lt;/h1&gt;
&lt;p&gt;We have now created the full functionality for the chat server, all nicely decoupled into isolated and well-defined traits. Now let&amp;#8217;s bring all these traits together and compose the complete concrete &amp;#8216;ChatService&amp;#8217;.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
/**
 * Object encapsulating the full Chat Service.
 */
object ChatService extends 
  ChatServer with 
  SessionManagement with 
  ChatManagement with 
  RedisChatStorageFactory
&lt;/pre&gt;
&lt;h1&gt;Making the ChatService remote&lt;/h1&gt;
&lt;p&gt;Now that we have the &amp;#8216;ChatService&amp;#8217; object how do we make it into a remote service that we can use from different nodes?&lt;/p&gt;
&lt;p&gt;It is very simple. We only need to do two things. First we need to start up a remote server to run the &amp;#8216;ChatService&amp;#8217;. Then for each client that wants to use the &amp;#8216;ChatService&amp;#8217; we just need to invoke &amp;#8216;ChatService.makeRemote&amp;#8217; to get a handle to the remote &amp;#8216;ChatService&amp;#8217;.&lt;/p&gt;
&lt;p&gt;Starting the first step. We have two options on how we can start up a remote server. Either start up the &amp;#8216;RemoteNode&amp;#8217; in some part of the code that runs on the machine you want to run the server on (can just be a simple class with a &amp;#8216;main&amp;#8217; method).&lt;/p&gt;
&lt;p&gt;We start the &amp;#8216;RemoteNode&amp;#8217; by invoking &amp;#8216;start&amp;#8217; and passing in the host name and port.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
RemoteNode.start(&quot;darkstar&quot;, 9999)
&lt;/pre&gt;
&lt;p&gt;You can also choose to use the version of &amp;#8216;start&amp;#8217; that takes a &amp;#8216;ClassLoader&amp;#8217; as argument if you want to be explicit on through which class loader you want to load the class of the Actor that you want to run as remote service.&lt;/p&gt;
&lt;p&gt;The second option is to put your application in a &lt;span class=&quot;caps&quot;&gt;JAR&lt;/span&gt; file and drop it into the &amp;#8216;AKKA_HOME/deploy&amp;#8217; directory and then start up the Akka microkernel. This will deploy your application and start the &amp;#8216;RemoteNode&amp;#8217; for you. Then you use the &amp;#8216;AKKA_HOME/config/akka.conf&amp;#8217; configuration file to configure the remote server (among many other things). The microkernel is started up like this:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;terminal&quot;&gt;
export AKKA_HOME=...
cd $AKKA_HOME
java -jar $AKKA_HOME/dist/akka-0.6.jar
&lt;/pre&gt;
&lt;p&gt;That was the server part. The client part is just as simple. We only need to tell the runtime system that we want to use the &amp;#8216;ChatService&amp;#8217; as a remote Actor by invoking the &amp;#8216;makeRemote(hostname, port)&amp;#8217; function on it. This will instantiate the Actor on the remote host and turn the local Actor instance into a proxy or handle through which we can use the remote Actor transparently with the exact same semantics as if it was a regular local Actor.&lt;/p&gt;
&lt;p&gt;That&amp;#8217;s it. Now let&amp;#8217;s run a sample client session.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
ChatService.makeRemote(&quot;darkstar&quot;, 9999)
ChatService.start
&lt;/pre&gt;
&lt;p&gt;That&amp;#8217;s it. Were done. Now we have a, very simple, but scalable, fault-tolerant, event-driven, persistent chat server that can without problem serve a million concurrent users on a regular workstation.&lt;/p&gt;
&lt;p&gt;Let&amp;#8217;s use it.&lt;/p&gt;
&lt;h1&gt;Sample client chat session&lt;/h1&gt;
&lt;p&gt;Now let&amp;#8217;s create a simple test runner that logs in posts some messages and logs out.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
import se.scalablesolutions.akka.sample.chat._

/**
 * Test runner emulating a chat session.
 */
object Runner {
  // create a handle to the remote ChatService 
  ChatService.makeRemote(&quot;localhost&quot;, 9999)
  ChatService.start

  def run = {
    val client = new ChatClient(&quot;jonas&quot;)

    client.login

    client.post(&quot;Hi there&quot;)
    println(&quot;CHAT LOG:\n\t&quot; + client.chatLog.log.mkString(&quot;\n\t&quot;))

    client.post(&quot;Hi again&quot;)
    println(&quot;CHAT LOG:\n\t&quot; + client.chatLog.log.mkString(&quot;\n\t&quot;))

    client.logout
  }
}
&lt;/pre&gt;
&lt;h1&gt;Sample code&lt;/h1&gt;
&lt;p&gt;All this code is available as part of the Akka distribution. It resides in the &amp;#8216;./akka-samples/akka-sample-chat&amp;#8217; module and have a &amp;#8216;&lt;span class=&quot;caps&quot;&gt;README&lt;/span&gt;&amp;#8217; file explaining how to run it as well as a Maven &amp;#8216;pom.xml&amp;#8217; build file so it is easy to build, run, hack, rebuild, run etc. You can also just read the next section for instructions on how to run it.&lt;/p&gt;
&lt;p&gt;Or if you rather browse it &lt;a href=&quot;http://github.com/jboner/akka/tree/master/akka-samples-chat/&quot;&gt;online&lt;/a&gt;.&lt;/p&gt;
&lt;h1&gt;Run it&lt;/h1&gt;
&lt;p&gt;First we need to start up Redis.&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;Download Redis from &lt;a href=&quot;http://code.google.com/p/redis/downloads/list&quot;&gt;here&lt;/a&gt;.&lt;/li&gt;
	&lt;li&gt;Step into the distribution.&lt;/li&gt;
	&lt;li&gt;Build: &amp;#8216;make install&amp;#8217;.&lt;/li&gt;
	&lt;li&gt;Run: &amp;#8216;./redis-server&amp;#8217;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;For details on how to set up Redis server have a look &lt;a href=&quot;http://code.google.com/p/redis/wiki/QuickStart&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Download and build Akka&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;Download Akka from &lt;a href=&quot;http://github.com/jboner/akka/downloads&quot;&gt;http://github.com/jboner/akka/downloads&lt;/a&gt;.&lt;/li&gt;
	&lt;li&gt;Set &amp;#8216;AKKA_HOME&amp;#8217; environment variable to the root of the Akka distribution.&lt;/li&gt;
	&lt;li&gt;Open up a shell and step into the Akka distribution root folder.&lt;/li&gt;
	&lt;li&gt;Build Akka by invoking &amp;#8216;mvn install -Dmaven.test.skip=true&amp;#8217;. This will also bulid the sample application and deploy it to the &amp;#8216;$AKKA_HOME/deploy&amp;#8217; directory.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Run the microkernel&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;terminal&quot;&gt;
export AKKA_HOME=...
cd $AKKA_HOME
java -jar ./dist/akka-0.6.jar
&lt;/pre&gt;
&lt;p&gt;Run a sample chat session&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;Now start up a new shell and go down into the &amp;#8216;./akka-samples/akka-sample-chat&amp;#8217; directory.&lt;/li&gt;
	&lt;li&gt;Invoke &amp;#8216;mvn scala:console -o&amp;#8217;. This will give you a Scala &lt;span class=&quot;caps&quot;&gt;REPL&lt;/span&gt; (interpreter) with the chat application and all its dependency JARs on the classpath.&lt;/li&gt;
	&lt;li&gt;Simply paste in the whole code block with the &amp;#8216;Runner&amp;#8217; object above and invoke &amp;#8216;Runner.run&amp;#8217;. This run a simulated client session that will connect to the running server in the microkernel.&lt;/li&gt;
	&lt;li&gt;Invoke &amp;#8216;Runner.run&amp;#8217; again and again&amp;#8230;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Now you could test client reconnect by killing the running microkernel and start it up again. See the client reconnect take place in the &lt;span class=&quot;caps&quot;&gt;REPL&lt;/span&gt; shell.&lt;/p&gt;
&lt;p&gt;That&amp;#8217;s it. Have fun.&lt;/p&gt;
&lt;h1&gt;Onward&lt;/h1&gt;
&lt;p&gt;There is much much more to Akka than what we have covered in this article. For example &lt;a href=&quot;http://doc.akkasource.org/active-objects&quot;&gt;Active Objects&lt;/a&gt;, &lt;a href=&quot;http://doc.akkasource.org/cluster-membership&quot;&gt;Cluster Membership &lt;span class=&quot;caps&quot;&gt;API&lt;/span&gt;&lt;/a&gt;, a &lt;a href=&quot;http://doc.akkasource.org/comet&quot;&gt;Comet module&lt;/a&gt;, &lt;a href=&quot;http://doc.akkasource.org/rest&quot;&gt;&lt;span class=&quot;caps&quot;&gt;REST&lt;/span&gt; (&lt;span class=&quot;caps&quot;&gt;JAX&lt;/span&gt;-RS) integration&lt;/a&gt;, a &lt;a href=&quot;http://doc.akkasource.org/security&quot;&gt;Security module&lt;/a&gt;, &lt;a href=&quot;http://doc.akkasource.org/amqp&quot;&gt;&lt;span class=&quot;caps&quot;&gt;AMQP&lt;/span&gt; integration&lt;/a&gt;, &lt;a href=&quot;http://doc.akkasource.org/spring-integration&quot;&gt;Spring integration&lt;/a&gt;, &lt;a href=&quot;http://doc.akkasource.org/guice-integration&quot;&gt;Google Guice integration&lt;/a&gt;, &lt;a href=&quot;http://github.com/jboner/akka/tree/master/akka-samples-lift/&quot;&gt;Lift integration&lt;/a&gt;, a rich &lt;a href=&quot;http://doc.akkasource.org/stm&quot;&gt;Transaction &lt;span class=&quot;caps&quot;&gt;API&lt;/span&gt;&lt;/a&gt;, tons of &lt;a href=&quot;http://doc.akkasource.org/configuration&quot;&gt;configuration possibilities&lt;/a&gt; etc.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Asynchronous Event Sourcing using Actors</title>
   <link href="http://jonasboner.com/2009/02/12/event-sourcing-using-actors.html"/>
   <updated>2009-02-12T00:00:00+01:00</updated>
   <id>http://jonasboner.com/2009/02/12/event-sourcing-using-actors</id>
   <content type="html">&lt;h1&gt;Asynchronous Event Sourcing using Actors&lt;/h1&gt;
&lt;p class=&quot;meta&quot;&gt;12 Feb 2009&lt;/p&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;There has been some discussions lately about Event Sourcing. For example, Greg Young &lt;a href=&quot;http://www.infoq.com/interviews/greg-young-ddd&quot;&gt;recently discussed&lt;/a&gt; how they were using Event Sourcing and explicit state transitions together with Domain-Driven Design (&lt;span class=&quot;caps&quot;&gt;DDD&lt;/span&gt;) to build a highly scalable and loosely coupled system.&lt;/p&gt;
&lt;p&gt;So what is Event Sourcing? Martin Fowler wrote an &lt;a href=&quot;http://martinfowler.com/eaaDev/EventSourcing.html&quot;&gt;excellent article&lt;/a&gt; about some years ago and there is no use repeating it here, so please read (or at least skim) that article before reading further.&lt;/p&gt;
&lt;p&gt;What I will do in this article is to show you how you can implement Event Sourcing using asynchronous message-passing based on actors. Actors are generally an excellent paradigm to implement asynchronous event-based systems and they allow you to easily get explicit state transitions working nicely together with an immutable domain model. This gives a concurrent system that scales very well, with the side-effect/feature of &lt;a href=&quot;http://www.allthingsdistributed.com/2008/12/eventually_consistent.html&quot;&gt;Eventual Consistency&lt;/a&gt;.&lt;/p&gt;
&lt;h1&gt;Domain model&lt;/h1&gt;
&lt;p&gt;I will reuse the example Martin Fowler used in his article but rewrite it using Scala Actors. So without further ado let&amp;#8217;s start hacking. Martin&amp;#8217;s example implements a simple Ship management system.&lt;/p&gt;
&lt;p&gt;First, let&amp;#8217;s define the simplistic domain model; Ship, Port and Country.&lt;/p&gt;
&lt;p&gt;The Ship class is worth discussing a bit. It is an actor, which means that it is an isolated &amp;#8216;lightweight process&amp;#8217; with its own state, which is only accessible and modifiable using messages (in our case, events). The Ship actor responds to four different events; set arrival and departure, query for current port and finally reset the state.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
class Ship(val name: String, val home: Port) extends Actor {

  def act = loop(home)

  private def loop(current: Port) {
    react {
      case ArrivalEvent(time, port, _) =&amp;gt; 
        println(toString + &quot; ARRIVED  at port   &quot; + port + &quot; @ &quot; + time)
        loop(port)

      case DepartureEvent(time, port, _) =&amp;gt; 
        println(toString + &quot; DEPARTED from port &quot; + port  + &quot; @ &quot; + time)
        loop(Port.AT_SEA)

      case Reset =&amp;gt; 
        println(toString + &quot; has been reset&quot;)
        loop(home)

      case CurrentPort =&amp;gt; 
        reply(current)
        loop(current)

      case unknown =&amp;gt; 
        error(&quot;Unknown event: &quot; + unknown)
    }
  }

  override def toString = &quot;Ship(&quot; + name + &quot;)&quot;
}

class Port(val city: String, val country: Country) {
  override def toString = &quot;Port(&quot; + city + &quot;)&quot;  
}
object Port {
  val AT_SEA = new Port(&quot;AT SEA&quot;, Country.AT_SEA)
}

case class Country(val name: String)
object Country {
  val US = new Country(&quot;US&quot;)
  val CANADA = new Country(&quot;CANADA&quot;)
  val AT_SEA = new Country(&quot;AT_SEA&quot;)
}
&lt;/pre&gt;
&lt;p&gt;Note: In this example I have been managing the state in the actors (Ship and EventProcessor) by passing it on in the recursive &amp;#8216;loop&amp;#8217;, using stack-confinement. This is a slick technique but not possible if you need to persist the state in some way, either using something like Terracotta or store it in a database. Then you would have to put the state in private field(s) in the actor, something that will &lt;b&gt;not&lt;/b&gt; affect the correctness or performance.&lt;/p&gt;
&lt;h1&gt;Events&lt;/h1&gt;
&lt;p&gt;Now let&amp;#8217;s define our events, implementing the explicit state transitions DepartureEvent and ArrivalEvent. In Scala these are best defined as &amp;#8216;case classes&amp;#8217; which supports pattern matching and attribute destructing. These two events encapsulate their state transition in the &amp;#8216;process&amp;#8217; method. We also define one event for asking the Ship for its current port and one for resetting its state to its &amp;#8220;home&amp;#8221; port.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
sealed abstract case class Event

abstract case class StateTransitionEvent(val occurred: Date) 
  extends Event {
  val recorded = new Date
  def process: Unit
}

case class DepartureEvent(val time: Date, val port: Port, val ship: Ship) 
  extends StateTransitionEvent(time) {
  override def process = ship ! this
}

case class ArrivalEvent(val time: Date, val port: Port, val ship: Ship) 
  extends StateTransitionEvent(time) {
  override def process = ship ! this
}

case object Reset extends Event

case object CurrentPort extends Event
&lt;/pre&gt;
&lt;h1&gt;Event processor&lt;/h1&gt;
&lt;p&gt;Finally, let&amp;#8217;s define the event processor. This class is an actor which responds to any event that is a subtype of StateTransitionEvent, e.g. either DepartureEvent or ArrivalEvent. It also holds a history list (&amp;#8216;log&amp;#8217;) with all events that it has processed. Something that we will make use of later on.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
class EventProcessor extends Actor {
  def act = loop(Nil)

  private def loop(log: List[StateTransitionEvent]) {
    react {
      case event: StateTransitionEvent =&amp;gt; 
        event.process
        loop(event :: log)

      case unknown =&amp;gt; 
        error(&quot;Unknown event: &quot; + unknown)
    }
  }
}
&lt;/pre&gt;
&lt;h2&gt;Test run 1&lt;/h2&gt;
&lt;p&gt;Now we have the basis for our Ship Management Event Sourcing framework. Let&amp;#8217;s create some tests to drive the thing. Since each event submission is processed asynchronously we have to interleave them with calls to &amp;#8216;Thread.sleep(500)&amp;#8217; in order to see what is going on.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
class ActorBasedEventSourcingTest {

  private var shipKR: Ship = _
  private var portSFO, portLA, portYYV: Port = _
  private var processor: EventProcessor = _

  def setup = {
    processor = new EventProcessor
    processor.start
    
    portSFO = new Port(&quot;San Francisco&quot;, Country.US)
    portLA = new Port(&quot;Los Angeles&quot;, Country.US)
    portYYV = new Port(&quot;Vancouver&quot;, Country.CANADA)

    shipKR = new Ship(&quot;King Roy&quot;, portYYV)
    shipKR.start

    this
  }

  def tearDown = { 
    processor.exit
    this
  }

  def arrivalSetsShipsLocation = {
    println(&quot;\n===&amp;gt; arrivalSetsShipsLocation&quot;)

    processor ! DepartureEvent(new Date(2009, 2, 1), portSFO, shipKR)
    Thread.sleep(500)

    processor ! ArrivalEvent(new Date(2009, 2, 3), portSFO, shipKR)
    Thread.sleep(500)

    assert(portSFO == (shipKR !? CurrentPort))
    this
  }

  def departurePutsShipOutToSea = {
    println(&quot;\n===&amp;gt; departurePutsShipOutToSea&quot;)

    processor ! DepartureEvent(new Date(2009, 2, 4), portLA, shipKR)
    Thread.sleep(500)

    assert(Port.AT_SEA == (shipKR !? CurrentPort))
    this
  }

  def smallTrip = {
    println(&quot;\n===&amp;gt; smallTrip&quot;)

    processor ! ArrivalEvent(new Date(2009, 2, 5), portLA, shipKR)
    Thread.sleep(500)

    processor ! DepartureEvent(new Date(2009, 2, 6), portYYV, shipKR)
    Thread.sleep(500)

    processor ! ArrivalEvent(new Date(2009, 2, 8), portYYV, shipKR)
    Thread.sleep(500)

    processor ! DepartureEvent(new Date(2009, 2, 9), portSFO, shipKR)
    Thread.sleep(500)

    processor ! ArrivalEvent(new Date(2009, 2, 11), portSFO, shipKR)
    Thread.sleep(500)

    assert(portSFO == (shipKR !? CurrentPort))
    this
  }
}

(new ActorBasedEventSourcingTest)
  .setup
  .arrivalSetsShipsLocation
  .departurePutsShipOutToSea
  .smallTrip
  .tearDown
&lt;/pre&gt;
&lt;p&gt;Which gives us the following output:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
===&amp;gt; arrivalSetsShipsLocation
Ship(King Roy) DEPARTED from port Port(San Francisco) @ Mon Mar 01 00:00:00 CET 3909
Ship(King Roy) ARRIVED  at port   Port(San Francisco) @ Wed Mar 03 00:00:00 CET 3909

===&amp;gt; departurePutsShipOutToSea
Ship(King Roy) DEPARTED from port Port(Los Angeles) @ Thu Mar 04 00:00:00 CET 3909

===&amp;gt; smallTrip
Ship(King Roy) ARRIVED  at port   Port(Los Angeles) @ Fri Mar 05 00:00:00 CET 3909
Ship(King Roy) DEPARTED from port Port(Vancouver) @ Sat Mar 06 00:00:00 CET 3909
Ship(King Roy) ARRIVED  at port   Port(Vancouver) @ Mon Mar 08 00:00:00 CET 3909
Ship(King Roy) DEPARTED from port Port(San Francisco) @ Tue Mar 09 00:00:00 CET 3909
Ship(King Roy) ARRIVED  at port   Port(San Francisco) @ Thu Mar 11 00:00:00 CET 3909
&lt;/pre&gt;
&lt;p&gt;Pretty nice.&lt;/p&gt;
&lt;p&gt;But now, let&amp;#8217;s start to take advantage of the event persistence. Let&amp;#8217;s implement event replay.&lt;/p&gt;
&lt;h1&gt;Replay&lt;/h1&gt;
&lt;p&gt;Implementing replay is actually very simple now when we have an event log. First we define a Replay event.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
case object Replay extends Event
&lt;/pre&gt;
&lt;p&gt;Then we need the EventProcessor to respond to this new event by first reversing the order of the event log (since functional lists are concatenated in reverse order) and then for each event invoke &amp;#8216;process&amp;#8217;.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
class EventProcessor extends Actor {
  def act = loop(Nil)

  private def loop(log: List[DomainEvent]) {
    react {
       ...

      case Replay =&amp;gt; 
        log.reverse.foreach(_.process) 
        loop(log)
    }
  }
}
&lt;/pre&gt;
&lt;p&gt;Done deal.&lt;/p&gt;
&lt;h2&gt;Test run 2&lt;/h2&gt;
&lt;p&gt;Let&amp;#8217;s try it out by adding a new test method to our suite. Here we make use of the Reset event which resets the ship to its initial state before replaying all state transitions.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
def resetAndReplayEventLog = {
  println(&quot;\n===&amp;gt; resetAndReplayEventLog&quot;)

  shipKR ! Reset

  processor ! Replay
  Thread.sleep(500)

  assert(portSFO == (shipKR !? CurrentPort))
  this
}

(new ActorBasedEventSourcingTest)
  .setup
  .arrivalSetsShipsLocation
  .departurePutsShipOutToSea
  .smallTrip
  .resetAndReplayEventLog // new test method
  .tearDown
&lt;/pre&gt;
&lt;p&gt;This yields the following output:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
===&amp;gt; arrivalSetsShipsLocation
Ship(King Roy) DEPARTED from port Port(San Francisco) @ Mon Mar 01 00:00:00 CET 3909
Ship(King Roy) ARRIVED  at port   Port(San Francisco) @ Wed Mar 03 00:00:00 CET 3909

===&amp;gt; departurePutsShipOutToSea
Ship(King Roy) DEPARTED from port Port(Los Angeles) @ Thu Mar 04 00:00:00 CET 3909

===&amp;gt; smallTrip
Ship(King Roy) ARRIVED  at port   Port(Los Angeles) @ Fri Mar 05 00:00:00 CET 3909
Ship(King Roy) DEPARTED from port Port(Vancouver) @ Sat Mar 06 00:00:00 CET 3909
Ship(King Roy) ARRIVED  at port   Port(Vancouver) @ Mon Mar 08 00:00:00 CET 3909
Ship(King Roy) DEPARTED from port Port(San Francisco) @ Tue Mar 09 00:00:00 CET 3909
Ship(King Roy) ARRIVED  at port   Port(San Francisco) @ Thu Mar 11 00:00:00 CET 3909

===&amp;gt; resetAndReplayEventLog
Ship(King Roy) has been reset
Ship(King Roy) DEPARTED from port Port(San Francisco) @ Mon Mar 01 00:00:00 CET 3909
Ship(King Roy) ARRIVED  at port   Port(San Francisco) @ Wed Mar 03 00:00:00 CET 3909
Ship(King Roy) DEPARTED from port Port(Los Angeles) @ Thu Mar 04 00:00:00 CET 3909
Ship(King Roy) ARRIVED  at port   Port(Los Angeles) @ Fri Mar 05 00:00:00 CET 3909
Ship(King Roy) DEPARTED from port Port(Vancouver) @ Sat Mar 06 00:00:00 CET 3909
Ship(King Roy) ARRIVED  at port   Port(Vancouver) @ Mon Mar 08 00:00:00 CET 3909
Ship(King Roy) DEPARTED from port Port(San Francisco) @ Tue Mar 09 00:00:00 CET 3909
Ship(King Roy) ARRIVED  at port   Port(San Francisco) @ Thu Mar 11 00:00:00 CET 3909
&lt;/pre&gt;
&lt;h1&gt;Replay up to a specific point in time&lt;/h1&gt;
&lt;p&gt;Finally, (my last example, I promise) let&amp;#8217;s add the possibility of replaying the event log up to a specific date to get a snapshot of the system&amp;#8217;s state at a particular point in time.&lt;/p&gt;
&lt;p&gt;You know the drill by now, first define a new event; ReplayUpTo, holding the date.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
case class ReplayUpTo(date: Date) extends Event
&lt;/pre&gt;
&lt;p&gt;Here the event processor first reverses the log, then it applies a filter to the list which filters out all events that has been created after the date specified and finally run &amp;#8216;process&amp;#8217; on all events in the resulting filtered list.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
class EventProcessor extends Actor {
  def act = loop(Nil)

  private def loop(log: List[DomainEvent]) {
    react {
       ...

      case ReplayUpTo(date) =&amp;gt; 
        log.reverse.filter(_.occurred.getTime &amp;lt;= date.getTime).foreach(_.process) 
        loop(log)
    }
  }
}
&lt;/pre&gt;
&lt;h2&gt;Test run 3&lt;/h2&gt;
&lt;p&gt;So we add a last test method to our suite, one that replays all events created in earlier tests up to the date &amp;#8216;2009/2/4&amp;#8217;.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
def resetAndReplayEventLogUpToDate = {
  println(&quot;\n===&amp;gt; resetAndReplayEventLogUpToDate&quot;)

  shipKR ! Reset

  processor ! ReplayUpTo(new Date(2009, 2, 4))
  Thread.sleep(500)

  assert(Port.AT_SEA == (shipKR !? CurrentPort))
  this
} 

(new EventSourcingWithActorsTest)
  .setup
  .arrivalSetsShipsLocation
  .departurePutsShipOutToSea
  .smallTrip
  .resetAndReplayEventLog
  .resetAndReplayEventLogUpToDate // new test method
  .tearDown
&lt;/pre&gt;
&lt;p&gt;This yield the following output.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
===&amp;gt; arrivalSetsShipsLocation
Ship(King Roy) DEPARTED from port Port(San Francisco) @ Mon Mar 01 00:00:00 CET 3909
Ship(King Roy) ARRIVED  at port   Port(San Francisco) @ Wed Mar 03 00:00:00 CET 3909

===&amp;gt; departurePutsShipOutToSea
Ship(King Roy) DEPARTED from port Port(Los Angeles) @ Thu Mar 04 00:00:00 CET 3909

===&amp;gt; smallTrip
Ship(King Roy) ARRIVED  at port   Port(Los Angeles) @ Fri Mar 05 00:00:00 CET 3909
Ship(King Roy) DEPARTED from port Port(Vancouver) @ Sat Mar 06 00:00:00 CET 3909
Ship(King Roy) ARRIVED  at port   Port(Vancouver) @ Mon Mar 08 00:00:00 CET 3909
Ship(King Roy) DEPARTED from port Port(San Francisco) @ Tue Mar 09 00:00:00 CET 3909
Ship(King Roy) ARRIVED  at port   Port(San Francisco) @ Thu Mar 11 00:00:00 CET 3909

===&amp;gt; resetAndReplayEventLog
Ship(King Roy) has been reset
Ship(King Roy) DEPARTED from port Port(San Francisco) @ Mon Mar 01 00:00:00 CET 3909
Ship(King Roy) ARRIVED  at port   Port(San Francisco) @ Wed Mar 03 00:00:00 CET 3909
Ship(King Roy) DEPARTED from port Port(Los Angeles) @ Thu Mar 04 00:00:00 CET 3909
Ship(King Roy) ARRIVED  at port   Port(Los Angeles) @ Fri Mar 05 00:00:00 CET 3909
Ship(King Roy) DEPARTED from port Port(Vancouver) @ Sat Mar 06 00:00:00 CET 3909
Ship(King Roy) ARRIVED  at port   Port(Vancouver) @ Mon Mar 08 00:00:00 CET 3909
Ship(King Roy) DEPARTED from port Port(San Francisco) @ Tue Mar 09 00:00:00 CET 3909
Ship(King Roy) ARRIVED  at port   Port(San Francisco) @ Thu Mar 11 00:00:00 CET 3909

===&amp;gt; resetAndReplayEventLogUpToDate
Ship(King Roy) has been reset
Ship(King Roy) DEPARTED from port Port(San Francisco) @ Mon Mar 01 00:00:00 CET 3909
Ship(King Roy) ARRIVED  at port   Port(San Francisco) @ Wed Mar 03 00:00:00 CET 3909
Ship(King Roy) DEPARTED from port Port(Los Angeles) @ Thu Mar 04 00:00:00 CET 3909
&lt;/pre&gt;
&lt;p&gt;That&amp;#8217;s all there&amp;#8217;s to it. We have only scratched the surface on what can be done with asynchronous Event Sourcing, and as in all these kind of articles, the example is almost too simplistic to fully understand the power and flexibility of the solution. But I hope that you have understood the underlying principle enough to be able to apply it to a real-world enterprise system.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Slides for my Pragmatic Real-World Scala presentation</title>
   <link href="http://jonasboner.com/2009/01/30/slides-pragmatic-real-world-scala.html"/>
   <updated>2009-01-30T00:00:00+01:00</updated>
   <id>http://jonasboner.com/2009/01/30/slides-pragmatic-real-world-scala</id>
   <content type="html">&lt;h1&gt;Slides for my Pragmatic Real-World Scala presentation&lt;/h1&gt;
&lt;p class=&quot;meta&quot;&gt;30 Jan 2009&lt;/p&gt;
&lt;p&gt;I have uploaded the slides for my &amp;#8216;Pragmatic Real-World Scala&amp;#8217; talk that I gave at &lt;a href=&quot;http://jfokus.se&quot;&gt;Jfokus&lt;/a&gt; yesterday to &lt;a href=&quot;http://www.slideshare.net/jboner/pragmatic-real-world-scala-45-min-presentation&quot;&gt;slideshare&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Enjoy.&lt;/p&gt;
&lt;div style=&quot;width:425px;text-align:left&quot; id=&quot;__ss_966972&quot;&gt;
&lt;a style=&quot;font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;&quot; href=&quot;http://www.slideshare.net/jboner/pragmatic-real-world-scala-45-min-presentation?type=powerpoint&quot; title=&quot;Pragmatic Real-World Scala (short version)&quot;&gt;Pragmatic Real-World Scala (short version)&lt;/a&gt;&lt;object style=&quot;margin:0px&quot; width=&quot;425&quot; height=&quot;355&quot;&gt;&lt;param name=&quot;movie&quot; value=&quot;http://static.slideshare.net/swf/ssplayer2.swf?doc=pragmaticrealworldscalajfokus2009-1233251076441384-2&amp;rel=0&amp;stripped_title=pragmatic-real-world-scala-45-min-presentation&quot; /&gt;&lt;param name=&quot;allowFullScreen&quot; value=&quot;true&quot;/&gt;&lt;param name=&quot;allowScriptAccess&quot; value=&quot;always&quot;/&gt;&lt;embed src=&quot;http://static.slideshare.net/swf/ssplayer2.swf?doc=pragmaticrealworldscalajfokus2009-1233251076441384-2&amp;rel=0&amp;stripped_title=pragmatic-real-world-scala-45-min-presentation&quot; type=&quot;application/x-shockwave-flash&quot; allowscriptaccess=&quot;always&quot; allowfullscreen=&quot;true&quot; width=&quot;425&quot; height=&quot;355&quot;&gt;&lt;/embed&gt;&lt;/object&gt;
&lt;/div&gt;</content>
 </entry>
 
 <entry>
   <title>Added Comments to Blog</title>
   <link href="http://jonasboner.com/2009/01/30/added-comments-to-blog.html"/>
   <updated>2009-01-30T00:00:00+01:00</updated>
   <id>http://jonasboner.com/2009/01/30/added-comments-to-blog</id>
   <content type="html">&lt;h1&gt;Added Comments to Blog&lt;/h1&gt;
&lt;p class=&quot;meta&quot;&gt;30 Jan 2009&lt;/p&gt;
&lt;p&gt;Many people have asked for it, so I have decided to add comments to my blog again.&lt;/p&gt;
&lt;p&gt;Thank you &lt;a href=&quot;http://disqus.com&quot;&gt;Disqus&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Let the discussion &lt;a href=&quot;http://jonasboner.com&quot;&gt;continue&lt;/a&gt;.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Back To Consulting</title>
   <link href="http://jonasboner.com/2009/01/10/back-to-consulting.html"/>
   <updated>2009-01-10T00:00:00+01:00</updated>
   <id>http://jonasboner.com/2009/01/10/back-to-consulting</id>
   <content type="html">&lt;h1&gt;Back To Consulting&lt;/h1&gt;
&lt;p class=&quot;meta&quot;&gt;10 Jan 2009&lt;/p&gt;
&lt;p&gt;The last year has been a ride.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://triental.com&quot;&gt;Startup&lt;/a&gt; in finance business, green field development, challenging and interesting problem domain, been pushing &lt;a href=&quot;http://scala-lang.org&quot;&gt;Scala&lt;/a&gt; to its limits in a real-world production setting. Its been a lot of fun and a great learning experience. (I have written some about the way we have used Scala in the &amp;#8220;Real-World Scala&amp;#8221; series of blog posts, check the &lt;a href=&quot;/archives&quot;&gt;archives&lt;/a&gt; if you are curious.)&lt;/p&gt;
&lt;p&gt;But now its all over. Zero cash flow in. Knocked out by the financial crisis. To bad, we had a great product coming. But not much to do.&lt;/p&gt;
&lt;p&gt;The good news is that I am back in the consulting business. Rewrote and redesigned my company site to mark the beginnning of a new era&amp;#8230;well, at least a &amp;#8220;new&amp;#8221; job.&lt;/p&gt;
&lt;p&gt;Check it out and let me know if you need help :-)&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://scalablesolutions.se/&quot;&gt;http://scalablesolutions.se&lt;/a&gt;&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Blogging Like a Hacker using Git and Jekyll</title>
   <link href="http://jonasboner.com/2009/01/07/blogging-like-a-hacker-using-git-and-jekyll.html"/>
   <updated>2009-01-07T00:00:00+01:00</updated>
   <id>http://jonasboner.com/2009/01/07/blogging-like-a-hacker-using-git-and-jekyll</id>
   <content type="html">&lt;h1&gt;Blogging Like a Hacker using Git and Jekyll&lt;/h1&gt;
&lt;p class=&quot;meta&quot;&gt;7 Jan 2009&lt;/p&gt;
&lt;p&gt;For the last year and have been falling in love with &lt;a href=&quot;http://git-scm.com&quot;&gt;Git&lt;/a&gt;. Git is truly an amazing&amp;#8230;..tool. I was going to say Source Code Management System (&lt;span class=&quot;caps&quot;&gt;SCM&lt;/span&gt;), but that ain&amp;#8217;t fair, Git is so much more. Git deserves a post on its own, however in this one I&amp;#8217;m going to talk about one of the things it can help you with; to blog like a hacker.&lt;/p&gt;
&lt;p&gt;For the last year I have not only used Git but have hosted my whole professional life on &lt;a href=&quot;http://github.com&quot;&gt;GitHub&lt;/a&gt;. GitHub started as a server with Git repositories but have since then grown into a thriving community with a lot of interesting and cool features and side projects up its sleeve. One of these &amp;#8220;features&amp;#8221; is &lt;a href=&quot;http://github.com/mojombo/jekyll/tree/master&quot;&gt;Jekyll&lt;/a&gt;. Jekyll is a minimalistic blog engine based upon Git. It allows you to write all your blog posts in either Textile, Markdown or &lt;span class=&quot;caps&quot;&gt;HTML&lt;/span&gt; while having Git (and GitHub) take care of storage, versioning etc.&lt;/p&gt;
&lt;p&gt;It is dead simple. Generates everything into static &lt;span class=&quot;caps&quot;&gt;HTML&lt;/span&gt;, which I think is great. And as with all viral good open source, there are already a bunch of plug-ins such as for example converting your MT, WordPress, Typo etc blogs into Textile/Markdown for Jekyll to consume. The thing I like most is that everything is plain text, residing in your Git repository (e.g. on your file system). This means that I can write my blog post in Emacs, commit the changes using the Emacs (emacs-git), push it up to GitHub using Emacs, generate my site and &lt;span class=&quot;caps&quot;&gt;FTP&lt;/span&gt; it up to my server from Emacs (replace Emacs with your favorite editor). Never been easier (or more fun) to blog. Hopefully this will make me do it more often.&lt;/p&gt;
&lt;p&gt;For a sample of a Jekyll-powered blog, take a look at mine: &lt;a href=&quot;http://jonasboner.com&quot;&gt;http://jonasboner.com&lt;/a&gt;&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Real-World Scala: Fault-tolerant Concurrent Asynchronous Components</title>
   <link href="http://jonasboner.com/2008/12/11/real-world-scala-fault-tolerant-concurrent-asynchronous-components.html"/>
   <updated>2008-12-11T00:00:00+01:00</updated>
   <id>http://jonasboner.com/2008/12/11/real-world-scala-fault-tolerant-concurrent-asynchronous-components</id>
   <content type="html">&lt;h1&gt;
&lt;p&gt;Real-World Scala: Fault-tolerant Concurrent Asynchronous Components&lt;/p&gt;
&lt;/h1&gt;
&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;In a &lt;a href=&quot;http://jonasboner.com/2008/06/16/erlang-style-supervisor-module-for-scala-actors.html&quot;&gt;previous post&lt;/a&gt; I wrote about &lt;a href=&quot;http://github.com/jboner/scala-otp/tree/master&quot;&gt;Scala &lt;span class=&quot;caps&quot;&gt;OTP&lt;/span&gt;&lt;/a&gt;, an initial attempt to bring the power or &lt;a href=&quot;http://www.erlang.se/doc/index.shtml&quot;&gt;Erlang &lt;span class=&quot;caps&quot;&gt;OTP&lt;/span&gt;&lt;/a&gt;, in particular its supervisor hierarchies and generic server to the &lt;a href=&quot;
http://www.scala-lang.org/node/242&quot;&gt;Scala Actors library&lt;/a&gt;. &lt;span class=&quot;caps&quot;&gt;OTP&lt;/span&gt; is one of the key parts in the Erlang success story and is in my opinion a requirement for Scala Actors to succeed in the real world.&lt;/p&gt;
&lt;p&gt;Actors can simplify concurrent programming and reasoning immensely and I believe that Scala Actors is a key piece in the future Java concurrency puzzle. However, programming with actors and with explicit message passing and message dispatch loops can feel a bit unnatural and unnecessary verbose for Java developers that are used to regular OO method invocations and synchronous control flow.&lt;/p&gt;
&lt;p&gt;For example, if we want to be able to pass a single message from one actor to the next we have to define two things.&lt;/p&gt;
&lt;p&gt;A message with optional payload.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
case class MyMessage(payload: AnyRef)
&lt;/pre&gt;
&lt;p&gt;A message dispatch matching loop (partial function) in the receiving actor.&lt;/p&gt;

&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
def act = {
  loop {
    react {
      case MyMessage(payload) =&amp;amp;gt; 
        ...  // do something with payload
      case _ =&amp;gt; 
        ... // default case
    }
  }
}
&lt;/pre&gt;
&lt;p&gt;It is also complicated to do things like stateful control flow, e.g. send message to A, wait for reply, then send message to B, wait for reply, then do C. (this can in some ways be addressed using &lt;a href=&quot;http://lampsvn.epfl.ch/trac/scala/attachment/ticket/781/monadActor.scala&quot;&gt;monad continuations&lt;/a&gt;, but is still not simple and intuitive to use).&lt;/p&gt;
&lt;p&gt;Don&amp;#8217;t get me wrong. Even though it has its &amp;#8220;flaws&amp;#8221;, using actors (message-passing concurrency) for concurrent programming is still &lt;strong&gt;so much&lt;/strong&gt; simpler than using threads and locks (shared-state concurrency).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Active Objects (Concurrent Asynchronous Components)&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;In this post I&amp;#8217;ll outline a little library that we have been using that tries to unify Scala Actors, Scala &lt;span class=&quot;caps&quot;&gt;OTP&lt;/span&gt; (supervisor hierarchies for fault tolerance) and regular OO method dispatch into an asynchronous component framework that I think can be best described as &lt;a href=&quot;http://en.wikipedia.org/wiki/Active_Object&quot;&gt;&lt;em&gt;Active Objects&lt;/em&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Each so-called &lt;em&gt;Active Object&lt;/em&gt; (concurrent asynchronous component) is a &lt;code&gt;GenericServer&lt;/code&gt; that is managed by a &lt;code&gt;Supervisor&lt;/code&gt;, either in isolation or as part of a supervisor hierarchy/tree. E.g. each component is fully fault-tolerant. For more information about how supervisor hierarchies work, read this post.  Each component consists of an interface (trait) and a regular Scala class as implementation for the interface. The catch is that each component has to be instantiate through a factory. Let&amp;#8217;s first take a look at the &lt;span class=&quot;caps&quot;&gt;API&lt;/span&gt; and how to use this thing before we dig into the actual implementation.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Usage&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Here is a simple example of a component that is using default supervisor management (which among other things mean that it is not part of a supervisor tree/hierarchy, but is still managed and will be restarted upon failure). We start with the component interface and implementation.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
  trait Foo {
    def foo(msg: String): String    
    @oneway def bar(msg: String)
  }

  class FooImpl extends Foo {
    def foo(msg: String): String = { println(&quot;foo: &quot; + msg); msg } 
    def bar(msg: String) = println(&quot;bar: &quot; + msg)
  }
&lt;/pre&gt;

&lt;p&gt;Now let&amp;#8217;s instantiate this component. The integer 1000 specifies the time interval an (asynchronous) invocation should have before timing out.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
  val foo = ActiveObject.newInstance[Foo](classOf[Foo], new FooImpl, 1000)
&lt;/pre&gt;

&lt;p&gt;Now we can use this component as any regular instance of &lt;code&gt;Foo&lt;/code&gt;. The difference is that invocations are now asynchronously dispatched in an event-based actor with its return value is wrapped in a &lt;code&gt;Future&lt;/code&gt;, this emulates synchronous behavior but is non-blocking. The  exception to this behavior is if a method is annotated with the &lt;code&gt;@scala.actors.annotation.oneway&lt;/code&gt; annotation, then it returns immediately. All components created through the factory are fault-tolerant &lt;code&gt;GenericServers&lt;/code&gt; managed by a &lt;code&gt;Supervisor&lt;/code&gt;, which means that they will be restarted upon failure using the restart scheme the supervisor has defined it under.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
   // use as usual
   foo.foo(&quot;foo&quot;)
   foo.bar(&quot;bar&quot;) // returns immediately since annotated with @oneway
&lt;/pre&gt;

&lt;p&gt;Now, if I would like to have more control over the &lt;code&gt;Supervisor&lt;/code&gt; configuration and/or want to compose different components into supervisor hierarchies, then we can use another factory method along with a method called &lt;code&gt;start&lt;/code&gt; that allows us to pass in a &lt;code&gt;Supervisor&lt;/code&gt; configuration (as defined by the Scala &lt;span class=&quot;caps&quot;&gt;OTP&lt;/span&gt; Supervisor).&lt;/p&gt;
&lt;p&gt;Let&amp;#8217;s take a look at a full example:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
  trait Foo {
    def foo(msg: String): String    
    @oneway def bar(msg: String)
  }

  class FooImpl extends Foo {
    val bar: Bar = new BarImpl 
    def foo(msg: String): String = { println(&quot;foo: &quot; + msg); msg } 
    def bar(msg: String) = bar.bar(msg)
  }

  trait Bar {
    def bar(msg: String)
  }

  class BarImpl extends Bar {
    def bar(msg: String) = println(&quot;bar: &quot; + msg)
  }
&lt;/pre&gt;

&lt;p&gt;First create proxies (&lt;code&gt;GenericServer&lt;/code&gt;s) for our services.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
  val fooProxy = new ActiveObjectProxy(new FooImpl, 1000)
  val barProxy = new ActiveObjectProxy(new BarImpl, 1000)
&lt;/pre&gt;
&lt;p&gt;Then let&amp;#8217;s configure the &lt;code&gt;GenericServer&lt;/code&gt;(s) by creating a list of &lt;code&gt;GenericServer&lt;/code&gt; configurations (defining lifecycles, restart strategies etc.). This configuration is passed into the &lt;code&gt;ActiveObject.supervise&lt;/code&gt; method which starts up the &lt;code&gt;Supervisor&lt;/code&gt; which starts up all &lt;code&gt;GenericServer&lt;/code&gt;&amp;#8217;s according to their configurations before returning the &lt;code&gt;Supervisor&lt;/code&gt; instance (which can be used for management of the components).&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
val supervisor = 
  ActiveObject.supervise(
    RestartStrategy(AllForOne, 3, 100),
    Component(
      fooProxy,
      LifeCycle(Permanent, 100)) ::
    Component(
      barProxy,
      LifeCycle(Permanent, 100))
    :: Nil)
&lt;/pre&gt;

&lt;p&gt;Create and use the components as in the previous example..&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
  val foo = ActiveObject.newInstance[Foo](classOf[Foo], fooProxy)
  val bar = ActiveObject.newInstance[Bar](classOf[Bar], barProxy)

  foo.foo(&quot;foo &quot;) 
  bar.bar(&quot;bar &quot;)
&lt;/pre&gt;

&lt;p&gt;That pretty much sums it up. So how is this implemented?&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Implementation&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The first thing we need to do is to define an invocation context, holding arguments, method to be invoked as well as the target instance.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
  case class Invocation(val method: Method, val args: Array[AnyRef], val target: AnyRef) {
    def invoke: AnyRef = method.invoke(target, args:_*)
    override def toString: String = &quot;Invocation [method: &quot; + method.getName + &quot;, args: &quot; + args + &quot;, target: &quot; + target + &quot;]&quot;
    override def hashCode(): Int = { ... }
    override def equals(that: Any): Boolean = { ... }
  }
&lt;/pre&gt;
&lt;p&gt;The second thing we need to do is to create a dynamic proxy wrapping the asynchronous dispatch. This proxy holds an instance of an actor dressed up in a &lt;code&gt;GenericServer&lt;/code&gt;.  Now comes the little trick; we will now use the &lt;code&gt;Invocation&lt;/code&gt; context as the message to our &lt;code&gt;GenericServer&lt;/code&gt; actor.&lt;/p&gt;
&lt;p&gt;As you can see in the code for the &lt;code&gt;dispatcher&lt;/code&gt; we are defining a partial function that is defined for two different messages; &lt;code&gt;Invocation&lt;/code&gt; and &lt;code&gt;'exit&lt;/code&gt;. If the &lt;code&gt;Invocation&lt;/code&gt; message is received, then we invoke the invocation context, e.g. the method on the implementation instance and are returning the result to the caller using &lt;code&gt;reply(..)&lt;/code&gt;. If we receive an &lt;code&gt;'exit&lt;/code&gt; message and we terminate the &lt;code&gt;GenericServer&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The call flow for this proxy is as follows. When a regular synchronous method invocation is made on the service interface or component is redirected to the &lt;code&gt;invoke(..)&lt;/code&gt; method.  In this method we simply create an invocation context for this specific method invocation and sends it as a message to our &lt;code&gt;GenericServer&lt;/code&gt; (server). Here we have two options.  If the target method is annotated with the &lt;code&gt;@scala.actors.annotation.oneway&lt;/code&gt; annotation then we fire the message and forget by invoking &lt;code&gt;server ! invocation&lt;/code&gt;, else we are sending the message using the &lt;code&gt;server !!! invocation&lt;/code&gt; operator which returns a &lt;code&gt;Future&lt;/code&gt; which we then wait on (emulating a synchronous method call).&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
class ActiveObjectProxy(val target: AnyRef, val timeout: Int) extends InvocationHandler {
  private val oneway = classOf[scala.actors.annotation.oneway]
 
  private[ActiveObjectProxy] object dispatcher extends GenericServer {
    override def body: PartialFunction[Any, Unit] = {
      case invocation: Invocation =&amp;gt;
        try {
          reply(ErrRef(invocation.invoke))
        } catch {
          case e: InvocationTargetException =&amp;amp;gt; reply(ErrRef({ throw e.getTargetException }))
          case e =&amp;amp;gt; reply(ErrRef({ throw e }))
        }
      case 'exit =&amp;amp;gt; exit; reply()
      case unexpected =&amp;gt; throw new ActiveObjectException(&quot;Unexpected message to actor proxy: &quot; + unexpected)
    }
  }
 
  private[component] val server = new GenericServerContainer(target.getClass.getName, () =&amp;gt; dispatcher)
  server.setTimeout(timeout)
  
  def invoke(proxy: AnyRef, m: Method, args: Array[AnyRef]): AnyRef = invoke(Invocation(m, args, target))
 
  def invoke(invocation: Invocation): AnyRef = {
    if (invocation.method.isAnnotationPresent(oneway)) server ! invocation // fire and forget
    else {
      val result: ErrRef[AnyRef] = server !!! (invocation, ErrRef({ throw new ActiveObjectInvocationTimeoutException(&quot;proxy invocation timed out after &quot; + timeout + &quot; milliseconds&quot;) }))
      result() // wait on future for result
    }
  }
}
&lt;/pre&gt;
&lt;p&gt;Finally we create a factory which will do the &lt;code&gt;Supervisor&lt;/code&gt; configuration, wiring and startup.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
object ActiveObject {
 
  def newInstance[T](intf: Class[T] forSome {type T}, target: AnyRef, timeout: Int): T = {
    val proxy = new ActiveObjectProxy(target, timeout)
    supervise(proxy)
    newInstance(intf, proxy)
  }
 
  def newInstance[T](intf: Class[T] forSome {type T}, proxy: ActiveObjectProxy): T = {
    Proxy.newProxyInstance(
      proxy.target.getClass.getClassLoader,
      Array(intf),
      proxy).asInstanceOf[T]
  }
 
  def supervise(restartStrategy: RestartStrategy, components: List[Component]): Supervisor = {
    object factory extends SupervisorFactory {
      override def getSupervisorConfig: SupervisorConfig = {
        SupervisorConfig(restartStrategy, components.map(c =&amp;gt; Worker(c.component.server, c.lifeCycle)))
      }
    }
    val supervisor = factory.newSupervisor
    supervisor ! scala.actors.behavior.Start
    supervisor
  }
 
  private def supervise(proxy: ActiveObjectProxy): Supervisor =
    supervise(
      RestartStrategy(OneForOne, 5, 1000),
      Component(
        proxy,
        LifeCycle(Permanent, 100))
      :: Nil)
}
 &lt;/pre&gt;
&lt;p&gt;That&amp;#8217;s pretty much all there is to it. The code is available as part of the Scala &lt;span class=&quot;caps&quot;&gt;OTP&lt;/span&gt; library:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://github.com/jboner/scala-otp/tree/master/component&quot;&gt;http://github.com/jboner/scala-otp/tree/master/component&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Check it out by invoking: &lt;code&gt;git clone git://github.com/jboner/scala-otp.git&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;All ideas, improvements, patches etc. are most welcome.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Real-World Scala: Managing Cross-Cutting Concerns using Mixin Composition and AOP</title>
   <link href="http://jonasboner.com/2008/12/09/real-world-scala-managing-cross-cutting-concerns-using-mixin-composition-and-aop.html"/>
   <updated>2008-12-09T00:00:00+01:00</updated>
   <id>http://jonasboner.com/2008/12/09/real-world-scala-managing-cross-cutting-concerns-using-mixin-composition-and-aop</id>
   <content type="html">&lt;h1&gt;
&lt;p&gt;Real-World Scala: Managing Cross-Cutting Concerns using Mixin Composition and &lt;span class=&quot;caps&quot;&gt;AOP&lt;/span&gt;&lt;/p&gt;
&lt;/h1&gt;
&lt;p&gt;In a &lt;a href=&quot;http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di.html&quot;&gt;previous post&lt;/a&gt; I showed you how you could use mixin composition and self type annotations to enable Dependency Injection (DI). Mixin composition is an extremely powerful tool that you can utilize in many different ways to enable modular and reusable code.  In this post I&amp;#8217;ll try to show you how you can use it to solve the problem of crosscutting concerns using &lt;span class=&quot;caps&quot;&gt;AOP&lt;/span&gt;/interceptor-style composition.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Crosscutting concerns and &lt;span class=&quot;caps&quot;&gt;AOP&lt;/span&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class=&quot;caps&quot;&gt;OOP&lt;/span&gt; has given us tools to reduce software complexity by introducing concepts like inheritance, abstraction, and polymorphism. However, developers face daily problems in software design that can&amp;#8217;t be solved easily using &lt;span class=&quot;caps&quot;&gt;OOP&lt;/span&gt;. One of these problems is how to handle cross-cutting concerns in the application.&lt;/p&gt;
&lt;p&gt;So what is a cross-cutting concern? A concern is a particular concept or area of interest. For example, in an ordering system the core concerns could be order processing and manufacturing, while the system concerns could be transaction handling and security management. A cross-cutting concern is a concern that affects several classes or modules, a concern that is not well localized and modularized.&lt;/p&gt;
&lt;p&gt;Symptoms of a cross-cutting concern are:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Code tangling &amp;#8211; when a module or code section is managing several concerns simultaneously&lt;/li&gt;
	&lt;li&gt;Code scattering &amp;#8211; when a concern is spread over many modules and is not well localized and modularized&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These symptoms affect software in various ways; for example, they make it harder to maintain and reuse software as well as harder to write and understand.&lt;/p&gt;
&lt;p&gt;Aspect-Oriented Programming (&lt;span class=&quot;caps&quot;&gt;AOP&lt;/span&gt;) tries to solve these problems by introducing the concept of separation of concerns, in which concerns can be implemented in a modular and well-localized way. &lt;span class=&quot;caps&quot;&gt;AOP&lt;/span&gt; solves this by adding an extra dimension to the design space, and introduces constructs that allow us to define the cross-cutting concerns, to lift them out into a new dimension and package them in a modular way.&lt;/p&gt;
&lt;p&gt;We are currently using two different types of interceptors (aspects if you like):&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Mixin composition stacks &amp;#8212; a limited but sometimes very useful approach&lt;/li&gt;
	&lt;li&gt;Generic interceptors/aspects using a pointcut pattern language&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Mixin composition stacks&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Mixin composition stacks is a core language feature of Scala and is similar to Rickard Oberg&amp;#8217;s idea on using the so-called &lt;a href=&quot;http://www.jroller.com/rickard/date/20031028&quot;&gt;Abstract Schema&lt;/a&gt; pattern for type-safe &lt;span class=&quot;caps&quot;&gt;AOP&lt;/span&gt; in plain Java. (This is a very contrived example that probably shows that don&amp;#8217;t know a zip about dogs, but please bare with me.)&lt;/p&gt;
&lt;p&gt;First let&amp;#8217;s define a couple of interfaces; &lt;code&gt;Dog&lt;/code&gt; and &lt;code&gt;DogMood&lt;/code&gt; modeled as a mixins (in this case without an implementation so similar to Java&amp;#8217;s interface):&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
trait Dog {
  def greet(me: Human)
}

trait DogMood extends Dog {
  def greet(me: Human) {
    println(me.sayHello)
  }
}
&lt;/pre&gt;
&lt;p&gt;Now let&amp;#8217;s define two different mixin &amp;#8220;interceptors&amp;#8221; that implement these interfaces. The first one defining an angry dog and the other one a hungry dog:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
trait AngryDog extends DogMood {
  abstract override def greet(me: Human) {
    println(&quot;Dog: Barks @ &quot; + me)
    super.greet(me)
  }
}
&lt;/pre&gt;

&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
trait HungryDog extends DogMood {
  abstract override def greet(me: Human) {
    super.greet(me)
    println(&quot;Dog: Bites &quot; + me)
  }
}
&lt;/pre&gt;
&lt;p&gt;As we can see in this example they both override the &lt;code&gt;Mood.greet&lt;/code&gt; method. If we look more closely we can see that they follow the same pattern:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Enter method (&lt;tt&gt;greet&lt;/tt&gt;)&lt;/li&gt;
&lt;li&gt;Do something&lt;/li&gt;
&lt;li&gt;Invoke the same method on &lt;tt&gt;super&lt;/tt&gt; (&lt;tt&gt;super.greet&lt;/tt&gt;)&lt;/li&gt;
&lt;li&gt;Do something else&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The trick here is in the semantics of the call to super. Here Scala will invoke the next mixin in a stack of mixins, e.g. the same method in the &amp;#8220;next&amp;#8221; mixin that have been mixed in. Exactly what f.e. &lt;a href=&quot;http://aspectj.org&quot;&gt;AspectJ&lt;/a&gt; does in its &lt;tt&gt;proceed(..)&lt;/tt&gt; method and what Spring does in its interceptors.&lt;/p&gt;
&lt;p&gt;Now let&amp;#8217;s fire up the Scala &lt;span class=&quot;caps&quot;&gt;REPL&lt;/span&gt; and create a component based on the &lt;code&gt;Dog&lt;/code&gt; interface. Scala&amp;#8217;s mixin composition can take place when we instantiate an instance, e.g. it allows us to mix in functionality into specific instances that object creation time for specific object instances.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
scala&amp;gt; val dog = new Dog with AngryDog with HungryDog 
stuff2: Dog with AngryDog with HungryDog = $anon$1@1082d45

scala&amp;gt; dog.greet(new Human(&quot;Me&quot;))
Dog: Barks @ Me
Me: Hello doggiedoggie
Dog: Bites Me
&lt;/pre&gt;
&lt;p&gt;As you can see the call to &lt;code&gt;Dog.greet&lt;/code&gt; is intercepted by the different moods that are added to the dog at instantiation time.&lt;/p&gt;
&lt;p&gt;Interceptors like this are as you can see not generically reusable since they are tied to a specific interface, however if well designed can be a pretty powerful technique.  It has the advantage that everything is statically compiled and type-checked by the Scala compiler&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Generic pointcut-based aspects&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The main usage of generic aspects is for implementing infrastructure concerns such as logging, transaction demarcation, security, clustering, persistence etc.&lt;/p&gt;
&lt;p&gt;In order to create a framework for implementing generic aspects, the first thing we need to do is to define an invocation context, holding arguments, method to be invoked as well as the target instance.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
case class Invocation(val method: Method, val args: Array[AnyRef], val target: AnyRef) {
  def invoke: AnyRef = method.invoke(target, args:_*)
  override def toString: String = &quot;Invocation [method: &quot; + method.getName + &quot;, args: &quot; + args + &quot;, target: &quot; + target + &quot;]&quot;
  override def hashCode(): Int = { ... }
  override def equals(that: Any): Boolean = { ... }
}
&lt;/pre&gt;
&lt;p&gt;The second thing that we need to do is to create a base Interceptor trait. This interface defines two different pointcut matching methods.  The first one matches a precompiled &lt;a href=&quot;http://aspectj.org&quot;&gt;AspectJ &lt;/a&gt;pointcut expression using the PointcutParser in AspectJ. This allows defining interceptors matches AspectJ compatible (method) pointcut expressions. The second matcher matches methods or classes that is annotated with a specific annotation.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
trait Interceptor {
  protected val parser = PointcutParser.getPointcutParserSupportingAllPrimitivesAndUsingContextClassloaderForResolution

  protected def matches(pointcut: PointcutExpression, invocation: Invocation): Boolean = {
    pointcut.matchesMethodExecution(invocation.method).alwaysMatches ||
    invocation.target.getClass.getDeclaredMethods.exists(pointcut.matchesMethodExecution(_).alwaysMatches) ||
    false
  }

  protected def matches(annotationClass: Class[T] forSome {type T &amp;lt;: Annotation}, invocation: Invocation): Boolean = {
    invocation.method.isAnnotationPresent(annotationClass) ||
    invocation.target.getClass.isAnnotationPresent(annotationClass) ||
    false
  }

  def invoke(invocation: Invocation): AnyRef
}
&lt;/pre&gt;
&lt;p&gt;The last thing we need to do is to create a factory method allows us to wire in our interceptors, declarative, in a seamless fashion. This factory is using the plain old Java Dynamic Proxy &lt;span class=&quot;caps&quot;&gt;API&lt;/span&gt; to create a proxy for our base components.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
object ManagedComponentFactory {
  def createComponent[T](intf: Class[T] forSome {type T}, proxy: ManagedComponentProxy): T =
    Proxy.newProxyInstance(
      proxy.target.getClass.getClassLoader,
      Array(intf),
      proxy).asInstanceOf[T]
}

class ManagedComponentProxy(val target: AnyRef) extends InvocationHandler {
  def invoke(proxy: AnyRef, m: Method, args: Array[AnyRef]): AnyRef = invoke(Invocation(m, args, target))
  def invoke(invocation: Invocation): AnyRef = invocation.invoke
}
&lt;/pre&gt;
&lt;p&gt;Just using this factory pass is won&amp;#8217;t do any wiring for us, which is actually good since if we would use the dynamic proxy the old-fashioned way and we would have it to invoke each interceptor explicitly using reflection. But we can do better than that. Instead we will let the Scala compiler statically compiled in an interceptor stack with all our interceptors. This is best explained with an example.&lt;/p&gt;
&lt;p&gt;In this example we will define a couple of simple services called &lt;code&gt;Foo&lt;/code&gt; and &lt;code&gt;Bar&lt;/code&gt; along with their implementations. We will then implement two different infrastructure in interceptors; logging and transaction demarcation.&lt;/p&gt;
&lt;p&gt;Let&amp;#8217;s first define the service.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
  import javax.ejb.{TransactionAttribute, TransactionAttributeType}

  trait Foo {
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    def foo(msg: String)
    def bar(msg: String)
  }

  class FooImpl extends Foo {
    val bar: Bar = new BarImpl
    def foo(msg: String) = println(&quot;msg: &quot; + msg)
    def bar(msg: String) = bar.bar(msg)
  }

  trait Bar {
    def bar(msg: String)
  }

  class BarImpl extends Bar {
    def bar(msg: String) = println(&quot;msg: &quot; + msg)
  }
&lt;/pre&gt;
&lt;p&gt;Now let&amp;#8217;s define a logging interceptor.  Both of these interceptors are just mockups, since the actual implementation is not really of interest. The logging interceptor is defined using a standard AspectJ pointcut while the transaction interceptor is wired to a specific annotation.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
  trait LoggingInterceptor extends Interceptor {
    val loggingPointcut = parser.parsePointcutExpression(&quot;execution(* *.bar(..))&quot;)

    abstract override def invoke(invocation: Invocation): AnyRef = 
      if (matches(loggingPointcut , invocation)) {
        println(&quot;=====&amp;gt; Enter: &quot; + invocation.method.getName + &quot; @ &quot; + invocation.target.getClass.getName)
        val result = super.invoke(invocation)
        println(&quot;=====&amp;gt; Exit: &quot; + invocation.method.getName + &quot; @ &quot; + invocation.target.getClass.getName)
        result
      } else super.invoke(invocation)
  }

  trait TransactionInterceptor extends Interceptor {
    val matchingJtaAnnotation = classOf[javax.ejb.TransactionAttribute]

    abstract override def invoke(invocation: Invocation): AnyRef = 
      if (matches(matchingJtaAnnotation, invocation)) {
        println(&quot;=====&amp;gt; TX begin&quot;)
        try {
          val result = super.doStuff
          println(&quot;=====&amp;gt; TX commit&quot;)
          result     
        } catch {
          case e: Exception =&amp;gt; 
            println(&quot;=====&amp;gt; TX rollback &quot;)
        } 
      } else super.invoke(invocation)
  }
&lt;/pre&gt;
&lt;p&gt;Now let&amp;#8217;s do the wiring.  Here we are using dynamic proxy-based factory that we implemented because you can see, the actual wiring on the interceptor stack is done using Scala mixing composition and therefore has all its benefits, like compiler type checking and enforcement, the speed of statically compiled code, refactoring safety etc.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
  var foo = ManagedComponentFactory.createComponent[Foo](
    classOf[Foo],
    new ManagedComponentProxy(new FooImpl)
      with LoggingInterceptor
      with TransactionInterceptor)

  foo.foo(&quot;foo&quot;)
  foo.bar(&quot;bar&quot;)
 }
&lt;/pre&gt;

&lt;p&gt;This will produce the following output:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
=====&amp;gt; TX begin
msg: foo
=====&amp;gt; TX commit
=====&amp;gt; Enter: bar @ FooImpl
msg: bar
=====&amp;gt; Exit: bar @ FooImpl
&lt;/pre&gt;
&lt;p&gt;So this wraps it up.  I hope that you have learned a little bit about how powerful mixin composition in Scala is and how it can be used to write modular and reusable components with little effort.&lt;/p&gt;
&lt;p&gt;This is working fine for us, but there is definitely room for improvement. For example, runtime matcher in the interceptor is fast enough for the annotation matching (only a boolean check) but the AspectJ pointcut matcher is a bit slower since it has to do some more work. This might turn out be a problem or not, most infrastructure services (like persistence and security) performs quite a lot to work and in these cases the overhead over the interceptor of matching will not affect the overall performance much, but in other cases (such as logging or auditing) it might. We are so far only use the annotation matching, so it has not turned out to be a problem so far.  However, if it turns out to be a performance bottleneck then we will most likely switch to using my old AspectWerkz &lt;a href=&quot;http://jonasboner.com/2004/12/08/awproxy-proxy-on-steroids.html&quot;&gt;AWProxy&lt;/a&gt; to get rid of all the Java reflection code and runtime matching.&lt;/p&gt;
&lt;p&gt;For those that are interested, here is the actual &lt;span class=&quot;caps&quot;&gt;JTA&lt;/span&gt; transaction demarcation interceptor that we are using in production (implementing all the &lt;span class=&quot;caps&quot;&gt;EJB&lt;/span&gt; transaction semantics).&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
trait EjbTransactionInterceptor extends Interceptor with TransactionProtocol {
  val matchingJtaAnnotation = classOf[javax.ejb.TransactionAttribute]

  abstract override def invoke(invocation: Invocation): AnyRef = if (matches(matchingJtaAnnotation, invocation)) {
    val txType = getTransactionAttributeTypeFor(invocation.target.getClass, invocation.method)
    if (txType == TransactionAttributeType.REQUIRED)           withTxRequired { super.invoke(invocation) }
    else if (txType == TransactionAttributeType.REQUIRES_NEW)  withTxRequiresNew { super.invoke(invocation) }
    else if (txType == TransactionAttributeType.MANDATORY)     withTxMandatory { super.invoke(invocation) }
    else if (txType == TransactionAttributeType.NEVER)         withTxNever { super.invoke(invocation) }
    else if (txType == TransactionAttributeType.SUPPORTS)      withTxSupports { super.invoke(invocation) }
    else if (txType == TransactionAttributeType.NOT_SUPPORTED) withTxNotSupported { super.invoke(invocation) }
    else super.invoke(invocation)
  } else super.invoke(invocation)
}
&lt;/pre&gt;</content>
 </entry>
 
 <entry>
   <title>Reward Failure</title>
   <link href="http://jonasboner.com/2008/10/14/reward-failure.html"/>
   <updated>2008-10-14T00:00:00+02:00</updated>
   <id>http://jonasboner.com/2008/10/14/reward-failure</id>
   <content type="html">&lt;h1&gt;
&lt;p&gt;Reward Failure&lt;/p&gt;
&lt;/h1&gt;
&lt;p&gt;Alex Miller has written a very important post on the &lt;a href=&quot;http://tech.puredanger.com/2008/10/09/fail/&quot;&gt;importance of failure&lt;/a&gt;, putting, what has been one of my guiding principles in leadership and working environment building, in words.&lt;/p&gt;
&lt;p&gt;It can&amp;#8217;t be emphasized enough that for a company to be a leader and not a follower one of the most important things is to foster an environment that encourages and rewards failure &amp;#8211; as a potential outcome of taking risks, trying crazy ideas out and out-of-the-box-thinking. It is only in a working environment where the fear of failing has been eliminated that the employees are set free to create amazing things.&lt;/p&gt;
&lt;p&gt;This was one of the things that I loved most while working for Terracotta, an amazing place to be working at, and one of the reason why it has managed to hire and keep so many brilliant developers and visionaries.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Real-World Scala: Dependency Injection (DI) </title>
   <link href="http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di.html"/>
   <updated>2008-10-06T00:00:00+02:00</updated>
   <id>http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di</id>
   <content type="html">&lt;h1&gt;
&lt;p&gt;Real-World Scala: Dependency Injection (DI)&lt;/p&gt;
&lt;/h1&gt;
&lt;p&gt;&lt;em&gt;Update: Corrected typo in the Cake Pattern version of the last example.&lt;/em&gt;&lt;br /&gt;
&lt;em&gt;Update: Added a version of the last example using the Cake Pattern for easier &lt;br /&gt;
comparison (see end of post).&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;In this second post in the &lt;a href=&quot;http://jonasboner.com/2008/10/01/real-world-scala-introduction.html&quot;&gt;Real-World Scala series&lt;/a&gt; I am going to discuss how to implement/achieve &lt;a href=&quot;http://www.martinfowler.com/articles/injection.html&quot;&gt;Depenency Injection&lt;/a&gt; (DI) in Scala. Scala is a very rich and deep language that gives you several ways of doing DI solely based on language constructs, but nothing prevents you from using existing Java DI frameworks, if that is preferred.&lt;/p&gt;
&lt;p&gt;At &lt;a href=&quot;http://www.triental.com/&quot;&gt;Triental&lt;/a&gt; we tried out three different strategies before settling for the one we are using now. The plan for this article is as follows; first explain in detail how we are doing DI now, and then briefly cover the other alternative strategies we have tried out.&lt;/p&gt;
&lt;h3&gt;Using the Cake Pattern&lt;/h3&gt;
&lt;p&gt;The current strategy we are using is based on the so-called Cake Pattern. This pattern is first explained in Martin Oderskys&amp;#8217; paper &lt;a href=&quot;http://lamp.epfl.ch/~odersky/papers/ScalableComponent.pdf&quot;&gt;Scalable Component Abstractions&lt;/a&gt; (which is an excellent paper that is highly recommended) as the way he and his team structured the Scala compiler. But rather than trying to explain the pattern and how it can be used to implement DI in plain English let&amp;#8217;s take a look at some (naive) sample code (loosely based on our production code).&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Note: &lt;br /&gt;
I will try to explain things in steps which I refactor towards the final version (this is only to help with the understanding), so please wait with yelling: &lt;em&gt;&amp;#8220;This sucks!&amp;#8221;&lt;/em&gt;, until you have read and understood the final version (after which you are of course allowed come with any criticism/praise/suggestions/ideas you feel is necessary). Also, the sample code will, as in all these kind of examples, look like an insanely complicated way of doing almost nothing, but bare with me and try to envision real services in a large production system and how it applies there.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;First, let&amp;#8217;s create a &lt;code&gt;UserRepository&lt;/code&gt; (&lt;span class=&quot;caps&quot;&gt;DAO&lt;/span&gt;) implementation.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
// a dummy service that is not persisting anything
// solely prints out info
class UserRepository {
  def authenticate(user: User): User = { 
    println(&quot;authenticating user: &quot; + user)
    user
   }
  def create(user: User) = println(&quot;creating user: &quot; + user)
  def delete(user: User) = println(&quot;deleting user: &quot; + user)
}
&lt;/pre&gt;
&lt;p&gt;Here we could have split up the implementation in a trait interface and its implementation, but in order to keep things simple I didn&amp;#8217;t see the need.&lt;/p&gt;
&lt;p&gt;Now let&amp;#8217;s create a user service (also a dummy one, merely redirecting to our repository).&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
class UserService {
  def authenticate(username: String, password: String): User = 
    userRepository.authenticate(username, password)  

  def create(username: String, password: String) = 
    userRepository.create(new User(username, password))

  def delete(user: User) = All is statically typed.  
    userRepository.delete(user)
}
&lt;/pre&gt;
&lt;p&gt;Here you can see that we are referencing an instance of the &lt;code&gt;UserRepository&lt;/code&gt;. This is the dependency that we would like to have injected for us.&lt;/p&gt;
&lt;p&gt;Ok. Now the interesting stuff starts.  Let&amp;#8217;s first wrap the &lt;code&gt;UserRepository&lt;/code&gt; in an enclosing trait and instantiate the user repository there.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
trait UserRepositoryComponent {
  val userRepository = new UserRepository
  class UserRepository {
    def authenticate(user: User): User = { 
      println(&quot;authenticating user: &quot; + user)
      user
    }
    def create(user: User) = println(&quot;creating user: &quot; + user)
    def delete(user: User) = println(&quot;deleting user: &quot; + user)
  }
} 
&lt;/pre&gt;
&lt;p&gt;This simply creates a component namespace for our repository. Why? Stay with me and I&amp;#8217;ll show you how to make use of this namespace in a second.&lt;/p&gt;
&lt;p&gt;Now let&amp;#8217;s look at the &lt;code&gt;UserService&lt;/code&gt;, the user of the repository. In order to declare that we would like to have the &lt;code&gt;userRepository&lt;/code&gt; instance injected in the &lt;code&gt;UserService&lt;/code&gt; we will first do what we did with the repository above; wrap the it in an enclosing (namespace) trait and use a so-called &lt;a href=&quot;http://www.scala-lang.org/node/124&quot;&gt;self-type annotation&lt;/a&gt; to declare our need for the &lt;code&gt;UserRepository&lt;/code&gt; service. Sounds more complicated than it is. Let&amp;#8217;s look at the code.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
// using self-type annotation declaring the dependencies this 
// component requires, in our case the UserRepositoryComponent
trait UserServiceComponent { this: UserRepositoryComponent =&amp;gt;
  val userService = new UserService  
  class UserService {
    def authenticate(username: String, password: String): User = 
      userRepository.authenticate(username, password)  
    def create(username: String, password: String) = 
      userRepository.create(new User(username, password))
    def delete(user: User) = userRepository.delete(user)
  }
}
&lt;/pre&gt;
&lt;p&gt;The self-type annotation we are talking about is this code snippet:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
this: UserRepositoryComponent =&amp;gt;
&lt;/pre&gt;
&lt;p&gt;If you need to declare more than one dependency then you can compose the annotations like this:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
this: Foo with Bar with Baz =&amp;gt;
&lt;/pre&gt;
&lt;p&gt;Ok. Now we have declared the &lt;code&gt;UserRepository&lt;/code&gt; dependency. What is left is the actual wiring.&lt;/p&gt;
&lt;p&gt;In order to do that the only thing we need to do is to merge/join the different namespaces into one single application (or module) namespace. This is done by creating a &amp;#8220;module&amp;#8221; object composed of all our components. When we do that all wiring is happening automatically.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
object ComponentRegistry extends
  UserServiceComponent with
  UserRepositoryComponent 
&lt;/pre&gt;
&lt;p&gt;One of the beauties here is that all wiring is statically typed. For example, if we have a dependency declaration missing, if it is misspelled or something else is screwed up then we get a compilation error. This also makes it very fast.&lt;/p&gt;
&lt;p&gt;Another beauty is that everything is immutable (all dependencies are declared as &lt;code&gt;val&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;In order to use the application we only need to get the &amp;#8220;top-level&amp;#8221; component from the registry, and all other dependencies are wired for us (similar to how Guice/Spring works).&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
val userService = ComponentRegistry.userService
...
val user = userService.authenticate(..) 
&lt;/pre&gt;
&lt;p&gt;So far so good?&lt;/p&gt;
&lt;p&gt;Well, no. This sucks.&lt;/p&gt;
&lt;p&gt;We have strong coupling between the service implementation and its creation, the wiring configuration is scattered all over our code base; utterly inflexible.&lt;/p&gt;
&lt;p&gt;Let&amp;#8217;s fix it.&lt;/p&gt;
&lt;p&gt;Instead of instantiating the services in their enclosing component trait, let&amp;#8217;s change it to an abstract member field.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
trait UserRepositoryComponent {
  val userRepository: UserRepository

  class UserRepository {
    ...
  }
} 
&lt;/pre&gt;

&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
trait UserServiceComponent { 
  this: UserRepositoryComponent =&amp;gt; 

  val userService: UserService  

  class UserService {
    ... 
  }
}
&lt;/pre&gt;
&lt;p&gt;Now, we can move the instantiation (and configuration) of the services to the &lt;code&gt;ComponentRegistry&lt;/code&gt; module.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
object ComponentRegistry extends 
  UserServiceComponent with 
  UserRepositoryComponent 
{
  val userRepository = new UserRepository
  val userService = new UserService
}
&lt;/pre&gt;

&lt;p&gt;By doing this switch we have now abstracted away the actual component instantiation as well as the wiring into a single &amp;#8220;configuration&amp;#8221; object.&lt;/p&gt;
&lt;p&gt;The neat thing is that we can here switch between different implementations of the services (if we had defined an interface trait and multiple implementations). But even more interestingly, we can create multiple &amp;#8220;worlds&amp;#8221; or &amp;#8220;environments&amp;#8221; by simply composing the traits in different combinations.&lt;/p&gt;
&lt;p&gt;To show you what I mean, we&amp;#8217;ll now create a &amp;#8220;testing environment&amp;#8221; to be used during unit testing.&lt;/p&gt;
&lt;p&gt;Now, instead of instantiating the actual services we instead create mocks to each one of them. We also change the &amp;#8220;world&amp;#8221; to a trait (why, I will show you in a second).&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
trait TestingEnvironment extends
  UserServiceComponent with
  UserRepositoryComponent with 
  org.specs.mock.JMocker
{
  val userRepository = mock(classOf[UserRepository])
  val userService = mock(classOf[UserService])
}
&lt;/pre&gt;
&lt;p&gt;Here we are not merely creating mocks but the mocks we create are wired in as the declared dependencies wherever defined.&lt;/p&gt;
&lt;p&gt;Ok, now comes the fun part. Let&amp;#8217;s create a unit test in which we are mixing in the &lt;code&gt;TestEnvironment&lt;/code&gt; mixin, which is holding all our mocks.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
class UserServiceSuite extends TestNGSuite with TestEnvironment {

  @Test { val groups=Array(&quot;unit&quot;) }
  def authenticateUser = {

    // create a fresh and clean (non-mock) UserService 
    // (who's userRepository is still a mock)
    val userService = new UserService

    // record the mock invocation
    expect {
      val user = new User(&quot;test&quot;, &quot;test&quot;)
      one(userRepository).authenticate(user) willReturn user
    }
    
    ... // test the authentication method
  }
  
  ...
}
&lt;/pre&gt;
&lt;p&gt;This pretty much sums it up and is just one example on how you can compose your components in the way you want.&lt;/p&gt;
&lt;h3&gt;Other alternatives&lt;/h3&gt;
&lt;p&gt;Let&amp;#8217;s now take a look at some other ways of doing DI in Scala. This post is already pretty long and therefore I will only walk through the techniques very briefly, but it will hopefully be enough for you to understand how it is done. I have based all these remaining examples on the same little dummy program to make it easier to digest and to compare (taken from some discussion found on the Scala User mailing list). In all these examples you can just copy the code and run it in the Scala interpreter, in case you want to play with it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Using structural typing&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This technique using &lt;a href=&quot;http://scala.sygneca.com/patterns/duck-typing-done-right&quot;&gt;structural typing&lt;/a&gt; was posted by Jamie Webb on the Scala User mailing list some time ago. I like this approach; elegant, immutable, type-safe.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
// =======================
// service interfaces
trait OnOffDevice {
  def on: Unit
  def off: Unit
}
trait SensorDevice {
  def isCoffeePresent: Boolean
}

// =======================
// service implementations
class Heater extends OnOffDevice {
  def on = println(&quot;heater.on&quot;)
  def off = println(&quot;heater.off&quot;)
}
class PotSensor extends SensorDevice {
  def isCoffeePresent = true
}

// =======================
// service declaring two dependencies that it wants injected,
// is using structural typing to declare its dependencies
class Warmer(env: {
  val potSensor: SensorDevice
  val heater: OnOffDevice
}) {
  def trigger = {
    if (env.potSensor.isCoffeePresent) env.heater.on
    else env.heater.off
  }
}

class Client(env : { val warmer: Warmer }) {
  env.warmer.trigger
}

// =======================
// instantiate the services in a configuration module 
object Config {
  lazy val potSensor = new PotSensor
  lazy val heater = new Heater
  lazy val warmer = new Warmer(this) // this is where injection happens
}

new Client(Config)
&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Using implicit declarations&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This approach is simple and straight-forward. But I don&amp;#8217;t really like that the actual wiring (importing the implicit declarations) is scattered and tangled with the application code.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
// =======================
// service interfaces
trait OnOffDevice {
  def on: Unit
  def off: Unit
}
trait SensorDevice {
  def isCoffeePresent: Boolean
}

// =======================
// service implementations
class Heater extends OnOffDevice {
  def on = println(&quot;heater.on&quot;)
  def off = println(&quot;heater.off&quot;)
}
class PotSensor extends SensorDevice {
  def isCoffeePresent = true
}

// =======================
// service declaring two dependencies that it wants injected
class Warmer(
  implicit val sensor: SensorDevice, 
  implicit val onOff: OnOffDevice) {

  def trigger = {
    if (sensor.isCoffeePresent) onOff.on
    else onOff.off
  }
}

// =======================
// instantiate the services in a module 
object Services {
  implicit val potSensor = new PotSensor
  implicit val heater = new Heater
}

// =======================
// import the services into the current scope and the wiring 
// is done automatically using the implicits
import Services._

val warmer = new Warmer
warmer.trigger
&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Using Google Guice&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Scala works nicely with separate DI frameworks and early on we were using &lt;a href=&quot;http://code.google.com/p/google-guice/&quot;&gt;Google Guice&lt;/a&gt;. You can use Guice in many different ways, but here we will discuss a slick technique based on a &lt;code&gt;ServiceInjector&lt;/code&gt; mixin that my Jan Kriesten showed me.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
// =======================
// service interfaces
trait OnOffDevice {
  def on: Unit
  def off: Unit
}
trait SensorDevice {
  def isCoffeePresent: Boolean
}
trait IWarmer {
  def trigger
}
trait Client

// =======================
// service implementations
class Heater extends OnOffDevice {
  def on = println(&quot;heater.on&quot;)
  def off = println(&quot;heater.off&quot;)
}
class PotSensor extends SensorDevice {
  def isCoffeePresent = true
}
class @Inject Warmer(
  val potSensor: SensorDevice, 
  val heater: OnOffDevice) 
  extends IWarmer {

  def trigger = {
    if (potSensor.isCoffeePresent) heater.on
    else heater.off
  }
}

// =======================
// client
class @Inject Client(val warmer: Warmer) extends Client {
  warmer.trigger
}

// =======================
// Guice's configuration class that is defining the 
// interface-implementation bindings 
class DependencyModule extends Module {
  def configure(binder: Binder) = {
    binder.bind(classOf[OnOffDevice]).to(classOf[Heater])
    binder.bind(classOf[SensorDevice]).to(classOf[PotSensor])
    binder.bind(classOf[IWarmer]).to(classOf[Warmer])
    binder.bind(classOf[Client]).to(classOf[MyClient])
  }
}

// =======================
// Usage: val bean = new Bean with ServiceInjector
trait ServiceInjector {
  ServiceInjector.inject(this)
}

// helper companion object 
object ServiceInjector {
  private val injector = Guice.createInjector(
    Array[Module](new DependencyModule))
  def inject(obj: AnyRef) = injector.injectMembers(obj)
}

// =======================
// mix-in the ServiceInjector trait to perform injection
// upon instantiation
val client = new MyClient with ServiceInjector

println(client)
&lt;/pre&gt;
&lt;p&gt;That sums up what I had planned to go through in this article. I hope that you have gained some insight in how one can do DI in Scala, either using language abstractions or a separate DI framework. What works best for you is up to your use-case, requirements and taste.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Update: &lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Below I have added a Cake Pattern version of the last example for easier comparison between the different DI strategies. Just a note, if you compare the different strategies using this naive example then the Cake Pattern might look a bit overly complicated with its nested (namespace) traits, but it really starts to shine when you have a less then trivial example with many components with more or less complex dependencies to manage.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
// =======================
// service interfaces
trait OnOffDeviceComponent {
  val onOff: OnOffDevice
  trait OnOffDevice {
    def on: Unit
    def off: Unit
  }
}
trait SensorDeviceComponent {
  val sensor: SensorDevice
  trait SensorDevice {
    def isCoffeePresent: Boolean
  }
}

// =======================
// service implementations
trait OnOffDeviceComponentImpl extends OnOffDeviceComponent {
  class Heater extends OnOffDevice {
    def on = println(&quot;heater.on&quot;)
    def off = println(&quot;heater.off&quot;)
  }
}
trait SensorDeviceComponentImpl extends SensorDeviceComponent {
  class PotSensor extends SensorDevice {
    def isCoffeePresent = true
  }
}
// =======================
// service declaring two dependencies that it wants injected
trait WarmerComponentImpl {
  this: SensorDeviceComponent with OnOffDeviceComponent =&amp;gt;
  class Warmer {
    def trigger = {
      if (sensor.isCoffeePresent) onOff.on
      else onOff.off
    }
  }
}

// =======================
// instantiate the services in a module
object ComponentRegistry extends
  OnOffDeviceComponentImpl with
  SensorDeviceComponentImpl with
  WarmerComponentImpl {

  val onOff = new Heater
  val sensor = new PotSensor
  val warmer = new Warmer
}

// =======================
val warmer = ComponentRegistry.warmer
warmer.trigger
&lt;/pre&gt;</content>
 </entry>
 
 <entry>
   <title>Real-World Scala: Introduction</title>
   <link href="http://jonasboner.com/2008/10/01/real-world-scala-introduction.html"/>
   <updated>2008-10-01T00:00:00+02:00</updated>
   <id>http://jonasboner.com/2008/10/01/real-world-scala-introduction</id>
   <content type="html">&lt;h1&gt;
&lt;p&gt;Real-World Scala: Introduction&lt;/p&gt;
&lt;/h1&gt;
&lt;p&gt;The last nine months I have been running my own business together with some friends (&lt;a href=&quot;http://www.triental.com/&quot;&gt;Triental AB&lt;/a&gt;). We are building a product suite for private banking and wealth management with a focus on portfolio management, analysis and simulation.&lt;/p&gt;
&lt;p&gt;One of the great things of being your own is that you get to choose whatever technology you like and think is best suitable for the job. The last years I have been studying and playing with Functional Programming (FP) in general and &lt;a href=&quot;http://www.scala-lang.org/&quot;&gt;Scala&lt;/a&gt; in particular (among with Erlang, Clojure and Haskell). FP has been used successfully in the financial domain before (for example &lt;a href=&quot;http://ocaml.janestcapital.com/&quot;&gt;Jane Street Capital (OCaml)&lt;/a&gt; and &lt;a href=&quot;http://labs.businessobjects.com/cal/&quot;&gt;Business Objects (&lt;span class=&quot;caps&quot;&gt;CAL&lt;/span&gt;)&lt;/a&gt;), and the work we do is heavily based on mathematics which maps excellent to the FP paradigm.&lt;/p&gt;
&lt;p&gt;Apart from the FP properties (such as immutability, high-order functions, closures etc.) Scala also have some other interesting properties such as:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Mixin composition (enables creation of components build up of reusable fragments, even runtime composition)&lt;/li&gt;
	&lt;li&gt;Actors library (message-passing concurrency, an easy way of parallelizing long-running computations and simulations out on multi-core or &lt;span class=&quot;caps&quot;&gt;SMP&lt;/span&gt; machines)&lt;/li&gt;
	&lt;li&gt;Flexible syntax with decent type inference (high productivity, great for DSLs etc.)&lt;/li&gt;
	&lt;li&gt;Statically typed (fast, in most cases as fast as Java)&lt;/li&gt;
	&lt;li&gt;Pattern matching&lt;/li&gt;
	&lt;li&gt;Seamless interoperability with Java&lt;/li&gt;
	&lt;li&gt;and much much more&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;So I decided to try use FP and Scala for real.&lt;/p&gt;
&lt;p&gt;By choosing to base the development on FP and a new and fairly unproven (at least in the industry) language like Scala, we were exposing ourselves to two main risks:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Technology: will the technology deliver, can we fix or work around the problems that will emerge down the road etc.?&lt;/li&gt;
	&lt;li&gt;Education: will the process and time needed to be invested in learning a new language and paradigm slow us down too much?&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;And will the benefit of using it in terms of:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;higher productivity,&lt;/li&gt;
	&lt;li&gt;cleaner, more stable and more reusable code, and&lt;/li&gt;
	&lt;li&gt;more fun&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;outweigh the potential risks and upfront time (and money) investment?&lt;/p&gt;
&lt;p&gt;To be honest, the trip has been a bit bumpy sometimes, but now after nine months of development I can say that Scala pulled it off. Both of these risks were manageable. We are very happy with the strategic decision to use Scala.&lt;/p&gt;
&lt;p&gt;Technology-wise, one of the biggest problems of using Scala in a &lt;span class=&quot;caps&quot;&gt;JEE&lt;/span&gt; application stack is that there are (currently) no frameworks, patterns or &amp;#8220;best-practices&amp;#8221; that will help you address fundamental issues like:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Dependency Injection (DI)&lt;/li&gt;
	&lt;li&gt;Code tangling and scattering e.g. &lt;span class=&quot;caps&quot;&gt;AOP&lt;/span&gt;&lt;/li&gt;
	&lt;li&gt;Transaction demarcation and context propagation&lt;/li&gt;
	&lt;li&gt;Component life-cycle&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Basically, we didn&amp;#8217;t have a &amp;#8220;container&amp;#8221; that could handle this for us so we had to write it ourselves. The good thing is that most Java frameworks works very nicely with Scala. For example, we have had using no problems using &lt;span class=&quot;caps&quot;&gt;JPA&lt;/span&gt;, Wicket etc. and deploy it in a standard &lt;span class=&quot;caps&quot;&gt;JEE&lt;/span&gt; appserver.&lt;/p&gt;
&lt;p&gt;Regarding the second risk; education, it turned out to not be much of an issue. Our developers who had never written a line in Scala and had very little experience with FP in general were fully up to speed in a couple of months. The first weeks there were some complaints but now they are loving it. Scala gives a smooth learning curve to FP since it, being a unique blend of the OO and FP paradigms, allows one to start with a very Java-esque imperative style of programming and gradually move towards a functional style. Now we have rewritten most of the imperative chunks of code that were written during the early education stages.&lt;/p&gt;
&lt;p&gt;This is the first post in a series of articles in which I will try to explain how we are bridging the &amp;#8220;Scala &amp;lt;&amp;#8212;&amp;gt; Real-World&amp;#8221; gap. I have to stress that these are by no means the only way to do things and perhaps not the best way of doing things, but simply the way we have solved our problems and what work for us. Hopefully it will also work for you.&lt;/p&gt;
&lt;p&gt;For those that are interested here is a list of the Scala frameworks that we are currently using:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Scala (for the domain model, persistence layer, service layer, facade layer and container code)&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://www.lag.net/configgy/&quot;&gt;Configgy&lt;/a&gt; (logging and configuration)&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://github.com/jboner/scala-otp/tree/master&quot;&gt;Scala &lt;span class=&quot;caps&quot;&gt;OTP&lt;/span&gt;&lt;/a&gt; (actor management)&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://liftweb.net&quot;&gt;Lift&lt;/a&gt; (misc util)&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://scalax.scalaforge.org/&quot;&gt;scalax&lt;/a&gt; (misc util)&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://www.artima.com/scalatest/&quot;&gt;ScalaTest&lt;/a&gt; (testing)&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://code.google.com/p/scalacheck/&quot;&gt;ScalaCheck&lt;/a&gt; (testing)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The rest is a fairly standard Java stack:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Wicket&lt;/li&gt;
	&lt;li&gt;Hibernate (&lt;span class=&quot;caps&quot;&gt;JPA&lt;/span&gt;)&lt;/li&gt;
	&lt;li&gt;Atomikos (&lt;span class=&quot;caps&quot;&gt;JTA&lt;/span&gt;)&lt;/li&gt;
	&lt;li&gt;Terracotta&lt;/li&gt;
	&lt;li&gt;Wicket-Push (Cometd)&lt;/li&gt;
	&lt;li&gt;Dojo&lt;/li&gt;
	&lt;li&gt;AspectJ&lt;/li&gt;
	&lt;li&gt;XStream&lt;/li&gt;
	&lt;li&gt;TestNG&lt;/li&gt;
	&lt;li&gt;DBUnit&lt;/li&gt;
	&lt;li&gt;EasyMock&lt;/li&gt;
	&lt;li&gt;MySQL&lt;/li&gt;
	&lt;li&gt;Jetty&lt;/li&gt;
	&lt;li&gt;Maven&lt;/li&gt;
	&lt;li&gt;Hudson&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The topics I am planning on covering are:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Dependency Injection&lt;/li&gt;
	&lt;li&gt;&lt;span class=&quot;caps&quot;&gt;AOP&lt;/span&gt;&lt;/li&gt;
	&lt;li&gt;Transaction demarcation (&lt;span class=&quot;caps&quot;&gt;JTA&lt;/span&gt;) and context propagation&lt;/li&gt;
	&lt;li&gt;Asynchronous event-driven components&lt;/li&gt;
	&lt;li&gt;&lt;span class=&quot;caps&quot;&gt;ORM&lt;/span&gt; (&lt;span class=&quot;caps&quot;&gt;JPA&lt;/span&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Stay tuned for the next article.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>The Book Is Out</title>
   <link href="http://jonasboner.com/2008/06/30/the-book-is-out.html"/>
   <updated>2008-06-30T00:00:00+02:00</updated>
   <id>http://jonasboner.com/2008/06/30/the-book-is-out</id>
   <content type="html">&lt;h1&gt;
&lt;p&gt;The Book Is Out&lt;/p&gt;
&lt;/h1&gt;
&lt;p&gt;&lt;a href=&quot;http://www.amazon.com/Definitive-Guide-Terracotta-Hibernate-Scalability/dp/1590599861&quot;&gt;The Definite Guide to Terracotta&lt;/a&gt; by me and my colleagues; &lt;a href=&quot;http://blog.terracottatech.com&quot;&gt;Ari&lt;/a&gt;, &lt;a href=&quot;http://rifers.org/blogs/gbevin&quot;&gt;Geert&lt;/a&gt;, &lt;a href=&quot;http://tech.puredanger.com/&quot;&gt;Alex&lt;/a&gt;, &lt;a href=&quot;http://orionl.blogspot.com/&quot;&gt;Orion&lt;/a&gt; and &lt;a href=&quot;http://javathink.blogspot.com/&quot;&gt;Taylor&lt;/a&gt;, is now available in the stores. &lt;br /&gt;
It is a pragmatic and practical book, with tons of real-world examples and stories, so if you want to learn how to use Terracotta for real then go and &lt;a href=&quot;http://www.amazon.com/Definitive-Guide-Terracotta-Hibernate-Scalability/dp/1590599861&quot;&gt;order a copy&lt;/a&gt;.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Erlang-style Supervisor Module for Scala Actors</title>
   <link href="http://jonasboner.com/2008/06/16/erlang-style-supervisor-module-for-scala-actors.html"/>
   <updated>2008-06-16T00:00:00+02:00</updated>
   <id>http://jonasboner.com/2008/06/16/erlang-style-supervisor-module-for-scala-actors</id>
   <content type="html">&lt;h1&gt;
&lt;p&gt;Erlang-style Supervisor Module for Scala Actors&lt;/p&gt;
&lt;/h1&gt;
&lt;p&gt;In this post I will explain how you can build fault-tolerant systems using Scala Actors by arranging them in Supervisor hierarchies using a library for Scala Supervisors that I just released.&lt;/p&gt;
&lt;p&gt;But first, let&amp;#8217;s recap what Actors are and what makes them useful.&lt;/p&gt;
&lt;p&gt;An actor is an abstraction that implements &lt;a href=&quot;http://c2.com/cgi/wiki?MessagePassingConcurrency&quot;&gt;Message-Passing Concurrency&lt;/a&gt;. Actors have no shared state and are communicating by sending and receiving messages. This is a paradigm that provides a very different and much simpler concurrency model than &lt;a href=&quot;http://c2.com/cgi/wiki?SharedStateConcurrency&quot;&gt;Shared-State Concurrency&lt;/a&gt; (the scheme adopted by C, Java, C# etc.) and making it easier to avoid problems like deadlocks, live locks, thread starvation etc. This makes it possible to write code that is deterministic and &lt;a href=&quot;http://en.wikipedia.org/wiki/Side_effect_%28computer_science%29&quot;&gt;side-effect-free&lt;/a&gt;, something that makes easier to write, test, understand and reason about. Each actor has a mailbox in which it receives incoming messages and can use pattern matching on the messages to decide if a message is interesting and which action to take.  The most well known and successful implementation of actors can be found in the Erlang language (and the &lt;span class=&quot;caps&quot;&gt;OTP&lt;/span&gt; platform) where it has been used to implement extremely fault tolerant (&lt;a href=&quot;http://ll2.ai.mit.edu/talks/armstrong.pdf &quot;&gt;99.9999999% reliability &amp;#8211; 9 nines&lt;/a&gt;) and massively concurrent systems (with hundreds of thousand simultaneous actors).&lt;/p&gt;
&lt;p&gt;So what are Supervisor hierarchies? Let&amp;#8217;s go to the source; &lt;a href=&quot;http://www.erlang.org/doc/design_principles/sup_princ.html#5&quot;&gt;http://www.erlang.org/doc/design_principles/sup_princ.html#5&lt;/a&gt;.&lt;/p&gt;
&lt;blockquote&gt;A supervisor is responsible for starting, stopping and monitoring its child processes. The basic idea of a supervisor is that it should keep its child processes alive by restarting them when necessary.&lt;/blockquote&gt;
&lt;p&gt;It has two different restart strategies; &lt;em&gt;All-For-One&lt;/em&gt; and &lt;em&gt;One-For-One&lt;/em&gt;. Best explained using some pictures (referenced from erlang.org):&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;OneForOne&lt;/strong&gt;&lt;br /&gt;
&lt;img src=&quot;http://www.erlang.org/doc/design_principles/sup4.gif&quot; alt=&quot;OneForOne&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;AllForOne&lt;/strong&gt;&lt;br /&gt;
&lt;img src=&quot;http://www.erlang.org/doc/design_principles/sup5.gif&quot; alt=&quot;AllForOne&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Naturally, the library I have written for Scala is by no means as complete and hardened as Erlang&amp;#8217;s, but it seems to do a decent job in providing the core functionality.&lt;/p&gt;
&lt;p&gt;The implementation consists of two main abstractions; &lt;code&gt;Supervisor&lt;/code&gt; and &lt;code&gt;GenericServer&lt;/code&gt;.&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;The Supervisor manages hierarchies of Scala actors and provides fault-tolerance in terms of different restart semantics. The configuration and semantics is almost a 1-1 port of the Erlang Supervisor implementation, explained in the &lt;a href=&quot;http://erlang.org&quot;&gt;erlang.org&lt;/a&gt; doc referenced above. Read this document in order to understand how to configure the Supervisor properly.&lt;/li&gt;
&lt;/ul&gt;
&lt;ul&gt;
	&lt;li&gt;The GenericServer (which subclasses the Actor class) is a trait that forms the base for a server to be managed by a Supervisor.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The GenericServer is wrapped by a GenericServerContainer instance providing a necessary indirection needed to be able to fully manage the life-cycle of the GenericServer in an easy way.&lt;/p&gt;
&lt;p&gt;So, let&amp;#8217;s try it out by writing a small example in which we create a couple of servers, configure them, use them in various ways, kill one of them, see it recover, hotswap its implementation etc.&lt;/p&gt;
&lt;p&gt;(Sidenote: I have &lt;a href=&quot;http://jonasboner.com/2007/12/19/hotswap-code-using-scala-and-actors.html&quot;&gt;written about hotswapping actors&lt;/a&gt; before, however this library has taken this approach a but further and provides a more flexible and powerful way of achieving this. Thanks &lt;a href=&quot;http://blog.lostlake.org/&quot;&gt;&lt;span class=&quot;caps&quot;&gt;DPP&lt;/span&gt;&lt;/a&gt;.)&lt;/p&gt;
&lt;p&gt;This walk-through will only cover some of the &lt;span class=&quot;caps&quot;&gt;API&lt;/span&gt;, for more details look at the code or the tests.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Create our server messages&lt;/strong&gt;&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
import scala.actors._
import scala.actors.Actor._

import com.jonasboner.supervisor._
import com.jonasboner.supervisor.Helpers._

sealed abstract class SampleMessage
case object Ping extends SampleMessage
case object Pong extends SampleMessage
case object OneWay extends SampleMessage
case object Die extends SampleMessage
&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;2. Create a &lt;code&gt;GenericServer&lt;/code&gt;&lt;/strong&gt;&lt;br /&gt;
We do that by extending the &lt;code&gt;GenericServer&lt;/code&gt; trait and override the &lt;code&gt;body&lt;/code&gt; method.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
class SampleServer extends GenericServer {

  // This method implements the core server logic and naturally has to be overridden
  override def body: PartialFunction[Any, Unit] = {
    case Ping =&amp;gt; 
      println(&quot;Received Ping&quot;); reply(Pong)

    case OneWay =&amp;gt; 
      println(&quot;Received OneWay&quot;)

    case Die =&amp;gt; 
      println(&quot;Received Die..dying...&quot;) 
      throw new RuntimeException(&quot;Received Die message&quot;)
  }

}
&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;GenericServer&lt;/code&gt; also has some callback life-cycle methods, such as &lt;code&gt;init(..)&lt;/code&gt; and &lt;code&gt;shutdown(..)&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;3. Wrap our &lt;code&gt;SampleServer&lt;/code&gt; in a &lt;code&gt;GenericServerContainer&lt;/code&gt;&lt;/strong&gt;&lt;br /&gt;
Here we also give it a name to be able to refer to it later. We are creating two instances of the same server impl in order to try out multiple server restart in case of failure.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
object sampleServer1 extends GenericServerContainer(&quot;sample1&quot;, () =&amp;gt; new SampleServer)
object sampleServer2 extends GenericServerContainer(&quot;sample2&quot;, () =&amp;gt; new SampleServer)
&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;4. Create a &lt;code&gt;Supervisor&lt;/code&gt; configuration&lt;/strong&gt;&lt;br /&gt;
Here we create a &lt;code&gt;SupervisorFactory&lt;/code&gt; that is configuring our servers. The configuration mimics the Erlang configuration and defines a general restart strategy for our &lt;code&gt;Supervisor&lt;/code&gt; as well as a list of workers (servers) which for each we define a specific life-cycle.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
object factory extends SupervisorFactory {
  override protected def getSupervisorConfig: SupervisorConfig = {
    SupervisorConfig(
      RestartStrategy(AllForOne, 3, 10000),
       Worker(
        sampleServer1,
        LifeCycle(Permanent, 1000)) ::
       Worker(
        sampleServer2,
        LifeCycle(Permanent, 1000)) ::
      Nil)
  }
}
&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;5. Create a new &lt;code&gt;Supervisor&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
val supervisor = factory.newSupervisor
&lt;/pre&gt;
&lt;p&gt;Output: &lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;&lt;br /&gt;
12:25:30.031 [Thread-2] &lt;span class=&quot;caps&quot;&gt;DEBUG&lt;/span&gt; com.jonasboner.supervisor.Supervisor &amp;#8211; Configuring supervisor:com.jonasboner.supervisor.Supervisor@860d49&lt;br /&gt;
12:25:30.046 [Thread-2] &lt;span class=&quot;caps&quot;&gt;DEBUG&lt;/span&gt; com.jonasboner.supervisor.Supervisor &amp;#8211; Linking actor [Main$SampleServer$1@1b9240e] to supervisor [com.jonasboner.supervisor.Supervisor@860d49]&lt;br /&gt;
12:25:30.062 [Thread-2] &lt;span class=&quot;caps&quot;&gt;DEBUG&lt;/span&gt; com.jonasboner.supervisor.Supervisor &amp;#8211; Linking actor [Main$SampleServer$1@1808199] to supervisor [com.jonasboner.supervisor.Supervisor@860d49]&lt;br /&gt;
12:25:30.062 [main] &lt;span class=&quot;caps&quot;&gt;DEBUG&lt;/span&gt; Main$factory$2$ &amp;#8211; Supervisor successfully configured&lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;6. Start the &lt;code&gt;Supervisor&lt;/code&gt;&lt;/strong&gt;&lt;br /&gt;
This also starts the servers.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
supervisor ! Start
&lt;/pre&gt;
&lt;p&gt;Output: &lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;&lt;br /&gt;
12:25:30.078 [Thread-8] &lt;span class=&quot;caps&quot;&gt;INFO&lt;/span&gt;  com.jonasboner.supervisor.Supervisor &amp;#8211; Starting server: Main$sampleServer2$2$&lt;code&gt;1479feb
12:25:30.078 [Thread-8] INFO  com.jonasboner.supervisor.Supervisor - Starting server: Main$sampleServer1$2$&lt;/code&gt;97a560&lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;7. Try to communicate with the servers.&lt;/strong&gt;&lt;br /&gt;
Here we try to send a couple one way asynchronous messages to our servers. &lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;&lt;br /&gt;
sampleServer1 ! OneWay&lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;Try to get a reference to our sampleServer2 (by name) from the Supervisor before sending a message.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
supervisor.getServer(&quot;sample2&quot;) match {
  case Some(server2) =&amp;gt; server2 ! OneWay
  case None =&amp;gt; println(&quot;server [sample2] could not be found&quot;)
}
&lt;/pre&gt;
&lt;p&gt;Output: &lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;&lt;br /&gt;
Received OneWay&lt;br /&gt;
Received OneWay&lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;8. Send a message using a future&lt;/strong&gt;&lt;br /&gt;
Try to send an asynchronous message &amp;#8211; receive a future &amp;#8211; and wait 100 ms (time-out) for the reply.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
val future = sampleServer1 !! Ping
val reply1 = future.receiveWithin(100) match {
  case Some(reply) =&amp;gt; 
    println(&quot;Received reply: &quot; + reply)
  case None =&amp;gt; 
    println(&quot;Did not get a reply witin 100 ms&quot;)
}
&lt;/pre&gt;
&lt;p&gt;Output: &lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;&lt;br /&gt;
Received Ping&lt;br /&gt;
Received reply: Pong&lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;9. Kill one of the servers&lt;/strong&gt;&lt;br /&gt;
Try to send a message (Die) telling the server to kill itself (by throwing an exception).&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
sampleServer1 ! Die
&lt;/pre&gt;
&lt;p&gt;Output: &lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;&lt;br /&gt;
Received Die..dying&amp;#8230;&lt;br /&gt;
12:25:30.093 [Thread-8] &lt;span class=&quot;caps&quot;&gt;ERROR&lt;/span&gt; c.j.supervisor.AllForOneStrategy &amp;#8211; Server [Main$SampleServer$1@1b9240e] has failed due to [java.lang.RuntimeException: Received Die message] &amp;#8211; scheduling restart &amp;#8211; scheme: ALL_FOR_ONE.&lt;br /&gt;
12:25:30.093 [Thread-8] &lt;span class=&quot;caps&quot;&gt;DEBUG&lt;/span&gt; Main$sampleServer2$2$ &amp;#8211; Waiting 1000 milliseconds for the server to shut down before killing it.&lt;br /&gt;
12:25:30.093 [Thread-8] &lt;span class=&quot;caps&quot;&gt;DEBUG&lt;/span&gt; Main$sampleServer2$2$ &amp;#8211; Server [sample2] has been shut down cleanly.&lt;br /&gt;
12:25:30.093 [Thread-8] &lt;span class=&quot;caps&quot;&gt;DEBUG&lt;/span&gt; c.j.supervisor.AllForOneStrategy &amp;#8211; Restarting server [sample2] configured as &lt;span class=&quot;caps&quot;&gt;PERMANENT&lt;/span&gt;.&lt;br /&gt;
12:25:30.093 [Thread-8] &lt;span class=&quot;caps&quot;&gt;DEBUG&lt;/span&gt; com.jonasboner.supervisor.Supervisor &amp;#8211; Linking actor [Main$SampleServer$1@166aa18] to supervisor [com.jonasboner.supervisor.Supervisor@860d49]&lt;br /&gt;
12:25:30.093 [Thread-8] &lt;span class=&quot;caps&quot;&gt;DEBUG&lt;/span&gt; Main$sampleServer1$2$ &amp;#8211; Waiting 1000 milliseconds for the server to shut down before killing it.&lt;br /&gt;
12:25:30.093 [main] &lt;span class=&quot;caps&quot;&gt;DEBUG&lt;/span&gt; com.jonasboner.supervisor.Helpers$ &amp;#8211; Future timed out while waiting for actor: Main$SampleServer$1@1b9240e&lt;br /&gt;
Expected exception: java.lang.RuntimeException: Time-out&lt;br /&gt;
12:25:31.093 [Thread-8] &lt;span class=&quot;caps&quot;&gt;DEBUG&lt;/span&gt; c.j.supervisor.AllForOneStrategy &amp;#8211; Restarting server [sample1] configured as &lt;span class=&quot;caps&quot;&gt;PERMANENT&lt;/span&gt;.&lt;br /&gt;
12:25:31.093 [Thread-8] &lt;span class=&quot;caps&quot;&gt;DEBUG&lt;/span&gt; com.jonasboner.supervisor.Supervisor &amp;#8211; Linking actor [Main$SampleServer$1@1968e23] to supervisor [com.jonasboner.supervisor.Supervisor@860d49]&lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;10. Send an asyncronous message and wait on a future.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If this call times out, the error handler we define will be invoked &amp;#8211; in this case throw an exception. It is likely that this call will time out since the server is in the middle of recovering from failure and we are on purpose defining a very short time-out to trigger this behavior.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
val reply2 = try {
  sampleServer1 !!! (Ping, throw new RuntimeException(&quot;Time-out&quot;), 10) 
} catch { case e =&amp;gt; println(&quot;Expected exception: &quot; + e.toString); Pong } 
&lt;/pre&gt;
&lt;p&gt;The output of this call (due to the async nature of actors) is interleaved with the logging for the restart of the servers. As you can see the log below can be found in the middle of the restart output.  &lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;&lt;br /&gt;
12:25:30.093 [main] &lt;span class=&quot;caps&quot;&gt;DEBUG&lt;/span&gt; com.jonasboner.supervisor.Helpers$ &amp;#8211; Future timed out while waiting for actor: Main$SampleServer$1@1b9240e&lt;br /&gt;
Expected exception: java.lang.RuntimeException: Time-out&lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;Server should be up again. Try the same call again&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
val reply3 = try {
  sampleServer1 !!! (Ping, throw new RuntimeException(&quot;Time-out&quot;), 1000) 
} catch { case e =&amp;gt; println(&quot;Expected exception: &quot; + e.toString); Pong } 
&lt;/pre&gt;
&lt;p&gt;Output: &lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;&lt;br /&gt;
Received Ping&lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;Also check that server number 2 is up and healthy.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
sampleServer2 ! Ping 
&lt;/pre&gt;
&lt;p&gt;Output: &lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;&lt;br /&gt;
Received Ping&lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;11. Try to hotswap the server implementation&lt;/strong&gt;&lt;br /&gt;
Here we are passing in a completely new implementation of the server logic (doesn&amp;#8217;t look that different tough, but it can be any piece of scala pattern matching code) to the server&amp;#8217;s hotswap method.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
sampleServer1.hotswap(Some({
  case Ping =&amp;gt; 
    println(&quot;Hotswapped Ping&quot;)
}))
&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;12. Try the hotswapped server out&lt;/strong&gt;&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
sampleServer1 ! Ping
&lt;/pre&gt;
&lt;p&gt;Output: &lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;&lt;br /&gt;
Hotswapped Ping&lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;13. Hotswap again&lt;br /&gt;
&lt;/strong&gt;&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
sampleServer1.hotswap(Some({
  case Pong =&amp;gt; 
    println(&quot;Hotswapped again, now doing Pong&quot;)
    reply(Ping)
}))
&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;14. Send an asyncronous message that will wait on a future (using a different syntax/method).&lt;/strong&gt;&lt;br /&gt;
Method returns an &lt;code&gt;Option[T]&lt;/code&gt; which can be of two different types; &lt;code&gt;Some(result)&lt;/code&gt; or &lt;code&gt;None&lt;/code&gt;. If we receive &lt;code&gt;Some(result)&lt;/code&gt; then we return the result, but if &lt;code&gt;None&lt;/code&gt; is received then we invoke the error handler that we define in the &lt;code&gt;getOrElse&lt;/code&gt; method. In this case print out an info message (but you could throw an exception or do whatever you like&amp;#8230;) and return a default value (&lt;code&gt;Ping&lt;/code&gt;).&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
val reply4 = (sampleServer1 !!! Pong).getOrElse({
  println(&quot;Time out when sending Pong&quot;)
  Ping
})
&lt;/pre&gt;
&lt;p&gt;Output: &lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;&lt;br /&gt;
Hotswapped again, now doing Pong&lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;Same invocation with pattern matching syntax.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
val reply5 = sampleServer1 !!! Pong match {
  case Some(result) =&amp;gt; result
  case None =&amp;gt; println(&quot;Time out when sending Pong&quot;); Ping  
}
&lt;/pre&gt;
&lt;p&gt;Output: &lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;&lt;br /&gt;
Hotswapped again, now doing Pong&lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;15. Hotswap back to original implementation.&lt;/strong&gt;&lt;br /&gt;
This is done by passing in &lt;code&gt;None&lt;/code&gt; to the hotswap method.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
sampleServer1.hotswap(None)
&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;16. Test the final hotswap&lt;/strong&gt;&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
sampleServer1 !  Ping
&lt;/pre&gt;
&lt;p&gt;Output: &lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;&lt;br /&gt;
Received Ping &lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;17. Shut down the supervisor and its server(s)&lt;/strong&gt;&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
supervisor ! Stop
&lt;/pre&gt;
&lt;p&gt;Output: &lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;&lt;br /&gt;
12:25:31.093 [Thread-6] &lt;span class=&quot;caps&quot;&gt;INFO&lt;/span&gt;  com.jonasboner.supervisor.Supervisor &amp;#8211; Stopping server: Main$sampleServer2$2$&lt;code&gt;1479feb
12:25:31.093 [Thread-6] INFO  com.jonasboner.supervisor.Supervisor - Stopping server: Main$sampleServer1$2$&lt;/code&gt;97a560&lt;br /&gt;
12:25:31.093 [Thread-6] &lt;span class=&quot;caps&quot;&gt;INFO&lt;/span&gt;  com.jonasboner.supervisor.Supervisor &amp;#8211; Stopping supervisor: com.jonasboner.supervisor.Supervisor@860d49&lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;You can find this code in the &lt;code&gt;sample.scala&lt;/code&gt; file in the root directory of the distribution. Run it by invoking:&lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;&lt;br /&gt;
scala -cp target/supervisor-0.3.jar:[dependency jars: slf4j and logback] sample.scala&lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Check out&lt;/strong&gt;&lt;br /&gt;
The &lt;span class=&quot;caps&quot;&gt;SCM&lt;/span&gt; system used is Git.&lt;/p&gt;
&lt;p&gt;1. Download and install &lt;a href=&quot;http://www.google.com/search?q=git&quot;&gt;Git&lt;/a&gt;&lt;br /&gt;
2. Invoke &lt;code&gt;git clone git@github.com:jboner/scala-supervisor.git&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Build it&lt;/strong&gt;&lt;br /&gt;
The build system used is Maven 2.&lt;/p&gt;
&lt;p&gt;1. Download and install &lt;a href=&quot;http://maven.apache.org/&quot;&gt;Maven 2&lt;/a&gt;. &lt;br /&gt;
2. Step into the root dir &lt;code&gt;scala-supervisor&lt;/code&gt;.&lt;br /&gt;
3. Invoke &lt;code&gt;mvn install&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;This will build the project, run all tests, create a jar and upload it to your local Maven repository ready for use.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Runtime dependencies&lt;/strong&gt;&lt;br /&gt;
Automatically downloaded my Maven.&lt;/p&gt;
&lt;p&gt;1. Scala 2.7.1-final&lt;br /&gt;
2. SLF4J 1.5.2&lt;br /&gt;
3. LogBack Classic 0.9.9&lt;/p&gt;
&lt;p&gt;That&amp;#8217;s all to it.&lt;/p&gt;
&lt;p&gt;Have fun.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>AOP-style Mixin Composition Stacks in Scala</title>
   <link href="http://jonasboner.com/2008/02/06/aop-style-mixin-composition-stacks-in-scala.html"/>
   <updated>2008-02-06T00:00:00+01:00</updated>
   <id>http://jonasboner.com/2008/02/06/aop-style-mixin-composition-stacks-in-scala</id>
   <content type="html">&lt;h1&gt;
&lt;p&gt;&lt;span class=&quot;caps&quot;&gt;AOP&lt;/span&gt;-style Mixin Composition Stacks in Scala&lt;/p&gt;
&lt;/h1&gt;
&lt;p&gt;Scala is one those great languages that is scalable. With scalable I mean that it is the language that grows with the user, that it makes simple things easy and hard things possible. A language that is easy to get started and to become productive in, but at the same time a deep language with very powerful constructs and abstractions.&lt;/p&gt;
&lt;p&gt;In this blog post I will try to highlight the power of &lt;a href=&quot;http://www.scala-lang.org/intro/mixin.html&quot;&gt;Scala&amp;#8217;s mixins&lt;/a&gt; and how you can use mixin composition to get &lt;span class=&quot;caps&quot;&gt;AOP&lt;/span&gt;/interceptor-like style of programming.&lt;/p&gt;
&lt;p&gt;First let&amp;#8217;s define our service interface, modeled as a mixin (in this case without an implementation so similar to Java&amp;#8217;s interface):&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
trait Stuff {
  def doStuff
}
&lt;/pre&gt;
&lt;p&gt;Now let&amp;#8217;s define two different mixin &amp;#8220;interceptors&amp;#8221; that implement the service interface. The first one manages logging and the other one transaction demarcation (but for simplicity I am just using a dummy mock for TX stuff for now):&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
trait LoggableStuff extends Stuff {
  abstract override def doStuff {
    println(&quot;logging enter&quot;)
    super.doStuff
    println(&quot;logging exit&quot;)
  }
}

trait TransactionalStuff extends Stuff {
  abstract override def doStuff {
    println(&quot;start TX&quot;)
    try {
      super.doStuff
      println(&quot;commit TX&quot;)      
    } catch {
      case e: Exception =&amp;gt; 
        println(&quot;rollback TX&quot;)   
    } 
  }
}
&lt;/pre&gt;
&lt;p&gt;As we can see in this example they both override the &lt;code&gt;Stuff.doStuff&lt;/code&gt; method. If we look more closely we can see that they follow the same pattern:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Enter method (&lt;tt&gt;doStuff&lt;/tt&gt;)&lt;/li&gt;
&lt;li&gt;Do something (log, start tx etc.)&lt;/li&gt;
&lt;li&gt;Invoke the same method on &lt;tt&gt;super&lt;/tt&gt; (&lt;tt&gt;super.doStuff&lt;/tt&gt;)&lt;/li&gt;
&lt;li&gt;Do something (log, commit tx etc.)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The trick here is in the semantics of the call to super. Here Scala will invoke the next mixin in a stack of mixins, e.g. the same method in the &amp;#8220;next&amp;#8221; mixin that have been mixed in. Exactly what f.e. &lt;a href=&quot;http://aspectj.org&quot;&gt;AspectJ&lt;/a&gt; does in its &lt;tt&gt;proceed(..)&lt;/tt&gt; method and what Spring does in its interceptors.&lt;/p&gt;
&lt;p&gt;But before we try this out, let&amp;#8217;s create a concrete implementation of our &lt;code&gt;Stuff&lt;/code&gt; service, called &lt;code&gt;RealStuff&lt;/code&gt;:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
class RealStuff {
  def doStuff = println(&quot;doing real stuff&quot;)
}
&lt;/pre&gt;
&lt;p&gt;Now we have everything we need, so let&amp;#8217;s fire up the Scala &lt;span class=&quot;caps&quot;&gt;REPL&lt;/span&gt; and create a component based on the &lt;code&gt;RealStuff&lt;/code&gt; class and a mixin stack with support for logging and transactionality. Scala&amp;#8217;s mixin composition can take place when we instantiate an instance, e.g. it allows us to mix in functionality into specific instances that object creation time for specific object instances.&lt;/p&gt;
&lt;p&gt;First let&amp;#8217;s create a plain &lt;code&gt;RealStuff&lt;/code&gt; instance and run it:&lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;&lt;br /&gt;
scala&amp;gt; import stacks._&lt;br /&gt;
import stacks._&lt;/p&gt;
&lt;p&gt;scala&amp;gt; val stuff = new RealStuff &lt;br /&gt;
stuff: stacks.RealStuff = $anon$1@6732d42&lt;/p&gt;
&lt;p&gt;scala&amp;gt; stuff.doStuff&lt;br /&gt;
doing real stuff&lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;Not too exciting, but let&amp;#8217;s do it again and this time mix in the &lt;code&gt;LoggableStuff&lt;/code&gt; mixin:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
scala&amp;gt; val stuff2 = new RealStuff with LoggableStuff 
stuff2: stacks.RealStuff with stacks.LoggableStuff = $anon$1@1082d45

scala&amp;gt; stuff2.doStuff
logging enter
doing real stuff
logging exit
&lt;/pre&gt;
&lt;p&gt;As you can see the call to &lt;code&gt;RealStuff.doStuff&lt;/code&gt; is intercepted and logging is added before we are invoking this method as well as after. Let&amp;#8217;s now add the &lt;code&gt;TransactionalStuff&lt;/code&gt; mixin:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
scala&amp;gt; val stuff3 = new RealStuff with LoggableStuff with TransactionalStuff
stuff3: stacks.RealStuff with stacks.LoggableStuff with stacks.TransactionalStuff = $anon$1@4512d65

scala&amp;gt; stuff3.doStuff
start TX
logging enter
doing real stuff
logging exit
commit TX
&lt;/pre&gt;
&lt;p&gt;As you can see, the semantics for this mixin stack is the exact same as you would get with stacking AspectJ aspects or Spring interceptors. Another interesting aspect is that the whole composition is statically compiled with all its benefits of compile time error detection, performance, potential tool support etc.&lt;/p&gt;
&lt;p&gt;This approach is similar to Rickard Oberg&amp;#8217;s idea on using the so-called &lt;a href=&quot;http://www.jroller.com/rickard/date/20031028&quot;&gt;Abstract Schema&lt;/a&gt; pattern for type-safe &lt;span class=&quot;caps&quot;&gt;AOP&lt;/span&gt; in plain Java.&lt;/p&gt;
&lt;p&gt;It is both simple and intuitive to change the order of the mixin &amp;#8220;interceptors&amp;#8221;, simply change the order in which they are applied to the target instance:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
scala&amp;gt; val stuff4 = new RealStuff with TransactionalStuff with LoggableStuff
stuff4: stacks.RealStuff with stacks.TransactionalStuff with stacks.LoggableStuff = $anon$1@a20232

scala&amp;gt; stuff4.doStuff
logging enter
start TX
doing real stuff
commit TX
logging exit
&lt;/pre&gt;
&lt;p&gt;Finally, just for fun, let&amp;#8217;s a create a mixin that can retry failing operations. This particular one will catch any exception that the service might throw and retry it three times before giving up:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
trait RetryStuff extends Stuff {
  abstract override def doStuff {
    var times = 0
    var retry = true
    while (retry) {
      try {
        super.doStuff      
        retry = false
      } catch {
        case e: Exception =&amp;gt; 
          if (times &amp;lt; 3) { // retry 3 times
            times += 1
            println(&quot;operation failed - retrying: &quot; + times)
          } else {
            retry = false
            throw e 
          }
      }
    }
  }
}&lt;/pre&gt;
&lt;p&gt;To test this behavior (as well as the &lt;em&gt;rollback&lt;/em&gt; feature in the &lt;code&gt;TransactionalStuff&lt;/code&gt;) we can change the &lt;code&gt;RealStuff.getStuff&lt;/code&gt; method to throw an exception:&lt;/p&gt;
&lt;p&gt;&lt;/pre&gt;&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;&lt;br /&gt;
class RealStuff {&lt;br /&gt;
  def doStuff {&lt;br /&gt;
    println(&amp;#8220;doing real stuff&amp;#8221;)&lt;br /&gt;
    throw new RuntimeException(&amp;#8220;expected&amp;#8221;)&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;Now we can try to add this mixin to the beginning of our our stack and run the service:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
scala&amp;gt; val stuff5 = new RealStuff with RetryStuff with TransactionalStuff  with LoggableStuff
stuff5: stacks.RealStuff with stacks.RetryStuff with stacks.LoggableStuff with stacks.TransactionalStuff = $anon$1@a927d45

scala&amp;gt; stuff5.doStuff
logging enter
start TX
doing real stuff
operation failed - retrying: 1
doing real stuff
operation failed - retrying: 2
doing real stuff
operation failed - retrying: 3
rollback TX
logging exit
&lt;/pre&gt;
&lt;p&gt;Pretty neat, right?&lt;/p&gt;
&lt;p&gt;That&amp;#8217;s all for now. In the next post I will cover a bunch of ways to use Scala&amp;#8217;s language primitives to do Dependency Injection (DI).&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Clustering Scala Actors with Terracotta</title>
   <link href="http://jonasboner.com/2008/01/25/clustering-scala-actors-with-terracotta.html"/>
   <updated>2008-01-25T00:00:00+01:00</updated>
   <id>http://jonasboner.com/2008/01/25/clustering-scala-actors-with-terracotta</id>
   <content type="html">&lt;h1&gt;
&lt;p&gt;Clustering Scala Actors with Terracotta&lt;/p&gt;
&lt;/h1&gt;
&lt;h2&gt;Introduction&lt;/h2&gt;
&lt;p&gt;A month ago I wrote an introductory post about &lt;a href=&quot;http://lamp.epfl.ch/~phaller/actors.html&quot;&gt;Scala Actors&lt;/a&gt;: &lt;a href=&quot;http://jonasboner.com/2007/12/19/hotswap-code-using-scala-and-actors.html&quot;&gt;HotSwap Code using Scala and Actors&lt;/a&gt;. For you who don&amp;#8217;t know what it is I don&amp;#8217;t want to start by reading the previous post let&amp;#8217;s briefly recap what Actors are and what you can use them for.&lt;/p&gt;
&lt;p&gt;An Actor is an abstraction that implements &lt;a href=&quot;http://c2.com/cgi/wiki?MessagePassingConcurrency&quot;&gt;Message-Passing Concurrency&lt;/a&gt;. Actors have no shared state and are communicating by sending and receiving messages. This is a paradigm that provides a very different and much simple concurrency model than &lt;a href=&quot;http://c2.com/cgi/wiki?SharedStateConcurrency&quot;&gt;Shared-State Concurrency&lt;/a&gt; (the scheme adopted by C, Java, C# etc.) and is avoiding most of the latter one&amp;#8217;s complexity and problems. This makes it possible to write code that is deterministic and side-effect-free, something that makes it easier to write, test, understand and reason about. Each Actor has a mailbox in which it receives incoming messages and normally uses pattern matching on the messages to decide if a message is interesting if action is needed.&lt;/p&gt;
&lt;p&gt;Scala&amp;#8217;s Actors are based on Doug Lea&amp;#8217;s &lt;a href=&quot;http://gee.cs.oswego.edu/dl/papers/fj.pdf&quot;&gt;Fork/Join library&lt;/a&gt; and have for example been used very effectively in the excellent &lt;a href=&quot;http://liftweb.net&quot;&gt;&lt;em&gt;lift&lt;/em&gt;&lt;/a&gt; web framework to among other things to enable &lt;a href=&quot;http://en.wikipedia.org/wiki/Comet_(programming)&quot;&gt;Comet&lt;/a&gt; style (push/streaming ajax) development. Actors allows us to, in a simple and uniformed way, parallelize applications using multiple threads, something that helps us take advantage of all the new dual/quad/&amp;#8230; core or &lt;span class=&quot;caps&quot;&gt;SMP&lt;/span&gt; machines that we are starting to get now days. But this also poses challenges; how can we make applications build on this &amp;#8220;new&amp;#8221; programming model highly available and how can we scale them out, if necessary. Would it not be cool if we could not only parallelize our application onto multiple threads but also onto multiple machines?&lt;/p&gt;
&lt;p&gt;Note: &lt;a href=&quot;http://erlang.org&quot;&gt;Erlang&lt;/a&gt;, the most successful implementation of Actors to date, solves the challenges in building fault-tolerant and highly available systems in an elegant way using supervisor hierarchies. Nothing prevents an implement of this strategy in Scala Actors, all the primitives (like link, trap_exit etc.) already exists.&lt;/p&gt;
&lt;p&gt;I have spent some time last weeks looking into if would make sense to utilize &lt;a href=&quot;http://terracotta.org&quot;&gt;Terracotta&lt;/a&gt; to cluster the Scala Actors library to give a platform on which we can both scale Actors out in a distributed fashion and ensure full fault tolerance and high-availability. The result of this exercise have been successful and I&amp;#8217;m happy to announce that they work very nice together. I will now spend the remainder of this post on walking you through a simple example in how to cluster a Scala Actor using Terracotta.&lt;/p&gt;
&lt;h2&gt;Check out the code from &lt;span class=&quot;caps&quot;&gt;SVN&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;But before we do anything, let my point you to the &lt;a href=&quot;http://svn.terracotta.org/svn/forge/projects/labs/tim-scala-actors-2.6.1/&quot;&gt;&lt;span class=&quot;caps&quot;&gt;SVN&lt;/span&gt; repository&lt;/a&gt; where you can fetch the Terracotta Integration Module (&lt;span class=&quot;caps&quot;&gt;TIM&lt;/span&gt;) that I have implemented for Scala Actors. You can check it out anonymously by invoking:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
svn co http://svn.terracotta.org/svn/forge/projects/labs/tim-scala-actors-2.6.1/
&lt;/pre&gt;
&lt;p&gt;When that is done, step into &lt;code&gt;tim-scala-actors-2.6.1/trunk&lt;/code&gt; and invoke &lt;code&gt;mvn install&lt;/code&gt; (the last command requires that you have &lt;a href=&quot;http://maven.apache.org/&quot;&gt;Maven&lt;/a&gt; installed). it&amp;#8217;ll take a while for Maven to download all its dependencies but after a while you will have a shiny new &lt;span class=&quot;caps&quot;&gt;TIM&lt;/span&gt; for Scala Actors installed in your local Maven repository (usually in &lt;code&gt;~/.m2&lt;/code&gt;). The sample that we will discuss in the next sections is available in the &lt;code&gt;src/samples/scala&lt;/code&gt; directory with the sample configuration in the &lt;code&gt;src/samples/resources&lt;/code&gt; directory.&lt;/p&gt;
&lt;h2&gt;Write an Actor&lt;/h2&gt;
&lt;p&gt;Now, let&amp;#8217;s write a little &lt;code&gt;Cart&lt;/code&gt; actor. This actor response to two different messages &lt;code&gt;AddItem(item)&lt;/code&gt; and &lt;code&gt;Tick&lt;/code&gt;. The former one adds an item to the &lt;code&gt;Cart&lt;/code&gt; while the latter one triggers the &lt;code&gt;Cart&lt;/code&gt; to print out its content (I&amp;#8217;ll let you know why it&amp;#8217;s called &lt;code&gt;Tick&lt;/code&gt; in a second):&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
// Messages
case object Tick
case class AddItem(item: String)
  
class Cart extends Actor {
  private[this] var items: List[String] = Nil 

  def act() {
    loop {
      react {
        case AddItem(item) =&amp;gt;
          items = item :: items
        case Tick =&amp;gt;
          println(&quot;Items: &quot; + items)
      }
    }
  }
  
  def ping = ActorPing.scheduleAtFixedRate(this, Tick, 0L, 5000L)
}
&lt;/pre&gt;
&lt;p&gt;As you see the state is held by a Scala &lt;code&gt;var&lt;/code&gt;, which holds onto a &lt;code&gt;List&lt;/code&gt; (immutable). In &lt;code&gt;react&lt;/code&gt; we wait for the next incoming message and if it is of type &lt;code&gt;AddItem&lt;/code&gt; then we grab the item and append it to the list with all our items, but if the message is of type &lt;code&gt;Tick&lt;/code&gt; we simply print the list of items out. Simple enough. But what is this method &lt;code&gt;ping&lt;/code&gt; doing? It uses an object called &lt;code&gt;ActorPing&lt;/code&gt; to schedule that a &lt;code&gt;Tick&lt;/code&gt; should be sent to the &lt;code&gt;Cart&lt;/code&gt; every 5 seconds (&lt;code&gt;ActorPing&lt;/code&gt; is shamelessly stolen from &lt;a href=&quot;http://blog.lostlake.org/&quot;&gt;Dave Pollak&amp;#8217;s&lt;/a&gt; &lt;em&gt;lift&lt;/em&gt;).&lt;/p&gt;
&lt;h2&gt;Configuration&lt;/h2&gt;
&lt;p&gt;In order to cluster the &lt;code&gt;Cart&lt;/code&gt; actor we have to write two things. First a hack, a simple configuration file in which declare which actors we want to cluster. This is something that later should be put into the regular &lt;code&gt;tc-config.xml&lt;/code&gt; file, but for now we have to live with it. So let&amp;#8217;s create a file with one single line, stating the fully qualified name of the &lt;code&gt;Cart&lt;/code&gt; actor; &lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt; samples.Cart &lt;/pre&gt; We can either name this file &lt;code&gt;clustered-scala-actors.conf&lt;/code&gt; and put it in root directory of the application or name it whatever we want and feed it to Terracotta using the &lt;code&gt;-Dclustered.scala.actors.config=[path to the file]&lt;/code&gt; &lt;span class=&quot;caps&quot;&gt;JVM&lt;/span&gt; property. Second, we have to write the regular Terracotta configuration file (tc-config.xml). Here we essentially have to define three things; the &lt;span class=&quot;caps&quot;&gt;TIM&lt;/span&gt; for Scala Actors, locks to guard our mutable state and finally which classes should be included for bytecode instrumentation.&lt;/p&gt;
&lt;p&gt;Starting with the &lt;span class=&quot;caps&quot;&gt;TIM&lt;/span&gt; for Scala Actors. Here we define the version on the module as well as the &lt;span class=&quot;caps&quot;&gt;URL&lt;/span&gt; to our Maven repository (in a short while we will put this jar in the Terracotta Maven repository and then you would not have to point out a local one).&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
&amp;lt;modules&amp;gt;
 &amp;lt;repository&amp;gt;file:///Users/jonas/.m2/repository&amp;lt;/repository&amp;gt;
 &amp;lt;module name=&quot;clustered-scala-actors-2.6.1&quot; version=&quot;2.6.0.SNAPSHOT&quot;/&amp;gt;
&amp;lt;/modules&amp;gt;
&lt;/pre&gt;
&lt;p&gt;Now we have to define the locks, which in Terracotta, also marks the transaction boundaries. The &lt;code&gt;Cart&lt;/code&gt; has one mutable field (the &lt;code&gt;var&lt;/code&gt; named &lt;code&gt;items&lt;/code&gt;) that we need to ensure is guarded correctly and has transactional semantics. For each var Scala generates a setter and a getter. The getter is named the same as the field while the getter has the name suffixed with &lt;code&gt;_$eq&lt;/code&gt;. That gives us the following lock definition:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
&amp;lt;locks&amp;gt;
  &amp;lt;named-lock&amp;gt;
    &amp;lt;lock-name&amp;gt;cart_items_write&amp;lt;/lock-name&amp;gt;
    &amp;lt;lock-level&amp;gt;write&amp;lt;/lock-level&amp;gt;
    &amp;lt;method-expression&amp;gt;* samples.Cart.items_$eq(..)&amp;lt;/method-expression&amp;gt;
  &amp;lt;/named-lock&amp;gt;
  &amp;lt;named-lock&amp;gt;
    &amp;lt;lock-name&amp;gt;cart_items_read&amp;lt;/lock-name&amp;gt;
    &amp;lt;lock-level&amp;gt;read&amp;lt;/lock-level&amp;gt;
    &amp;lt;method-expression&amp;gt;* samples.Cart.items()&amp;lt;/method-expression&amp;gt;
  &amp;lt;/named-lock&amp;gt;
&amp;lt;/locks&amp;gt;
&lt;/pre&gt;
&lt;p&gt;We have to define a pair like this for each mutable &lt;strong&gt;user defined&lt;/strong&gt; field in a clustered actor (not the standard one&amp;#8217;s that are common for all Scala Actors, those are automatically defined).&lt;/p&gt;
&lt;p&gt;It important to understand the &lt;span class=&quot;caps&quot;&gt;TIM&lt;/span&gt; automatically clusters the Actor&amp;#8217;s mailbox, which means that no messages will ever be lost &amp;#8211; providing full fault-tolerance.&lt;/p&gt;
&lt;p&gt;Finally we have to define the classes that we need to include for instrumentation. This naturally includes our application classes, e.g. the classes that are using our &lt;code&gt;Cart&lt;/code&gt; actor in one way or the other. Those are picked out by the pattern like: &lt;code&gt;'samples.*'&lt;/code&gt;. We also have to include all the Scala runtime and library classes that we are referencing from the message is that we send. In our case that means the classes that are used to implement the &lt;code&gt;List&lt;/code&gt; abstraction in Scala. Here is the full listing:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
&amp;lt;instrumented-classes&amp;gt;
 &amp;lt;include&amp;gt;
   &amp;lt;class-expression&amp;gt;samples.*&amp;lt;/class-expression&amp;gt;
 &amp;lt;/include&amp;gt;
 &amp;lt;include&amp;gt;
   &amp;lt;class-expression&amp;gt;scala.List&amp;lt;/class-expression&amp;gt;
 &amp;lt;/include&amp;gt;
 &amp;lt;include&amp;gt;
   &amp;lt;class-expression&amp;gt;scala.$colon$colon&amp;lt;/class-expression&amp;gt;
 &amp;lt;/include&amp;gt;
 &amp;lt;include&amp;gt;
   &amp;lt;class-expression&amp;gt;scala.Nil$&amp;lt;/class-expression&amp;gt;
 &amp;lt;/include&amp;gt;
&amp;lt;/instrumented-classes&amp;gt;
&lt;/pre&gt;
&lt;p&gt;I could have included these (and many more) classes in the &lt;span class=&quot;caps&quot;&gt;TIM&lt;/span&gt;, but since Terracotta adds a tiny bit of overhead to each class that it instruments I took the decision that it would be better to let the user explicitly define the classes that needs to be instrumented and leave the other ones alone. Since you can pretty much put any valid Scala data or abstraction in an actor message, it is very likely that you will have to declare some includes, else Terracotta will throw an exception (which is expected) with a message listing the &lt;span class=&quot;caps&quot;&gt;XML&lt;/span&gt; snippet that you have to put in the tc-config.xml file. So don&amp;#8217;t panic if things blow up.&lt;/p&gt;
&lt;h2&gt;Enable Terracotta&lt;/h2&gt;
&lt;p&gt;Last but not least, we need to enable Terracotta in the Scala runtime (if you are planning to run the application in a Terracotta enabled application server, then you can skip this section &amp;#8211; however I think it might still be useful to be able to try the application out in the Scala &lt;span class=&quot;caps&quot;&gt;REPL&lt;/span&gt;). The simplest way of doing that is to do some minor changes to the &lt;code&gt;scala&lt;/code&gt; command. First, let&amp;#8217;s step down into the &lt;code&gt;scala/bin&lt;/code&gt; directory and make a copy of the &lt;code&gt;scala&lt;/code&gt; command called &lt;code&gt;tc-scala&lt;/code&gt;, then scroll down all the way to the bottom. As you can see it is just a wrapper around the regular &lt;code&gt;java&lt;/code&gt; command, which makes things pretty easy for us. We start by defining some environmental variables (here showing my local settings):&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
TC_SCALA_ACTORS_CONFIG_FILE=/Users/jonas/src/java/tc-forge/projects/tim-scala-actors-2.6.1/trunk/src/samples/resources/clustered-scala-actors.conf
TC_CONFIG_FILE=/Users/jonas/src/java/tc-forge/projects/tim-scala-actors-2.6.1/trunk/src/samples/resources/tc-config.xml
TC_INSTALL_DIR=/Users/jonas/src/java/tc/code/base/build/dist/terracotta-trunk-rev6814
TC_BOOT_JAR=&quot;$TC_INSTALL_DIR&quot;/lib/dso-boot/dso-boot-hotspot_osx_150_13.jar
TC_TIM_SCALA_ACTORS_JAR=/Users/jonas/.m2/repository/org/terracotta/modules/clustered-scala-actors-2.6.1/2.6.0-SNAPSHOT/clustered-scala-actors-2.6.1-2.6.0-SNAPSHOT.jar
&lt;/pre&gt;
&lt;p&gt;When these variables have been defined we can replace the existing invocation of &lt;code&gt;java&lt;/code&gt; with the following:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
${JAVACMD:=java} ${JAVA_OPTS:=-Xmx256M -Xms256M} \
 -Xbootclasspath/p:&quot;$TC_BOOT_JAR&quot; \
 -Dtc.install-root=&quot;$TC_INSTALL_DIR&quot; \
 -Dtc.config=&quot;$TC_CONFIG_FILE&quot; \
 -Dclustered.scala.actors.config=&quot;$TC_SCALA_ACTORS_CONFIG_FILE&quot; \
 -Dscala.home=&quot;$SCALA_HOME&quot; \
 -Denv.classpath=&quot;$CLASSPATH&quot; \
 -Denv.emacs=&quot;$EMACS&quot; \
 -cp &quot;$BOOT_CLASSPATH&quot;:&quot;$EXTENSION_CLASSPATH&quot;:&quot;$TC_TIM_SCALA_ACTORS_JAR&quot; \
 scala.tools.nsc.MainGenericRunner  &quot;$@&quot;
&lt;/pre&gt;
&lt;h2&gt;Let&amp;#8217;s run it&lt;/h2&gt;
&lt;p&gt;Enough hacking. Now let&amp;#8217;s try it out. I think that the best way of learning new things in Scala is to use its &lt;span class=&quot;caps&quot;&gt;REPL&lt;/span&gt;, so let&amp;#8217;s start that up, this time with Terracotta enabled. But before we do that we have to start up the Terracotta server by stepping into the bin directory in the Terracotta installation and invoke:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
$ ./start-tc-server.sh
&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; you need to grab Terracotta from &lt;span class=&quot;caps&quot;&gt;SVN&lt;/span&gt; trunk to get the bits that work with the Scala &lt;span class=&quot;caps&quot;&gt;TIM&lt;/span&gt;. See instructions on how to &lt;a href=&quot;http://www.terracotta.org/confluence/display/wiki/Source+Repository&quot;&gt;check out the sources&lt;/a&gt; and &lt;a href=&quot;http://www.terracotta.org/confluence/display/devdocs/Building+Terracotta&quot;&gt;how to build it&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Now, we can start up the Terracotta enabled Scala &lt;span class=&quot;caps&quot;&gt;REPL&lt;/span&gt;:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
$ tc-scala
2008-01-25 07:42:11,643 INFO - Terracotta trunk-rev6814, as of 20080124-140101 (Revision 6814 by jonas@homer from trunk)
2008-01-25 07:42:12,136 INFO - Configuration loaded from the file at '/Users/jonas/src/java/tc-forge/projects/tim-scala-actors-2.6.1/trunk/src/samples/resources/tc-config.xml'.
2008-01-25 07:42:12,325 INFO - Log file: '/Users/jonas/terracotta/client-logs/scala/actors/20080125074212303/terracotta-client.log'.
Parsing scala actors config file: /Users/jonas/src/java/tc-forge/projects/tim-scala-actors-2.6.1/trunk/src/samples/resources/clustered-scala-actors.conf
Configuring clustering for Scala Actor: samples.Cart
Welcome to Scala version 2.6.0-final.
Type in expressions to have them evaluated.
Type :help for more information.

scala&amp;gt;
&lt;/pre&gt;
&lt;p&gt;Here we can see that it has found and connected to the Terracotta server, found our &lt;code&gt;clustered-scala-actors.conf&lt;/code&gt; config file and configured clustering for one Scala Actor; &lt;code&gt;samples.Cart&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Let&amp;#8217;s have some fun and start up another &lt;span class=&quot;caps&quot;&gt;REPL&lt;/span&gt; in another terminal window. In each of these we do the following; import our classes, create a new &lt;code&gt;Cart&lt;/code&gt; (Actor) and start up the Actor.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
scala&amp;gt; import samples._              
import samples._

scala&amp;gt; val cart = new Cart
cart: samples.Cart = samples.Cart@81af82

scala&amp;gt; cart.start
res0: scala.actors.Actor = samples.Cart@81af82

scala&amp;gt; 
&lt;/pre&gt;
&lt;p&gt;Now we have a distributed Actor just waiting to be fed with some messages. We don&amp;#8217;t want to make it disappointed so let&amp;#8217;s now add a bunch of bananas and apples to the &lt;code&gt;Cart&lt;/code&gt;, and then feed it with a &lt;code&gt;Tick&lt;/code&gt; message to make it print out the result:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
scala&amp;gt; cart ! AddItem(&quot;bananas&quot;)

scala&amp;gt; cart ! AddItem(&quot;apples&quot;)

scala&amp;gt; cart ! Tick

scala&amp;gt; Items: List(apples, bananas)

scala&amp;gt; 
&lt;/pre&gt;
&lt;p&gt;Ok, so far no news. But comes the moment of truth, let&amp;#8217;s take the other &lt;span class=&quot;caps&quot;&gt;REPL&lt;/span&gt; and fire of a &lt;code&gt;Tick&lt;/code&gt;:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
scala&amp;gt; cart ! Tick

scala&amp;gt; Items: List(apples, bananas)

scala&amp;gt; 
&lt;/pre&gt;
&lt;p&gt;Yippee, it works. Now we can invoke the &lt;code&gt;ping&lt;/code&gt; method to schedule a &lt;code&gt;Tick&lt;/code&gt; (to print out status) every 5 seconds.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
scala&amp;gt; cart.ping
res2: java.util.concurrent.ScheduledFuture = java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask@3a4388

scala&amp;gt; Items: List(apples, bananas)

scala&amp;gt; Items: List(apples, bananas)

scala&amp;gt; cart ! AddItem(&quot;football&quot;)

scala&amp;gt; Items: List(football, apples, bananas)

...
&lt;/pre&gt;

&lt;h2&gt;How to define scope of the clustered Actor?&lt;/h2&gt;
&lt;p&gt;The Scala Actors &lt;span class=&quot;caps&quot;&gt;TIM&lt;/span&gt; currently supports three different scopes; &lt;code&gt;instance&lt;/code&gt;, &lt;code&gt;class&lt;/code&gt; and &lt;code&gt;custom&lt;/code&gt;. The scope is defined by appending a colon &amp;#8216;:&amp;#8217; and the type of scope after the &lt;span class=&quot;caps&quot;&gt;FQN&lt;/span&gt; of the Actor in the &lt;code&gt;clustered-scala-actors.conf&lt;/code&gt;. If no scope is defined then the Actor is assumed to have scope &lt;code&gt;instance&lt;/code&gt;. For example:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
com.biz.Foo:custom
com.biz.Bar:class
com.biz.Baz:instance  
com.biz.Bam
&lt;/pre&gt;
&lt;p&gt;The default scope named &lt;code&gt;instance&lt;/code&gt; means that the Scala &lt;span class=&quot;caps&quot;&gt;TIM&lt;/span&gt; is transparently intercepting the instantiation (f.e. &lt;code&gt;new Cart&lt;/code&gt;) of all the Actors that you declare in the &lt;code&gt;clustered-scala-actors.conf&lt;/code&gt; file. Each clustered Actor &lt;strong&gt;instance&lt;/strong&gt; will have a unique identity across the cluster and each time this specific instance is created (f.e. when a new node joins the cluster) then the clustered instance with this specific identity will be handed out. The &lt;span class=&quot;caps&quot;&gt;TIM&lt;/span&gt; distinguishes between actors of the same type but instantiated in different code paths. To take an example, let&amp;#8217;s create one object &lt;code&gt;ActorFactory&lt;/code&gt; with one single method &lt;code&gt;create&lt;/code&gt;:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
object ActorFactory {
  def create: Actor = new MyActor
}
&lt;/pre&gt;
&lt;p&gt;If we now have two classes &lt;code&gt;Foo&lt;/code&gt; and &lt;code&gt;Bar&lt;/code&gt; as follows:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
class Foo {
  val actor = ActorFactory.create
}

class Bar {
  val actor = ActorFactory.create
}
&lt;/pre&gt;
&lt;p&gt;Then &lt;code&gt;Foo&lt;/code&gt; and &lt;code&gt;Bar&lt;/code&gt; will have two distinct clustered Actors each with a unique but cluster-wide identity.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;class&lt;/code&gt; scope lets all Actors of a the same type share Actor instance, so each time an Actor of a specific type is created the same clustered one will be handed out.&lt;/p&gt;
&lt;p&gt;Finally we have the &lt;code&gt;custom&lt;/code&gt; scope. Which, as it sounds, allows custom user defined scoping.&lt;/p&gt;
&lt;h2&gt;How to define custom scoped Actors?&lt;/h2&gt;
&lt;p&gt;If you want more control over scope and life-cycle of a specific Actor then you can define it to have &lt;code&gt;custom&lt;/code&gt; scope in the &lt;code&gt;clustered-scala-actors.conf&lt;/code&gt; file and create a factory in which you bind each Actor to whatever scope you wish. But now you have to create some data structure that is holding on to your Actors in the factory and explicitly define it to be a root in the &lt;code&gt;tc-config.xml&lt;/code&gt; file. The factory might look something like this:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
// Cart factory, allows mapping an instance to any ID
object Cart {
  
  // This instance is the custom Terracotta root
  private[this] val instances: Map[Any, Cart] = new HashMap

  def newInstance(id: Any): Cart = {
    instances.get(id) match {
      case Some(cart) =&amp;gt; cart
      case None =&amp;gt; 
        val cart = new Cart
        instances += (id -&amp;gt; cart)
        cart
    }
  }
}
&lt;/pre&gt;
&lt;p&gt;This means that we have to add some more configuration elements to our Terracotta configuration. First we need to add the root &lt;code&gt;samples.Cart$.instances&lt;/code&gt; (&lt;code&gt;Cart$&lt;/code&gt; is the name of Scala&amp;#8217;s compiled &lt;code&gt;Cart&lt;/code&gt; companion object, all companion objects compiles to a class with the name of the original class suffixed with &lt;code&gt;$&lt;/code&gt;):&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
&amp;lt;roots&amp;gt;
  &amp;lt;root&amp;gt;
    &amp;lt;field-name&amp;gt;samples.Cart$.instances&amp;lt;/field-name&amp;gt;
  &amp;lt;/root&amp;gt;
&amp;lt;/roots&amp;gt;
&lt;/pre&gt;
&lt;p&gt;Then we have to add locking for the &lt;code&gt;Cart.newInstance(..)&lt;/code&gt; method and finally a whole bunch of new include statements for all the Scala types that are referenced by the &lt;code&gt;scala.collection.mutable.HashMap&lt;/code&gt; that we used as root:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
...  
&amp;lt;named-lock&amp;gt;
  &amp;lt;lock-name&amp;gt;Cart_newInstance&amp;lt;/lock-name&amp;gt;
  &amp;lt;lock-level&amp;gt;write&amp;lt;/lock-level&amp;gt;
  &amp;lt;method-expression&amp;gt;* samples.Cart$.newInstance(..)&amp;lt;/method-expression&amp;gt;
&amp;lt;/named-lock&amp;gt;

...
          
&amp;lt;include&amp;gt;
  &amp;lt;class-expression&amp;gt;scala.collection.mutable.HashMap&amp;lt;/class-expression&amp;gt;
&amp;lt;/include&amp;gt;
&amp;lt;include&amp;gt;
  &amp;lt;class-expression&amp;gt;scala.runtime.BoxedAnyArray&amp;lt;/class-expression&amp;gt;
&amp;lt;/include&amp;gt;
&amp;lt;include&amp;gt;
  &amp;lt;class-expression&amp;gt;scala.runtime.BoxedArray&amp;lt;/class-expression&amp;gt;
&amp;lt;/include&amp;gt;
&amp;lt;include&amp;gt;
  &amp;lt;class-expression&amp;gt;scala.collection.mutable.DefaultEntry&amp;lt;/class-expression&amp;gt;
&amp;lt;/include&amp;gt;
  
...
&lt;/pre&gt;
&lt;p&gt;That&amp;#8217;s pretty much all there&amp;#8217;s to it. Check out the code, play with it and come back with feedback, bug reports, patches etc.&lt;/p&gt;
&lt;p&gt;Enjoy. &lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>HotSwap Code using Scala and Actors</title>
   <link href="http://jonasboner.com/2007/12/19/hotswap-code-using-scala-and-actors.html"/>
   <updated>2007-12-19T00:00:00+01:00</updated>
   <id>http://jonasboner.com/2007/12/19/hotswap-code-using-scala-and-actors</id>
   <content type="html">&lt;h1&gt;
&lt;p&gt;HotSwap Code using Scala and Actors&lt;/p&gt;
&lt;/h1&gt;
&lt;p&gt;&lt;strong&gt;Update&lt;/strong&gt;: In this article I am showing an even more powerful way of doing hotswap in Scala: &lt;br /&gt;
&lt;a href=&quot;http://jonasboner.com/2008/06/16/erlang-style-supervisor-module-for-scala-actors.html&quot;&gt;http://jonasboner.com/2008/06/16/erlang-style-supervisor-module-for-scala-actors.html&lt;/a&gt;.&lt;br /&gt;
Se the bottom of this article for an example of how this is used to enable hotswap of arbitrary pieces of pattern matching code.&lt;/p&gt;
&lt;hr /&gt;

&lt;p&gt;In this post I will show you how you can do code hotswap in the same fashion as in &lt;a href=&quot;http://erlang.org&quot;&gt;Erlang&lt;/a&gt; using &lt;a href=&quot;http://www.scala-lang.org&quot;&gt;Scala&lt;/a&gt; and its &lt;a href=&quot;http://lamp.epfl.ch/~phaller/actors.html&quot;&gt;Actors&lt;/a&gt; package.&lt;/p&gt;
&lt;p&gt;An actor is an abstraction that implements &lt;a href=&quot;http://c2.com/cgi/wiki?MessagePassingConcurrency&quot;&gt;Message-Passing Concurrency&lt;/a&gt;. Actors have no shared state and are communicating by sending and receiving messages. This is a paradigm that provides a very different and much simpler concurrency model than &lt;a href=&quot;http://c2.com/cgi/wiki?SharedStateConcurrency&quot;&gt;Shared-State Concurrency&lt;/a&gt; (the scheme adopted by C, Java, C# etc.) and is avoiding all of the latter one&amp;#8217;s problems with deadlocks, live locks, thread starvation etc. This makes it possible to write code that is deterministic and &lt;a href=&quot;http://en.wikipedia.org/wiki/Side_effect_%28computer_science%29&quot;&gt;side-effect-free&lt;/a&gt;, something that makes easier to write, test, understand and reason about. Each actor has a mailbox in which it receives incoming messages and can use pattern matching on the messages to decide if a message is interesting and which action to take.  The most well known and successful implementation of actors can be found in the Erlang language (and the &lt;span class=&quot;caps&quot;&gt;OTP&lt;/span&gt; platform) where it has been used to implement extremely fault tolerant (&lt;a href=&quot;http://ll2.ai.mit.edu/talks/armstrong.pdf &quot;&gt;99.9999999% reliability &amp;#8211; 9 nines&lt;/a&gt;) and massively concurrent systems (with hundreds of thousand simultaneous actors).&lt;/p&gt;
&lt;p&gt;Let&amp;#8217;s start by writing a little server. We implement this in the form of a &lt;code&gt;trait&lt;/code&gt;, which is Scala&amp;#8217;s &lt;a href=&quot;http://en.wikipedia.org/wiki/Mixin&quot;&gt;mixin&lt;/a&gt; construct. Traits allows you to build up your components using so-called mixin composition which is something that can give you a very high grade of reuse and flexibility. This &lt;code&gt;trait&lt;/code&gt; only defines a single method named &lt;code&gt;status&lt;/code&gt; which prints out info about the enclosing instance. Completely useless and not much for a server, but it will give you the idea. Then we subclass this mixin and define the &lt;code&gt;ServerOne&lt;/code&gt; concrete server class (with the &lt;code&gt;status&lt;/code&gt; method mixed in).&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
// servers
trait Server {
  def status = println(&quot;current server: &quot; + this)
}
class ServerOne extends Server 
&lt;/pre&gt;
&lt;p&gt;Let&amp;#8217;s instantiate the &lt;code&gt;ServerOne&lt;/code&gt; class and see what the &lt;code&gt;status&lt;/code&gt; method it will print out. Here we are doing it interactively through Scala&amp;#8217;s &lt;span class=&quot;caps&quot;&gt;REPL&lt;/span&gt; (read-eval-print-loop).&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
$ scala -cp .

scala&amp;gt; val server = new ServerOne
server: ServerOne = ServerOne@7be75d

scala&amp;gt; server status
current server: ServerOne@7be75d
&lt;/pre&gt;
&lt;p&gt;Now, before we write the actor we have to define the messages it responds to. Here Scala is using something called &lt;em&gt;case classes&lt;/em&gt; which are similar to normal classes but with some enhancements. First you can match on them, e.g. use pattern matching similar to the one found in Erlang. They also have some syntactic sugar, f.e. you can create them without using &lt;code&gt;new&lt;/code&gt;, the compiler generates getters and setters for the constructor arguments, equality is not based on object id but on meaning/content (something that makes them ideal to use for &lt;a href=&quot;http://c2.com/cgi/wiki?ValueObject&quot;&gt;value objects&lt;/a&gt;, but that is another story). We define two different messages; Status and HotSwap.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
// triggers the status method
case object Status

// triggers hotswap - carries the new server to be hotswapped to
case class HotSwap(s: Server)
&lt;/pre&gt;
&lt;p&gt;Ok, now it is time for the actual actor. Actor is a base class in the Scala library and we can choose to either extend it explicitly or to create an anonymous actor through the &lt;code&gt;actor {...}&lt;/code&gt; construct. When we subclass the actor we have to implement the method called &lt;code&gt;act&lt;/code&gt; which is the callback method that is invoked when the actor is started up.&lt;/p&gt;
&lt;p&gt;Scala comes with two different implementations; one that is based on Java threads in that each actor is getting its own thread, while the other one is based on events and very lightweight allowing hundreds of thousands of actors to run simultaneously. Here we will use the event-based version (which is done by using the &lt;code&gt;react&lt;/code&gt; method instead of the &lt;code&gt;receive&lt;/code&gt; method for receiving messages).&lt;/p&gt;
&lt;p&gt;The trick to do hotswap by using actors is to loop recursively and pass on the state in each recursive call. This is a very common idiom in functional programming.  The beauty of it is that we do not update any mutual state but our execution is side effect free which makes it easier to test and reason about.  In this case our state is the actual server. We start the loop by instantiating &lt;code&gt;ServerOne&lt;/code&gt;. The pattern matching is happening in &lt;code&gt;react&lt;/code&gt; statement in which we have three different cases (pattern matchers).&lt;/p&gt;
&lt;p&gt;The first one matches our &lt;code&gt;Status&lt;/code&gt;, when we receive this message we simply invoke the &lt;code&gt;status&lt;/code&gt; method on our server and then taking another round in the &lt;code&gt;loop&lt;/code&gt; passing along the server.&lt;/p&gt;
&lt;p&gt;The second one matches our &lt;code&gt;HotSwap&lt;/code&gt; message. It is here things are starting to get interesting. Now we can take the new replacement server (here called &lt;code&gt;newServer&lt;/code&gt;), which is passed to us as an argument to the &lt;code&gt;HotSwap&lt;/code&gt; message, and pass it in to the call to the &lt;code&gt;loop&lt;/code&gt; method. Voila, we have updated our server at runtime. Now all subsequent messages will act on our new server instance.&lt;/p&gt;
&lt;p&gt;This will work since the &lt;code&gt;react&lt;/code&gt; method will in fact never return but infinitely recur. Infinite recursion would have been a problem in f.e. Java since each recursion would consume a new stack frame until we run out of memory. But recursion is one of the most powerful and commonly used idioms in functional programming and the Scala compiler optimizes &lt;a href=&quot;http://en.wikipedia.org/wiki/Tail_recursion&quot;&gt;tail-recursive&lt;/a&gt; algorithms and turns them into regular loops.&lt;/p&gt;
&lt;p&gt;At the end we have also added a match-all pattern that does nothing, this is defined by the &lt;code&gt;case _ =&amp;gt; ...&lt;/code&gt; clause. Let&amp;#8217;s take a look at the code.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
class ServerActor extends Actor {
  def act = {
    println(&quot;starting server actor...&quot;)
    loop(new ServerOne)
  }
  
  def loop(server: Server) {
    react {
      case Status =&amp;gt; 
        server.status
        loop(server)

      case HotSwap(newServer) =&amp;gt; 
        println(&quot;hot swapping code...&quot;)
        loop(newServer)

      case _ =&amp;gt; loop(server)
    }
  }
}
&lt;/pre&gt;
&lt;p&gt;Finally we will follow one of Scala&amp;#8217;s idioms and create a companion object for our &lt;code&gt;ServerActor&lt;/code&gt; class. In this object, which is a singleton but should be seen upon as a module for functions and immutable state, we define an immutable handle to an instantiated and started actor.&lt;/p&gt;
&lt;p&gt;Worth to note is that the &lt;code&gt;val&lt;/code&gt; holding our actor is initialized when the enclosing object is first used, and since we are starting up the actor in the initialization block of the &lt;code&gt;val&lt;/code&gt;, the actor will not be started until it is used for the first time.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
// actor companion object
object ServerActor {
  val actor = {
    val a = new ServerActor
    a.start; a
  }
}
&lt;/pre&gt;
&lt;p&gt;Let&amp;#8217;s try to run it in the Scala &lt;span class=&quot;caps&quot;&gt;REPL&lt;/span&gt;. The Scala function &lt;em&gt;!&lt;/em&gt; (pronounced bang) means &amp;#8220;send a message&amp;#8221;. So &lt;em&gt;act ! msg&lt;/em&gt; means send message &lt;em&gt;msg&lt;/em&gt; to actor &lt;em&gt;act&lt;/em&gt;.&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
$ scala -cp .  

scala&amp;gt; import hotswap._
import hotswap._

scala&amp;gt; val actor = ServerActor.actor
starting actor...
actor: hotswap.ServerActor = hotswap.ServerActor@528ed7

scala&amp;gt; actor ! Status
current server: hotswap.ServerOne@226445

scala&amp;gt; class ServerTwo extends Server {
     | override def status = println(&quot;hotswapped server: &quot; + this)
     | }
defined class ServerTwo

scala&amp;gt; actor ! HotSwap(new ServerTwo)
hot swapping code...

scala&amp;gt; actor ! Status
hotswapped server: line5$object$$iw$$iw$$iw$ServerTwo@b556
&lt;/pre&gt;
&lt;p&gt;Pretty cool, right?&lt;/p&gt;
&lt;p&gt;This would be even more cool if Scala came with an &lt;span class=&quot;caps&quot;&gt;SSH&lt;/span&gt; server that could provide this &lt;span class=&quot;caps&quot;&gt;REPL&lt;/span&gt; remotely (like we have in Erlang &lt;span class=&quot;caps&quot;&gt;OTP&lt;/span&gt;). Then we could connect to our application from the outside and change its behavior, fixing bugs, upgrade the server etc. Another solution would be to make use of the &lt;a href=&quot;http://www.scala-lang.org/docu/files/api/scala/actors/remote$content.html&quot;&gt;remote actors&lt;/a&gt; in the Scala distribution, but that is something for another post.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;strong&gt;Update&lt;/strong&gt;:&lt;/p&gt;
&lt;p&gt;This is a slightly simplified version of the GenericServer code (as discussed &lt;a href=&quot;http://jonasboner.com/2008/06/16/erlang-style-supervisor-module-for-scala-actors.html&quot;&gt;here&lt;/a&gt;), allowing hotswap of arbitrary pieces of pattern matching code:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
// the actor's main loop
def act = loop { react { genericBase orElse actorBase } }

// should we go with the hotswapped impl or the regular server impl (body)
private def actorBase: PartialFunction[Any, Unit] = hotswap getOrElse body

// the hotswapped impl
private var hotswap: Option[PartialFunction[Any, Unit]] = None

// generic functionality
private val genericBase: PartialFunction[Any, Unit] = {
  case HotSwap(code) =&amp;gt; hotswap = code
}

// the regular server implementation
def body: PartialFunction[Any, Unit] = {
  ...
}

&lt;/pre&gt;
&lt;p&gt;This code can be used like this:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;scala&quot;&gt;
server ! HotSwap(Some({
  case Ping =&amp;gt; 
    println(&quot;Ping&quot;)
}))
&lt;/pre&gt;</content>
 </entry>
 
 <entry>
   <title>The Terracotta Book</title>
   <link href="http://jonasboner.com/2007/12/18/the-terracotta-book.html"/>
   <updated>2007-12-18T00:00:00+01:00</updated>
   <id>http://jonasboner.com/2007/12/18/the-terracotta-book</id>
   <content type="html">&lt;h1&gt;
&lt;p&gt;The Terracotta Book&lt;/p&gt;
&lt;/h1&gt;
&lt;p&gt;The last month I have been very busy writing on &lt;a href=&quot;http://www.apress.com/book/view/1590599861&quot;&gt;The Definitive Guide to Terracotta&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;It is a collaborative effort from the Terracotta team each one writing on chapters in their area of expertise. It is a very practical and will teach you how to use Terracotta with the X framework/appserver or for a Y use-case, yet thorough and deep in concepts and theory.&lt;/p&gt;
&lt;p&gt;It will be available sometime next year and if you&amp;#8217;re interested in getting updates on the book can subscribe to: bookupdate AT terracottatech &lt;span class=&quot;caps&quot;&gt;DOT&lt;/span&gt; com.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Oredev 2007: BDD, LINQ, Scalability trends etc.</title>
   <link href="http://jonasboner.com/2007/11/17/oredev-2007-bdd-linq-terracotta-etc.html"/>
   <updated>2007-11-17T00:00:00+01:00</updated>
   <id>http://jonasboner.com/2007/11/17/oredev-2007-bdd-linq-terracotta-etc</id>
   <content type="html">&lt;h1&gt;
&lt;p&gt;Oredev 2007: &lt;span class=&quot;caps&quot;&gt;BDD&lt;/span&gt;, &lt;span class=&quot;caps&quot;&gt;LINQ&lt;/span&gt;, Scalability trends etc.&lt;/p&gt;
&lt;/h1&gt;
&lt;p&gt;I had the pleasure of attending &lt;a href=&quot;http://oredev.org&quot;&gt;Oredev&lt;/a&gt; last month. This was a great conference. I have attended this conference three years in a row and it&amp;#8217;s getting better and better every year.&lt;/p&gt;
&lt;p&gt;This year they had a great speaker lineup and I was able to catch some very interesting talks. Among the most memorable ones were &lt;a href=&quot;http://dannorth.net/&quot;&gt;Dan North&lt;/a&gt;&amp;#8216;s keynote about why &amp;#8220;Best Practices&amp;#8221; in software development are neither &amp;#8220;Best&amp;#8221; no &amp;#8220;Practices&amp;#8221;. I also attended Dan&amp;#8217;s talk on &lt;span class=&quot;caps&quot;&gt;BDD&lt;/span&gt; (&lt;a href=&quot;http://behaviour-driven.org/&quot;&gt;Behavior-Driven&lt;br /&gt;
Development&lt;/a&gt;). Great talk. I find &lt;span class=&quot;caps&quot;&gt;BDD&lt;/span&gt; very interesting, it feels like the natural extension of, or complement to &lt;span class=&quot;caps&quot;&gt;TDD&lt;/span&gt; (Test-Drived Development) in that it focuses on getting complete concept coverage in the tests instead of code coverage (as in &lt;span class=&quot;caps&quot;&gt;TDD&lt;/span&gt;).&lt;/p&gt;
&lt;p&gt;Other great talks were &lt;a href=&quot;http://blog.toolshed.com/&quot;&gt;Andy Hunt&lt;/a&gt;&amp;#8216;s (Pragmatic Programmers) keynote and &lt;a href=&quot;http://research.microsoft.com/~emeijer/&quot;&gt;Erik Meijer&lt;/a&gt;&amp;#8217;s talk on &lt;a href=&quot;http://msdn2.microsoft.com/en-us/netframework/aa904594.aspx&quot;&gt;&lt;span class=&quot;caps&quot;&gt;LINQ&lt;/span&gt;&lt;/a&gt;. The latter one was fun to watch, Erik (undeliberately it felt like) turned it more or less into a praise of &lt;a href=&quot;http://haskell.org&quot;&gt;Haskell&lt;/a&gt;; how they have stolen all the good stuff in &lt;span class=&quot;caps&quot;&gt;LINQ&lt;/span&gt; from Haskell and that the world would be a better place if everyone just used Haskell.&lt;/p&gt;
&lt;p&gt;My talk on &lt;a href=&quot;http://terracotta.org&quot;&gt;Terracotta&lt;/a&gt; was able to attract quite a lot of attendees. One of the most interesting things was when I asked them, at the end of the talk, how many could see immediate need for something like Terracotta in their daily work roughly 80% raise their hands. I find this quite amazing and is actually something that have been consistent during last half year. I remember when I started asking this question, around 2 years ago, roughly 5-10 % raised their hands. This is quite a drastic change. Since I know that we were facing the same problems with scalability and HA a couple of years as we do now, I guess this is a sign of that the awareness of clustering, persistent and durable &lt;span class=&quot;caps&quot;&gt;RAM&lt;/span&gt; and similar services has increased; that people have started to consider writing stateful applications with rich domain models &amp;#8211; which implies another solution to HA and scalability than Oracle &lt;span class=&quot;caps&quot;&gt;RAC&lt;/span&gt; and similar.&lt;/p&gt;
&lt;p&gt;However, the best thing was that the conference had invited one of the best coffee shops in Malmo to serve all speakers unlimited amount of caffeine in the form of espresso, cafe latte, machiatto or whatever was asked for. I paid them 4-5 visits every day.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Interview with Joe Armstrong on Erlang and more...</title>
   <link href="http://jonasboner.com/2007/10/30/interview-with-joe-armstrong-on-erlang-and-more.html"/>
   <updated>2007-10-30T00:00:00+01:00</updated>
   <id>http://jonasboner.com/2007/10/30/interview-with-joe-armstrong-on-erlang-and-more</id>
   <content type="html">&lt;h1&gt;
&lt;p&gt;Interview with Joe Armstrong on Erlang and more&amp;#8230;&lt;/p&gt;
&lt;/h1&gt;
&lt;p&gt;I had the pleasure of attending Joe Armstrong&amp;#8217;s fantastic presentation at &lt;a href=&quot;http://jaoo.dk/&quot;&gt;&lt;span class=&quot;caps&quot;&gt;JAOO&lt;/span&gt;&lt;/a&gt; some weeks ago. It was by far the best talk at the whole conference, both in terms of content and presentation. Joe showed deep knowledge in both hardware and software, good teaching skills all wrapped up in a dry twisted sense of British humor &amp;#8211; Joe was incredibly funny, I sometimes felt like had attended a stand-up comedian show.&lt;/p&gt;
&lt;p&gt;Anyway, for all of you that missed Joe&amp;#8217;s talk, &lt;a href=&quot;http://channel9.msdn.com/ShowPost.aspx?PostID=351659#351659&quot;&gt;here is a great interview&lt;/a&gt; with him discussing Erlang&amp;#8217;s (and a functional programmer&amp;#8217;s) view of the world, the problem with OO, shared state concurrency and much more. Not as funny as the talk, but very interesting.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Clojure: a Lisp-dialect for the JVM - with focus on Functional and Concurrent Programming</title>
   <link href="http://jonasboner.com/2007/10/18/clojure-a-lisp-dialect-for-the-jvm-with-focus-on-functional-and-concurrent-programming.html"/>
   <updated>2007-10-18T00:00:00+02:00</updated>
   <id>http://jonasboner.com/2007/10/18/clojure-a-lisp-dialect-for-the-jvm-with-focus-on-functional-and-concurrent-programming</id>
   <content type="html">&lt;h1&gt;
&lt;p&gt;Clojure: a Lisp-dialect for the &lt;span class=&quot;caps&quot;&gt;JVM&lt;/span&gt; &amp;#8211; with focus on Functional and Concurrent Programming&lt;/p&gt;
&lt;/h1&gt;
&lt;p&gt;Yesterday, Rich Hickey announced the birth of &lt;a href=&quot;http://clojure.sourceforge.net/&quot;&gt;Clojure&lt;/a&gt; &amp;#8211; a lisp dialect for the &lt;span class=&quot;caps&quot;&gt;JVM&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;After just a brief look, Clojure is perhaps the most interesting language in the (now fairly large) family of &amp;#8216;dynamic languages for the &lt;span class=&quot;caps&quot;&gt;JVM&lt;/span&gt;&amp;#8217;. It brings the power of Lisp to the &lt;span class=&quot;caps&quot;&gt;JVM&lt;/span&gt; but have made some design decisions that in some ways makes it more interesting than &lt;a href=&quot;http://en.wikipedia.org/wiki/Common_lisp&quot;&gt;&lt;span class=&quot;caps&quot;&gt;ANSI&lt;/span&gt; Common Lisp&lt;/a&gt;. Here are some of the things that I find particularly interesting:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Allows pure functional programming with immutable state (with immutable data-structures etc.) for side-effect-free code (possible in CL but hard to enforce).&lt;/li&gt;
	&lt;li&gt;&lt;ul&gt;&lt;br /&gt;
Great support for concurrent programming: &lt;br /&gt;
	&lt;li&gt;Immutable state can be freely shared across threads.&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://en.wikipedia.org/wiki/Software_transactional_memory&quot;&gt;Software Transactional Memory&lt;/a&gt; (&lt;span class=&quot;caps&quot;&gt;STM&lt;/span&gt;) that allows atomic and isolated updates to mutable state (through &amp;#8220;Refs&amp;#8221;) with rollback and retry upon collision.&lt;/li&gt;
	&lt;li&gt;Safe usage of mutable state through thread isolation (using &amp;#8220;Vars&amp;#8221;).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
	&lt;li&gt;Full Lisp-style macro support and eval.&lt;/li&gt;
	&lt;li&gt;Compiles to &lt;span class=&quot;caps&quot;&gt;JVM&lt;/span&gt; bytecode but still fully dynamic (sounds promising but I don&amp;#8217;t know its actual performance).&lt;/li&gt;
	&lt;li&gt;Excellent integration with Java APIs, with type inference for static compilation of Java &lt;span class=&quot;caps&quot;&gt;API&lt;/span&gt; calls.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here are some tasters (from the &lt;a href=&quot;http://groups.google.com/group/clojure&quot;&gt;forum&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Java integration:&lt;/strong&gt;&lt;br /&gt;
&lt;pre&gt;&lt;br /&gt;
(new java.util.Date)&lt;br /&gt;
=&amp;gt; Wed Oct 17 20:01:38 &lt;span class=&quot;caps&quot;&gt;CEST&lt;/span&gt; 2007&lt;/p&gt;
&lt;p&gt;(. (new java.util.Date) (getTime))&lt;br /&gt;
=&amp;gt; 1192644138751&lt;/p&gt;
&lt;p&gt;(.. System out (println &amp;#8220;This is cool!&amp;#8221;))&lt;br /&gt;
This is cool!&lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Macros:&lt;/strong&gt;&lt;br /&gt;
&lt;pre&gt;  &lt;br /&gt;
(defmacro time [form]&lt;br /&gt;
  `(let [t0# (. System (currentTimeMillis))&lt;br /&gt;
         res# ~form&lt;br /&gt;
         t1# (. System (currentTimeMillis))]&lt;br /&gt;
    (.. System out (println (strcat &amp;quot;Execution took &amp;quot;&lt;br /&gt;
                                    (/ (- t1# t0#) 1000.0) &amp;quot; s&amp;quot;)))&lt;br /&gt;
    res#))&lt;/p&gt;
&lt;p&gt;Usage:&lt;br /&gt;
(defn factorial [n]&lt;br /&gt;
   (if (&amp;lt; n 2)&lt;br /&gt;
       1&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;n (factorial (- n 1)))))&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;(time (factorial 1000))&lt;br /&gt;
=&amp;gt; Execution took 0.012 s&lt;br /&gt;
     40&amp;#8230; &lt;br /&gt;
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;It is still in beta but if you want to start playing around with it yourself, dive into the &lt;a href=&quot;http://clojure.sourceforge.net/reference/getting_started.html&quot;&gt;docs&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Dreaming on:&lt;/strong&gt;&lt;br /&gt;
Stuff that I would like to see (in order to make it the ultimate playground) are among other things: message-passing concurrency (I don&amp;#8217;t fully believe in &lt;span class=&quot;caps&quot;&gt;STM&lt;/span&gt;&amp;#8230;yet) and declarative pattern matching (from &lt;a href=&quot;http://erlang.org&quot;&gt;Erlang&lt;/a&gt;), implicit currying and laziness (as in &lt;a href=&quot;http://haskell.org&quot;&gt;Haskell&lt;/a&gt;), transparent distribution (as in &lt;a href=&quot;http://www.mozart-oz.org/&quot;&gt;Mozart/Oz&lt;/a&gt; and Erlang) and optional static typing. Some of these can be found in &lt;a href=&quot;http://www.lambdassociates.org/&quot;&gt;Qi&lt;/a&gt;, I just would love to see them on the &lt;span class=&quot;caps&quot;&gt;JVM&lt;/span&gt;.&lt;/p&gt;</content>
 </entry>
 
 
</feed>
