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' }
end

attr_accessor :foo
end

obj = MyClojureObj.new
puts "obj.foo = " + obj.foo

begin
puts "Setting obj.foo to 'bar'"
obj.foo = 'bar'
rescue ConcurrencyError
puts "Oops, need a transaction"
end

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

puts "obj.foo = " + obj.foo


Some pretty good abstractions of using dosync and Refs in STM. So how do we use it?
Clone the code from http://github.com/headius/cloby/blob/. 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 = ClojureLibrary.new
clj_lib.load(JRuby.runtime, true)


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

2 comments:

Guy Korland said...

Hi,

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.

See: http://www.deucestm.org/

Sai Venkatakrishnan said...

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