Clojure STM in JRuby


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  1. require "java"
  2. require "clojure.jar"
  3. include_class "clojure.lang.LockingTransaction"
  4. include_class "clojure.lang.Ref"
  5.  
  6. my_account = Ref.new(1)
  7.  
  8. puts "Initial value #{my_account.deref}"
  9.  
  10. begin
  11. my_account.set(1000)
  12. rescue java.lang.IllegalStateException
  13. puts "Reference updated outside a transaction.. Naughty.. :)"
  14. end
  15.  
  16. puts "Value after failed update #{my_account.deref}"
  17.  
  18. Thread.new {LockingTransaction.run_in_transaction(Proc.new { my_account.set 1000 })}
  19.  
  20. Thread.new {LockingTransaction.run_in_transaction(Proc.new { sleep 0.1; my_account.set 21000 })} # Will fail because get commited after first transaction
  21.  
  22. puts "Value after successful transaction #{my_account.deref}"

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.