Skip to content

Instantly share code, notes, and snippets.

@m0wfo

m0wfo/gist:1513847

Created Dec 23, 2011
Embed
What would you like to do?
require 'java'
java_import java.util.concurrent.Executors
java_import java.lang.System
def benchmark(&work)
before = System.nanoTime
work.call
after = System.nanoTime
p "That took #{(after - before)/1E9}s"
end
class Something
attr_reader :value
def initialize(value)
@queue = Executors.newSingleThreadExecutor
@value = value
@lock = java.util.concurrent.locks.ReentrantLock.new
end
def inc
@queue.execute { @value += 1 }
end
def inc_locked
@lock.lock
@value += 1
@lock.unlock
end
def finalize
@queue.shutdown
end
end
s = Something.new(0)
# Async :(
benchmark do
workers = 3.times.map { Thread.new { 1E3.to_i.times { s.inc } } }
workers.map { |w| w.join }
end
# Locked :)
benchmark do
workers = 3.times.map { Thread.new { 1E3.to_i.times { s.inc_locked } } }
workers.map { |w| w.join }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.