Last active
August 29, 2015 14:01
-
-
Save Gonzih/f62ccc35a9d4d8d23ba0 to your computer and use it in GitHub Desktop.
Fun with cuncurrency 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
class Future | |
include java.util.concurrent.Callable | |
@@executor = java.util.concurrent.Executors::newFixedThreadPool(5) | |
def initialize(&block) | |
@block = block | |
end | |
def on_success(&block) | |
@on_success = block | |
self | |
end | |
def on_error(&block) | |
@on_error = block | |
self | |
end | |
def run | |
@future = @@executor.submit(self) | |
end | |
def get | |
@future.get | |
end | |
def call | |
result = begin | |
@block.call | |
rescue Exception => e | |
@on_error.call(e) unless @on_error.nil? | |
raise e | |
end | |
@on_success.call unless @on_success.nil? | |
result | |
end | |
def self.pool_size=(num) | |
@@executor.core_pool_size = num | |
end | |
def self.pool_size | |
@@executor.core_pool_size | |
end | |
end | |
f = Future.new { sleep 1; puts "1"; 1 } | |
f.on_success do | |
puts 'everything is fine!' | |
end.on_error do |e| | |
puts 'error!' | |
end | |
f.run | |
f.get |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you need to submit the Callable and not the block (getting "caster" to another Callable) :
@future = @@executor.submit(self)