Saturday 15 September 2012

Entities, Value Objects and Services

In chapter five A Model Expressed in Software of Domain-Driven Design, Eric Evans wrote about ENTITIES, VALUE OBJECTS and SERVICES. These are three important patterns of DDD. They help us to capture important concepts of the domain. By classifying the objects in this way we can make objects less ambiguous. In this post I write down my understanding about this topic.

So what is an ENTITY?

ENTITY = IDENTITY + CONTINUITY

ENTITY is an object that has distinct identity and also has continuity. This type of object is not fundamentally defined by its attributes. For example: two customers can have same name, age or even living in same address but they must have unique identifier (say, customer number) within the system.



ENTITY has a life cycle that can change its form and content over the time but a thread of continuity must be maintained. Here identity plays an important role because ENTITY can be tracked effectively with the help of it.



Care must be taken when generating identity for an ENTITY. Identity must be guaranteed to be unique within the system no matter how the system is developed, even whether it is distributed or not. Once generated, it must not be changed. Sometimes single data attribute (guaranteed to be unique) can be identity of an entity. For example: order number, transaction number, account number, customer number etc. Sometimes you need a combination of data attributes to define an identity. For example: daily newspapers might be identified by the name of the newspaper, the city, and the date of publication.

What about VALUE OBJECTS?

VALUE OBJECT does not have a conceptual identity but it represents a descriptive aspect of the domain.For example: A customer may be modelled as an ENTITY with an identity, but his phone number is a VALUE OBJECT.

VALUE OBJECTS help us to design and code in a better way:
  • They make implicit concepts explicit.
  • They help to write a clear service api.
  • They take the responsibility of data validation and error handling.
  • They help us to write a well testable and maintainable code.
Take the example of a phone number. We can declare it's type as string in customer class.

public class customer {  
  ...... 
  private string phoneNumber;
  ........ 
}

But if you think carefully, declaring phoneNumber as a string does not say much about it. Here the phoneNumber is implicit. It may introduce bugs, make you to write awkward and duplicate code. When you make it explicit, things become more clear:

public class customer {  
  ...... 
  private PhoneNumber phoneNumber;
  ........ 
}

It also opens option to add different behaviors to PhoneNumber. You can add data validation and error handing to this object. Here is the sample code of PhoneNumber [2]:

public class PhoneNumber {

  private final String number;
  
  public PhoneNumber(String number) {
     if(!isValid(number))
    throw ...
     this.number = number;
  }
  
  public String getNumber() {
    return number;
  }
  
  static public boolean isValid(String number) {
    return number.matches("[0-9]*");
  }
  
  public String getAreaCode() {
    String prefix = null;
    for (int i=0; i< number.length(); i++) {
 String begin = number.subString(0,i);
        if(isAreaCode(begin)) {
    prefix = begin;
    break;
        }
    return prefix;
  }

  private boolean isAreaCode(String prefix) { ... }
}
If you noticed carefully, you will find that we have put computational complexity in this object rather than putting it in service layer. So the service layer has less burden. Code duplication is reduced. Less code means less bug. Now you can write a set of junit testcases for this object.

Lets see how VALUE OBJECTS help us to write clear service api. For example: we have a api that takes name, age, address and phone number to add a customer:

void addCustomer(String, Int, String, String);

Is the above api clear to you? You can see String and Int all over, nothing meaningful. How about writing this way:

void addCustomer(Name, Age, Address, PhoneNumber);

Now the api is readable. Even a non technical person can understand the above method signature.One thing we need to remember - VALUE OBJECTS should be immutable. For example:

Money money1 = new Money("EUR", 30);
Money money2 = new Money("EUR", 40);
Money money3 = money1.add(money2);

When you add money2 to money1, you are not altering money1, instead returning a new Money object (assigned to money3) which represents the two amounts of Money added together. Ensuring immutability of value object is important if you want to share it safely. It cannot be changed except by full replacement.

Services

A SERVICE is a standalone domain operation that you cannot fit in an ENTITY or VALUE OBJECT. It is defined purely in terms of what it can do for a client.

Evans mentioned in his book that a good SERVICE should have three characteristics:
  • The operation relates to a domain concept that is not a natural part of an ENTITY or VALUE OBJECT
  • The interface is defined in terms of other elements of the domain model
  • The operation is stateless

SERVICES can be partitioned based on layer:
  • APPLICATION SERVICES sit above the domain services, handle cross cutting concern such as transaction, security. They also talk to the presentation layer to get the input or send the output back.
  • DOMAIN SERVICES deal with business logic that cannot live in an ENTITY. For example, transferring fund between two accounts.
  • INFRASTRUCTURE SERVICES are those service that are more technical in nature, for example sending out an email or SMS text message.

Operation names in SERVICES should come from the UBIQUITOUS LANGUAGE. Parameters and results of these operations should be domain objects to make them explicit. SERVICES should be used carefully, don't take away all the behaviors from ENTITIES and VALUE OBJECTS and put them in SERVICES.

References:

1. Domain-Driven Design by Eric Evans
2. Power Use of Value Objects in DDD by Dan Bergh Johnsson
3. EvansClassification by Martin Fowler

Sunday 18 March 2012

Playing with Play Framework - PART 1

Last few days I have been playing with the Play Framework. I must say that I am loving it. Recently Play 2.0 is released.  It is a good web framework in many ways: 
  • fast development & feedback loop
  • it is based on event-driven and non-blocking IO
  • it is built for asynchronous programming
  • support for both Java and Scala
  • and more .... (please check http://www.playframework.org
I have also been learning Scala. So I have thought that it would be a good idea to create a sample application using Play 2.0 and Scala.  My intention is to develop this sample application gradually and at the same time demonstrate various aspects of Play Framework (trying Scala in this way is a bonus for me). One thing I should say here I have followed the sample applications that are given with the Play to create this application.

Lets begin the work. But before that a short introduction of the sample application.

Introduction

My application is called HR Solutions. This application will keep track of details of employees of an organisation. HR Solutions will be used by two group of users: human resource managers and employees. Human resource managers are responsible for capturing the details of employees. They can create, update, read and delete an employee. Employees will get view permission to see their own details and they can only update their personal details when logged in (this will be added in future). As mentioned earlier I will gradually add other details in later post. Here is the initial domain diagram:



Steps

Here are the steps I have followed to create this application:

Step 1: 

I have downloaded the Play 2.0 from this link download.playframework.org/releases/play-2.0.zip  I have java version 1.7.0_01 in my machine. You need minimum java 1.6 or later.

Step 2: 

Unzip it and add the play directory to the working path. To check that the installation worked, I open a new command line and type play; it shows me the play basic usage help. So everything is ok to create my application.

Step 3: 
I execute the below command to create the application

E:\>play new hr-system


Now I use intellj to open this application to update. The play new command creates a new directory hr-system/ . Play also creates all the necessary files and directories:
  • app/  contains the application’s core, split between models, controllers and views directories. This is the directory where .scala source files live.
  • conf/ contains all the application’s configuration files, especially the main application.conf file, the routes definition files and the messages files used for internationalization.
  • project contains the build scripts. The build system is based on sbt (Simple Build Tool).
  • public/ contains all the publicly available resources, which includes JavaScript, stylesheets and images directories.

Step 4: 
Below commands are used to run the newly created application

E:\>cd hr-system

E:\hr-system>play

[hr-system] $ run


Step 5:

I open the browser and use the url http://localhost:9000 to see the application. It works. Great. 

Step 6:
To capture the details of the employees I need a database. I am going to use Play provided H2 for this. It is useful since I am going to do lot of testing and changes to my domain model. To set up the database I open hr-system/conf/application.conf and uncomment the below two lines:

db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play" 

Step 7:

It is useful to keep track and organize the database schema evolution. Play provides a way to do this using several evolution scripts. In my case I am going to add one script now, 1.sql under hr-system/conf/evolutions/default

# --- !Ups

set ignorecase true;

CREATE TABLE employee (
  id                             bigint not null auto_increment,
  name                           varchar(255) not null,
  age                            integer,
  gender                         char(1),
  address_id                     bigint,
  constraint pk_employee primary key (id)
);

CREATE TABLE address (
  id                             bigint not null auto_increment,
  street                         varchar(255) not null,
  city                           varchar(255),
  postcode                       varchar(30) not null,
  constraint pk_address primary key (id)
);

alter table employee add constraint fk_employee_address_1 foreign
key (address_id) references address (id) on delete restrict;

# --- !Downs

SET REFERENTIAL_INTEGRITY FALSE;

drop table if exists address;

drop table if exists employee;

SET REFERENTIAL_INTEGRITY TRUE;

The above script contains two parts:
  • The Ups part the describe the required transformations.
  • The Downs part that describe how to revert them.
Step 8:
Now it is time to create the model class and also write necessary code to query the database. I will use Anorm to interact with the database. I create Employee and Address case classes and also their helper objects in a file Employee.scala under hr-system/app/models/ .  First let me show the case classes:
 

case class Employee (
   id: Pk[Long] = NotAssigned,
   name: String,
   age:Number,
   gender:String,
   addressId:Option[Long]
)

case class Address (
   id: Pk[Long] = NotAssigned,
   street: String,
   city:String,
   postcode:String
)

I have implemented SQL queries in Employee and Address companion objects. I have also defined the below parsers to transform a JDBC ResultSet row to a Employee and Address value. 

In Employee helper object:


  /**
   * Parse a Employee from a ResultSet
   */
  val simple = {
     get[Pk[Long]]("employee.id") ~
     get[String]("employee.name") ~
     get[Int]("employee.age") ~
     get[String]("employee.gender") ~
     get[Option[Long]]("employee.address_id") map {
        case id~name~age~gender~addressId => 
          Employee(id, name, age, gender, addressId)
     }
  }

  /**
   * Parse a (Employee,Address) from a ResultSet
   */
  val withAddress = Employee.simple ~ Address.simple  map {
     case employee~address => (employee,address)
  }

In Address helper object:


 /**
   * Parse a Address from a ResultSet
   */
  val simple = {
      get[Pk[Long]]("address.id") ~
      get[String]("address.street") ~
      get[String]("address.city") ~
      get[String]("address.postcode") map {
        case id~street~city~postcode => Address(id, street, city, postcode)
      }
  }

Now let me show how I have used these parsers. For example the below method is responsible to return a list of employees with their address:


 /**
   *  Find all the employees
   */
  def all(): List[(Employee, Address)]= {
     DB.withConnection { implicit connection =>
     SQL("select * from employee join address on " +
     "employee.address_id = address.id").as(Employee.withAddress *)
  }

In Play we have DB.withConnection helper to create and release a JDBC connection automatically. In the above method I use the Anorm SQL method to create the query. The as method is used to parse the ResultSet using the Employee.withAddress * parser. It then return a List[(Employee, Address)]. The connection will be automatically closed at the end of the block.

Here is another example:


 /**
   *  Create an employee
   *
   *  @param name - Name of the employee
   *  @param age - Age of the employee
   *  @param gender - Gender of the employee
   *  @param street - Street of the employee
   *  @param city - City of the employee
   *  @param postcode - Postcode of the employee
   *
   */
  def create(name:String,  age:Number, gender:String,  
             street:String, city:String, postcode:String): Unit = {

     DB.withTransaction { implicit connection =>

        SQL("insert into address(street,city,postcode) " +
                "values ({street}, {city}, {postcode})").on(
           'street -> street,
           'city -> city,
           'postcode -> postcode
        ).executeUpdate()

        val addressId:Long = SQL("select id from address " +
                "order by id desc limit 1").as(scalar[Long].single)

        SQL("insert into employee(name,age,gender, address_id) " +
                "values ({name}, {age}, {gender}, {address_id})").on(
           'name -> name,
           'age -> age,
           'gender -> gender,
           'address_id -> addressId
        ).executeUpdate()
    }
  }

In the above code I use DB.withTransaction to manage a transaction for the block.

Step 9:
After creating the model class I create EmployeeController.scala under hr-system/app/controllers 


/**
 * This controller is responsible to manage employees' records
 */
object EmployeeController extends Controller {

  /**
   *  Employee form for creating and editing an employee
   */
  val employeeForm = Form(
     tuple(
        "name" -> text,
        "age" -> number,
        "gender" -> text,
        "street" -> text,
        "city" -> text,
        "postcode" -> text
     )
  )

  /**
   * Display the list of employee
   */

  def employees = Action {
     Ok(html.index(Employee.all()))
  }

  /**
   * Display the employee form to create an employee
   */
  def createForm = Action {
    Ok(html.createForm(employeeForm))
  }

  /**
   * Handle the employee form submission
   */
  def save = Action { implicit request =>
     employeeForm.bindFromRequest.fold(
        errors => BadRequest(html.createForm(errors)),
        {
           case (name, age, gender, street, city, postcode) =>
              Employee.create(name, age, gender, street, city, postcode)
              Redirect(routes.Application.index())
        }
     )
  }

  /**
   * Display the employee form to edit
   * @param id - Id of the employee to edit
   */
  def editForm(id: Long) = Action {
     val employeeMap = new HashMap[Int, String]
     Employee.findById(id).map {
        case (employee, address) => {
           employeeMap += 1 -> employee.name
           employeeMap += 2 -> employee.age.toString
           employeeMap += 3 -> employee.gender
           employeeMap += 4 -> address.street
           employeeMap += 5 -> address.city
           employeeMap += 6 -> address.postcode
        }
     }
     Ok(html.editForm(id, employeeForm.fill((employeeMap(1), 
  employeeMap(2).toInt, employeeMap(3), employeeMap(4), employeeMap(5),
 employeeMap(6)))))
  } 

  /**
   * Handle the employee form submission to edit
   * @param id - Id of the employee to be updated
   */
  def update(id: Long) = Action { implicit request =>
     employeeForm.bindFromRequest.fold(
        errors => BadRequest(html.editForm(id, errors)),
        {
           case (name, age, gender, street, city, postcode) =>
            Employee.update(id, name, age, gender, street, city, postcode)
              Redirect(routes.Application.index())
        }
    )
  }

  /**
   * Handle the request to delete an employee
   * @param id - Id of the employee to be deleted
   */
  def delete(id: Long) = Action {
     Employee.delete(id)
     Redirect(routes.Application.index())
  }
}

In the above controller class you will find I have used employerForm to capture all the data. The type of the employeeForm is Form[(String, Int, String, String, String, String)]. Though not shown above I have imported play.api.data classes. I use bindFromRequest to fill the form with the request data. In case of errors I redisplay it with BadRequest 400. I also use Redirect instead of Ok to specify a 303 See Other HTTP response type. 


Step 10:

Next step is to define router. The router is in charge of translating each incoming HTTP request to an Action. An HTTP request is seen as an event by the MVC framework. Each event contains two major pieces of information:
  • the request path including the query string. For example: /employees/13,
  • the HTTP method i.e. GET, POST, PUT, HEAD, etc.
All the routes are defined in hr-system/conf/routes file. Each route consists of an HTTP method and URI pattern, both associated with a call to an Action generator.


# Home page
GET /                         controllers.Application.index

# Employees
GET /employees                controllers.EmployeeController.employees()

# Add an employee
GET  /createForm              controllers.EmployeeController.createForm()
POST /save                    controllers.EmployeeController.save()

# Edit an employee
GET /employees/:id/editForm  controllers.EmployeeController.editForm(id:Long)
POST /employees/:id          controllers.EmployeeController.update(id:Long)

# Delete an employee
POST /employees/:id/delete  controllers.EmployeeController.delete(id:Long)


Step 11:

Now lets concentrate on creating views. At present this application has four web pages: 
  • main.scala.html template contains all the necessary includes.
  • index.scala.html template shows the list of employees
  • create.scala.html template is for creating an employee's record
  • edit.scala.html template is for editing
All these templates are added under hr-system/app/views. Here I am showing only create.scala.html and index.scala.html. Others you can see here.

create.scala.html


@(employeeForm: Form[(String, Int, String, String, String, String)])

@import helper._
@import helper.twitterBootstrap._

@main(title = "HR Solutions") {

@form(action = routes.EmployeeController.save) {

<fieldset>
    <:legend>Add Employee</legend>

    @inputText(
        field = employeeForm("name"),
        args = '_label -> "Name"
    )

    @inputText(
        field = employeeForm("age"),
        args = '_label -> "Age", '_size -> 3
    )

    @select(
        field = employeeForm("gender"),
        options = options(
            "" -> "Please select",
            "m" -> "Male",
            "f" -> "Female"
        ),
        args = '_label -> "Gender"
    )

    @inputText(
        field = employeeForm("street"),
        args = '_label -> "Street"
    )

    @inputText(
        field = employeeForm("city"),
        args = '_label -> "City"
    )

    @inputText(
        field = employeeForm("postcode"),
        args = '_label -> "Post Code"
    )

    <br/>

    <div class="actions">
        <input type="submit" value="Submit">
        <a href="@routes.Application.index">Cancel</a>
    </div>
</fieldset>
}
}


index.scala.html


@(employees: List[(Employee, Address)])

@import helper._

@main(title = "HR Solutions"){
<center>
<h2>HR Solutions</h2>

<h3>Total number of Employees: @employees.size</h3>

<table width="60%" border="1" align="center" text-align="center">
    <thead>
    <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Gender</th>
        <th>Street</th>
        <th>City</th>
        <th>Postcode</th>
        <th>Edit</th>
        <th>Delete</th>
    </tr>
    </thead>
    <tbody>
    @employees.map {
        case (employee, address) => {
        <tr align="center">
            <td>@employee.name</td>
            <td>@employee.age</td>
            <td>
                @if(employee.gender.equals("m")) {
                   Male
                } else {
                   Female
                }
            </td>
            <td>@address.street</td>
            <td>@address.city</td>
            <td>@address.postcode</td>
            <td>
      @form(action = routes.EmployeeController.editForm(employee.id.get)) {
         <input type="submit" value="Edit">
      }
            </td>
            <td>
      @form(routes.EmployeeController.delete(employee.id.get)) {
         <input type="submit" value="Delete">
      }
            </td>
        </tr>
        }
    }
    </tbody>
</table>
<br/>
<a href="/createForm">Add a new employee</a>
</center>
}


Conclusion
In this article I have demonstrated how to create a CRUD application using Play 2.0 framwork. It is a good and productive learning phase for me. As I am new to Scala and Play you may find some mistakes in the code. So your feedback is most welcome.  In future articles I will extend and improve this application by adding other features using Play. Please check the code https://github.com/sanjoykroy/hr-system

Tuesday 31 January 2012

Data Flow Concurrency, STM and Message-Passing Concurrency - Alternate options to write concurrent program

Introduction

Last year Venkat Subramaniam wrote a book called Programming Concurrency in JVM. In this book he outlined the concurrency techniques using different JVM programming languages such as Java, Clojure, Scala, Groovy and JRuby.  In this book he talked about three concurrency style - synchronization model of JDK, Software Transactional Memory and Actor based concurrency.  An excellent book for someone who wants to learn the alternate options that are available in different JVM based programming languages. In this article I will write down Shared State Concurrency and problems associated with it and also briefly outline how these problems can be solved using alternative approaches like Dataflow concurrency, Software Transactional Memory and Message-passing concurrency. At first let me talk about Shared State concurrency and its problem.

Shared State Concurrency

One of the desired characteristic that we want to have in our program is the ability to deal with several independent activities, each of which executes at its own pace, which is called "concurrency". There should be no interference between the activities, unless we want them to communicate. How do we introduce concurrency in our program? It is simple. We can do this by creating threads. A thread is simply an executing program. A program can have more than one thread. All threads share the same underlying computer. They may access a set of shared passive objects. Threads coordinate with each other when accessing these shared objects. They do this by means of coarse-grained atomic actions such as locks, monitors, transactions etc. What I have written so far in this paragraph falls under Shared State Concurrency. A formal definition is given below:

"Shared State Concurrency is concurrency among two or more processes (here, a process is a flow of control), which have some shared state between them, which both processes can read to and write from." [1]

It adds explicit state in the form of cells, which are a kind of mutable variables.

Shared State Concurrency is hard, why?
  • Execution consists of multiple threads, all executing independently and all accessing shared cells.
  • Requires lots of synchronization primitives (locks, mutex, semaphores, etc) to protect mutable states
  • Much more difficult to model and prove a system is correct.
In Shared State Concurrency we need to protect mutable state with locks. Writing correct program using lock is not easy thing because of the below reasons:
  • enforcing lock ordering 
  • locks do not compose
  • taking too few locks or too many locks
  • taking the wrong locks
  • taking locks in the wrong order
  • error recovery and debuging is hard
As a Java programmer we start our concurrency journey using the concept outlined above. We use different concurrency primitives like lock, synchronized along with our business logic. Lot of concurrency related plumbing work which make our program difficult to understand. It is also difficult to write the unit test.  Java is an Object Oriented (OO) Programming language. OO typically unifies identity and state, i.e. an object (identity) is a pointer to the memory that contains the value of its state. Problem lies in the unification of identity and value, which are not same. In OO state is everywhere. There is no way to observe a stable state without blocking others from chaging it. We need to guard the state [2]. Immutable state is ok but mutable state is the problem. We need a better way of dealing mutable state. You can read more on this from http://clojure.org/state .

Alternate approaches

But if you want solve your concurrency problem using a JDK solution then you must read JAVA Concurrency in Practice by Brian Goetz. This book is the bible on how to deal with concurrency in Java and also try to use java.util.concurrent API.  But if you are open to use some other jvm based alternative concurrency solutions then you will be happy to know that there are options available like:
  • Dataflow Concurrency (Dataflow - Single Assignment variables)
  • Software Transactional Memory (Managed References)
  • Message-Passing Concurrency (Actors/Active Objects/Agents)
Dataflow Concurrency

"Operations (in Dataflow programs) consist of 'black boxes' with inputs and outputs, all of which are always explicitly defined. They run as soon as all of their inputs become valid, as opposed to when the program encounters them. Whereas a traditional program essentially consists of a series of statements saying "do this, now do this", a dataflow program is more like a series of workers on an assembly line, who will do their assigned task as soon as the materials arrive. This is why dataflow languages are inherently parallel; the operations have no hidden state to keep track of, and the operations are all 'ready' at the same time." [3]

The core idea:
  • Number of allowed variable assignment is limited to one
  • A variable (Dataflow variable) can only be assigned a value once in its lifetime, while the number of reads is unlimited
  • Reads preceding the write operations are postponed (blocked) until the value is set by a write (bind) action

    The beauty of Dataflow Concurrency is its determinism. This type of program always behave in a same way. If you execute the program once and it gives you 10 then it will always give you that value no matter how many times you run the same program. If it throws exception once then it will always throw that exception.   It is also called declarative or data driven concurrency model. In a declarative concurrent model, the nondeterminism is not visible to the programmer because of the two reasons:
    • Dataflow variables can be bound to only one value.
    • Any operation that needs the value of a variable has no choice but to wait until the variable is bound. If we allow operations that could choose whether to wait or not then the nondeterminism would become visible.[1]
    Three Operations:
    • Create a dataflow variable
                val x = new DataFlowVariable[Int]
    • Wait for the variable to be bound
                x()
    • Bind the variable
               x << 5

    Dataflow variables are monotonic. It means that they can be bound to just one value and once bound, the value does not change. On the other hand mutable variables are non-monotonic. They can be assigned any number of times to values that have no relation to each other. Threads that share a mutable variable cannot make any assumption about its content. At any time the content can be completely different from the previous content [1]. Dataflow variable does not suffer from this problem.

    Dataflow concurrency also does not introduce race condition. It works on-demand and lazy way. There are few limitations though:
    • It cannot have side effects like exceptions, IO (File, println, file socket), time etc.
    • Not general purpose. It is generally good for work flow related dependent processes like business processes.
    You can read more on this from  http://gpars.codehaus.org/Dataflow.

    Software Transactional Memory

    You might have heard about ACID properties of database management system. Using STM you get ACIDness without D. I mean you get atomicity, consistency and isolation in memory without durability. Since everything (begin-commit and rollback) happens in memory, it is extremely fast. A formal definition is given below:

    "software transactional memory (STM) is a concurrency control mechanism analogous to database transactions for controlling access to shared memory in concurrent computing." [4]

    STM actually turns Java heap into a transactional data set. A block of actions will be executed as a transaction. This block is atomic, isolated and consistent. Atomic means that every changes to this block within transaction occurs or none. Within this block a series of read and write can be executed and these reads and writes logically occur at a single instance of time. When we enter the block and start executing the code, other threads cannot see the changes made our threads until we exit. Our threads will also not see the changes made by other threads.  So completely isolated. And it is consistent, means each new value can be checked with a validator function before allowing the transaction to commit. Other threads can only see the committed changes. When a transaction has a conflict while running, it will automatically retried.

    Transactions can nest and compose:

    atomic {
        .........
        atomic {
            ......
        }
    }

    When you write atomic STM executes it automatically without deadlocks and races.

    You will find STM implemented in different programming languages like Scala, Java, Haskell, Clojure, Python, Common Lisp, Perl, C/C++. You will also get STM implementation in Akka and there is also ScalaSTM. You can get a full list in http://en.wikipedia.org/wiki/Software_transactional_Memory 

    Here I will show a simple example in Akka. More examples can be found http://akka.io/docs/akka/1.2/scala/stm.html . In Akka Ref is a transactional reference and can only be changed in a transaction, which is delimited by atomic. These updates to Ref are atomic and isolated.

    import akka.stm._

    val ref = Ref(0)

    atomic {
        ref.set(5)
    }

    // -> 0

    atomic {
       println(ref.get)
    }

    // -> 5

    Though STM allows us to write simple and beautiful code, it is not totally problem free. Jonas Boner of Akka (now TypeSafe) mentioned in his presentation http://www.slideshare.net/jboner/state-youre-doing-it-wrong-javaone-2009 - "high contention (many transaction collisions) can lead to: potential bad performance and too high latency, progress can not be guaranteed (e.g. live locking), Fairness is not mantained, implementation details hidden in black box".

    Message-Passing Concurrency

    In Message-Passing Concurrency two or more processes (here, process is a flow of control) communicate with each other by passing messages. There is no shared regions between these processes. All the computations are done in processes and only way to exchange data is through asynchronous message passing. 

    Message-Passing Concurrency have been popularized by Erlang language. Two other languages Oz and Occam also implemented this.
    Actor model concurrency implements Message-Passing Concurrency. Actor model enforces that there is nothing like shared state. Actor can run in different threads and the only way an actor can influence another actor is by sending him a message and have him update his state internally.It is not possible to go into it and temper his state. It provides really nice isolation of state as a very explicit state management. It removes all of the problems that we normally have with mutable shared state in a concurrent setting.

    This is how actor works in Akka:
    1. Each actor has a mail box. It can send and receive messages.
    2. There is a scheduler that can wake up an actor, resume it, have it being applied to the messages that it has in the mail box
    3. Since an actor has a mailbox, it can still receive messages that will be put in the mailbox while it is passive.
    4. An actor can execute X number of messages before it is suspended and another actor can use the same thread that the suspended actor was just using.
    Actors are extremely ligthweight. So actors only consumes memory, they do not sit on a thread. In thread based model, threads are extremely heavyweight. It is only possible to run X number of threads on the JVM while it is possible to run millions of actors easily since actor is only constrained by memory. Actors never do anything unless being told.

    Here is the preferred way sending a message to a actor:

    actor ! "Hello"

    Example in Akka:

    class MyActor extends Actor {
      def receive = {
        case "test" => println("received test")
        case _ => println("received unknown message")
      }
    }

    val myActor = Actor.actorOf[MyActor]
    myActor.start()

    myActor ! "test"


    Output: test

    In the above example we have created an actor called MyActor by extending Actor class. We have also implemented the receive method. We have provided a pattern match for all messages that this actor can accept and since we also want our actor to handle unknown messages, there is a default case for this in the example above. We send a message "test" to our actor in a fire-and-forget fashion.


    Using Actor model it is possible to avoid
    1. Race conditions
    2. Deadlocks
    3. Starvation
    4. Live locks

    References:
    1. Concepts, Techniques, and Models of Computer Programming by Peter Van Roy and Seif Harid, 2003
    2.  http://clojure.org/state
    3.  http://www.gpars.org/guide/guide/7.%20Dataflow%20Concurrency.html
    4.  http://en.wikipedia.org/wiki/Software_transactional_memory
    5.  http://www.slideshare.net/jboner/state-youre-doing-it-wrong-javaone-2009
    6.  http://akka.io