Skip to content

Commit

Permalink
[refactor] executor's thread factory
Browse files Browse the repository at this point in the history
  • Loading branch information
kares committed Jun 1, 2022
1 parent 5e1f82b commit 683bfb7
Showing 1 changed file with 19 additions and 11 deletions.
30 changes: 19 additions & 11 deletions lib/manticore/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,24 @@ class Client
# This is a class rather than a proc because the proc holds a closure around
# the instance of the Client that creates it.
class ExecutorThreadFactory
include ::Java::JavaUtilConcurrent::ThreadFactory
include java.util.concurrent.ThreadFactory

java_import 'java.lang.Thread'

@@factory_no = java.util.concurrent.atomic.AtomicInteger.new

def initialize(client)
@thread_no = java.util.concurrent.atomic.AtomicInteger.new
@name_prefix = "manticore##{client.object_id}-#{@@factory_no.increment_and_get}-"
end

def newThread(runnable)
thread = Executors.defaultThreadFactory.newThread(runnable)
thread.daemon = true
return thread
thread = Thread.new(runnable, @name_prefix + @thread_no.increment_and_get.to_s)
thread.setDaemon(true)
thread
end
end
private_constant :ExecutorThreadFactory

include ProxiesInterface

Expand Down Expand Up @@ -357,8 +367,7 @@ def close

# Get at the underlying ExecutorService used to invoke asynchronous calls.
def executor
create_executor_if_needed
@executor
@executor ||= create_executor
end

def self.shutdown_on_finalize(client, objs)
Expand Down Expand Up @@ -425,17 +434,16 @@ def socket_config_from_options(options)
socket_config_builder.build
end

def create_executor_if_needed
return @executor if @executor
@executor = Executors.new_cached_thread_pool(ExecutorThreadFactory.new)
finalize @executor, :shutdown
def create_executor
executor = Executors.new_cached_thread_pool(ExecutorThreadFactory.new(self))
finalize executor, :shutdown
executor
end

def request(klass, url, options, &block)
req, context = request_from_options(klass, url, options)
async = options.delete(:async)
background = options.delete(:async_background)
create_executor_if_needed if (background || async)
response = response_object_for(req, context, &block)

if async
Expand Down

0 comments on commit 683bfb7

Please sign in to comment.