Last active
December 1, 2017 17:43
-
-
Save midhunkrishna/840d162d9712c11463196dd1f823592a 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
module ConcurrentExecutor | |
class Error < StandardError | |
def initialize(exceptions) | |
@exceptions = exceptions | |
super | |
end | |
def message | |
@exceptions.map { | e | e.message }.join "\n" | |
end | |
def backtrace | |
trace = @exceptions.map { |e| e.backtrace }.join("\n") | |
"ConcurrentExecutor::Error START\n #{trace} \nEND \n" | |
end | |
end | |
class Promise | |
def initialize(pool: nil) | |
@pool = pool || Concurrent::FixedThreadPool.new(20) | |
@exceptions = Concurrent::Array.new | |
end | |
# Sample Usage | |
# executor = ConcurrentExecutor::Promise.new(pool: pool) | |
# executor.execute(carriers) do | carrier | | |
# ... | |
# end | |
# | |
# values = executor.resolve | |
def execute array, &block | |
@futures = array.map do | element | | |
Concurrent::Promise.execute({ executor: @pool }) do | |
yield(element) | |
end.rescue do | exception | | |
@exceptions << exception | |
end | |
end | |
self | |
end | |
def resolve | |
values = @futures.map(&:value) | |
if @exceptions.length > 0 | |
raise ConcurrentExecutor::Error.new(@exceptions) | |
end | |
values | |
end | |
end | |
end |
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
executor = ConcurrentExecutor::Promise.new.execute(carriers) do |carrier| | |
# ... | |
end | |
values = [] | |
begin | |
values = executor.resolve | |
rescue ConcurrentExecutor::Error => e | |
raise e | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment