Skip to content

Instantly share code, notes, and snippets.

@m0wfo
Created December 23, 2011 10:44
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 m0wfo/1513847 to your computer and use it in GitHub Desktop.
Save m0wfo/1513847 to your computer and use it in GitHub Desktop.
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