Groovy and STM

May 18, 2010

Yesterday evening I was playing with some initial support for Groovy in Multiverse; a software transactional memory implementation for Java. And with the help of Alex Tkachman is was easy to get up some initial support.

If you want to have a transactional reference (similar to a ref in Clojure), you can just create a Ref (or in this case a LongRef):

class Account{
   final LongRef balance = new LongRef();

   void long getBalance(){balance.get()}

   void setBalance(long newBalance){
            throw new InsufficientFundsException();

And if you want to have an atomic block, you can execute the following:

    Account from = new Account(10)
    Account to = new Account(10)

    atomic(readonly:false, trackreads:true) {
      from.balance -= 5
      to.balance += 5

    println "from $from.balance"
    println "to $to.balance"

The parameters in the atomic block are not needed (Multiverse is able to infer some settings and in the future more inference will be added), but I wanted to see if it was possible. Having closure support in a language, increases language complexity, but imho makes a language a lot easier to use and less painful on the eyes.

There is more clutter that can be removed, but I really need to polish my Groovy skills. Groovy support is going to be added to Multiverse 0.6 (expected in 6/8 weeks). I haven’t checked in the new groovy support on the snapshot, so contact me if you want to play with it.