Skip to content

Instantly share code, notes, and snippets.

@headius
Last active August 29, 2015 14:19
Show Gist options
  • Save headius/3807e0180e83ed7c98a2 to your computer and use it in GitHub Desktop.
Save headius/3807e0180e83ed7c98a2 to your computer and use it in GitHub Desktop.
Performance improvements for concurrent-ruby's Executor
diff --git a/lib/concurrent/executor/executor.rb b/lib/concurrent/executor/executor.rb
index d97b537..82cdb67 100644
--- a/lib/concurrent/executor/executor.rb
+++ b/lib/concurrent/executor/executor.rb
@@ -290,12 +290,23 @@ module Concurrent
caller_runs: java.util.concurrent.ThreadPoolExecutor::CallerRunsPolicy
}.freeze
+ class Job
+ include Runnable
+ def initialize(args, block)
+ @args = args
+ @block = block
+ end
+
+ def run
+ @block.call(*@args)
+ end
+ end
+
# @!macro executor_method_post
def post(*args, &task)
raise ArgumentError.new('no block given') unless block_given?
return handle_fallback(*args, &task) unless running?
- executor_submit = @executor.java_method(:submit, [Runnable.java_class])
- executor_submit.call { yield(*args) }
+ @executor.submit_runnable Job.new(args, task)
true
rescue Java::JavaUtilConcurrent::RejectedExecutionException
raise RejectedExecutionError
diff --git a/lib/concurrent/executor/java_single_thread_executor.rb b/lib/concurrent/executor/java_single_thread_executor.rb
index 7931734..dd6e54b 100644
--- a/lib/concurrent/executor/java_single_thread_executor.rb
+++ b/lib/concurrent/executor/java_single_thread_executor.rb
@@ -20,6 +20,11 @@ if Concurrent.on_jruby?
# @see http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html
def initialize(opts = {})
@executor = java.util.concurrent.Executors.newSingleThreadExecutor
+ if !defined?(@executor.submit_runnable)
+ @executor.class.class_eval do
+ java_alias :submit_runnable, :submit, [java.lang.Runnable.java_class]
+ end
+ end
@fallback_policy = opts.fetch(:fallback_policy, :discard)
raise ArgumentError.new("#{@fallback_policy} is not a valid fallback policy") unless FALLBACK_POLICIES.keys.include?(@fallback_policy)
self.auto_terminate = opts.fetch(:auto_terminate, true)
diff --git a/lib/concurrent/executor/java_thread_pool_executor.rb b/lib/concurrent/executor/java_thread_pool_executor.rb
index d9ba7c5..8811141 100644
--- a/lib/concurrent/executor/java_thread_pool_executor.rb
+++ b/lib/concurrent/executor/java_thread_pool_executor.rb
@@ -75,6 +75,11 @@ if Concurrent.on_jruby?
min_length, max_length,
idletime, java.util.concurrent.TimeUnit::SECONDS,
queue, FALLBACK_POLICIES[@fallback_policy].new)
+ if !defined?(@executor.submit_runnable)
+ @executor.class.class_eval do
+ java_alias :submit_runnable, :submit, [java.lang.Runnable.java_class]
+ end
+ end
self.auto_terminate = opts.fetch(:auto_terminate, true)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment