Created
December 23, 2011 10:44
-
-
Save m0wfo/1513847 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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