Fork me on GitHub

Friday, February 19, 2010

Software Transactional Memory in JRuby - Redux with Cloby

After I wrote about using Clojure's Software Transactional Memory infrastructure in JRuby in my previous post. @headius has written an awesome wrapper Cloby in Java to use Clojure STM in JRuby and writing Ruby objects which can be used as Clojure Refs.

Here is an example code of using a Ruby object in STM.

require 'clojure'

class MyClojureObj < Clojure::Object
def initialize
dosync { @foo = 'foo' }

attr_accessor :foo

obj =
puts " = " +

puts "Setting to 'bar'" = 'bar'
rescue ConcurrencyError
puts "Oops, need a transaction"

puts "Trying again with a transaction"
dosync { = 'bar' }
puts "Success"

puts " = " +

Some pretty good abstractions of using dosync and Refs in STM. So how do we use it?
Clone the code from Build ClojureLibrary.jar with clojure and jruby.jar. Keep ClojureLibrary.jar and clojure.jar in classpath.
And here is the bridge I wrote between your awesome code using STM and ClojureLibrary.jar

#!/usr/bin/env jruby

require "java"
require "ClojureLibrary.jar"
require "clojure-1.0.0.jar"
include_class "org.jruby.clojure.ClojureLibrary"

clj_lib =
clj_lib.load(JRuby.runtime, true)

Now its pretty easy to use Clojure's STM. No raw usage of LockingTransactions or Refs. Enjoy Cloby... :)


Guy Korland said...


Did you try to use DeuceSTM in JRuby?
It seems like it should much easier isn't it?
DeuceSTM is an STM for Java applications.


Sai Venkatakrishnan said...

Interesting... I would try this out with JRuby. Thanks for this..