Skip to content
Browse files

Add ThreadSafe::Cache#each_pair method.

  • Loading branch information...
1 parent 8ddd26b commit 4612a6ee62568db5905ef986ed897402dbf26ac7 @thedarkone thedarkone committed Jun 29, 2012
View
12 examples/bench_cache.rb
@@ -6,7 +6,9 @@
hash = {}
cache = ThreadSafe::Cache.new
-10_000.times do |i|
+ENTRIES = 10_000
+
+ENTRIES.times do |i|
hash[i] = i
cache[i] = i
end
@@ -22,4 +24,12 @@
results.report('Cache#[]') do
TESTS.times { cache[key] }
end
+
+ results.report('Hash#each_pair') do
+ (TESTS / ENTRIES).times { hash.each_pair {|k,v| v} }
+ end
+
+ results.report('Cache#each_pair') do
+ (TESTS / ENTRIES).times { cache.each_pair {|k,v| v} }
+ end
end
View
10 ext/org/jruby/ext/thread_safe/ConcurrentCacheBackendLibrary.java
@@ -1,11 +1,13 @@
package org.jruby.ext.thread_safe;
import java.io.IOException;
+import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.jruby.*;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
+import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
@@ -96,5 +98,13 @@ public IRubyObject clear() {
map.clear();
return this;
}
+
+ @JRubyMethod
+ public IRubyObject each_pair(ThreadContext context, Block block) {
+ for (Map.Entry<IRubyObject,IRubyObject> entry : map.entrySet()) {
+ block.yieldSpecific(context, entry.getKey(), entry.getValue());
+ }
+ return this;
+ }
}
}
View
7 lib/thread_safe/non_concurrent_cache_backend.rb
@@ -27,5 +27,12 @@ def clear
@backend.clear
self
end
+
+ def each_pair
+ @backend.each_pair do |k, v|
+ yield k, v
+ end
+ self
+ end
end
end
View
19 lib/thread_safe/synchronized_cache_backend.rb
@@ -22,5 +22,24 @@ def delete(key)
def clear
synchronize { super }
end
+
+ def each_pair
+ collection = []
+ synchronize do
+ super do |k, v|
+ collection << k << v
+ end
+ end
+
+ i = 0
+ total = collection.length
+
+ while i < total
+ yield collection[i], collection[i + 1]
+ i += 2
+ end
+
+ self
+ end
end
end
View
15 test/test_cache.rb
@@ -87,6 +87,21 @@ def test_clear
assert_equal nil, @cache[:a]
end
+ def test_each_pair
+ @cache.each_pair {|k, v| flunk}
+ assert_equal(@cache, (@cache.each_pair {}))
+ @cache[:a] = 1
+
+ h = {}
+ @cache.each_pair {|k, v| h[k] = v}
+ assert_equal({:a => 1}, h)
+
+ @cache[:b] = 2
+ h = {}
+ @cache.each_pair {|k, v| h[k] = v}
+ assert_equal({:a => 1, :b => 2}, h)
+ end
+
def test_options_validation
assert_valid_options(nil)
assert_valid_options({})

0 comments on commit 4612a6e

Please sign in to comment.
Something went wrong with that request. Please try again.