Skip to content

Instantly share code, notes, and snippets.

@fipar
Created March 14, 2014 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fipar/9539935 to your computer and use it in GitHub Desktop.
Save fipar/9539935 to your computer and use it in GitHub Desktop.
thread safe attribute accessors using clojure Atoms
require "java"
class Class
def atom_attr_accessor(*args)
self.class_eval("
require 'clojure.jar'
java_import 'clojure.lang.LockingTransaction'
java_import 'clojure.lang.Atom'
")
args.each do |arg|
self.class_eval("
def #{arg}
@#{arg}.deref unless @#{arg}.nil?
end
def #{arg}=(val)
if @#{arg}.nil?
@#{arg} = Atom.new(val)
else
@#{arg}.reset val
end
end
")
end
end
end
class ThreadSafeVar
atom_attr_accessor :id, :name
end
v = ThreadSafeVar.new
v.id = 1
v.name = "test"
puts "meet v: "
puts v.id
puts v.name
puts "now let's fire up concurrent threads to change v.id, and check its value every second while they run"
Thread.new {v.id = v.id + 10; puts "thread 1 done"}
Thread.new {v.id = v.id + 1; puts "thread 2 done"}
Thread.new {v.id = v.id + 5; puts "thread 3 done"}
# give them some time
sleep 2
puts "new value: #{v.id}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment