Created
April 24, 2014 00:05
-
-
Save seansu4you87/11236841 to your computer and use it in GitHub Desktop.
Using Executor in jruby
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
# Start the executor service. Note that this won't create any threads right away, | |
# but will create new threads as the jobs are submitted, until it gets to 5 threads. | |
# Then it will reuse the threads. | |
executor = java.util.concurrent.Executors.newFixedThreadPool(5) | |
# Submit jobs, get back java.util.concurrent.FutureTask objects. | |
future_tasks = [1, 2, 3, 4, 5, 6].map do |number| | |
executor.submit do | |
puts "starting work" | |
sleep(10) | |
puts "done" | |
end | |
end | |
# We get control back immediately, while the queries are being executed by the thread pool. | |
# We can do some other things here while the queries run. | |
# Get the results of all queries and combine them into an array. FutureTask.get will wait | |
# for the task to complete if it's not completed yet, so it's safe to call this right away. | |
# If for some reason we wanted to check if a task is complete, we can call t.done? . | |
results = future_tasks.map do |future_task| | |
begin | |
# Max timeout for each thread is 10 seconds | |
future_task.get(10, java.util.concurrent.TimeUnit::SECONDS) | |
rescue java.util.concurrent.ExecutionException, java.util.concurrent.TimeoutException => e | |
if e.is_a? java.util.concurrent.TimeoutException | |
raise TimeoutError | |
else | |
# Convert the exception to one actually thrown inside the task. | |
raise e.cause.exception | |
end | |
end | |
end | |
# Shut down the thread pool. | |
executor.shutdown_now |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
source: http://blog.bitmelt.com/2013/05/concurrent-tasks-in-jruby.html