Created
November 11, 2011 00:59
-
-
Save jorgenpt/1356797 to your computer and use it in GitHub Desktop.
Workaround for JRuby's timeout not working well with IO.popen
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
# Workaround for IO.popen.readlines being allowed to block indefinitely even if | |
# wrapped in a Timeout::timeout call. | |
# | |
# Test case: | |
# $ time jruby -rtimeout -e "timeout(1) { IO.popen('sleep 10').readlines }" | |
require 'jruby' | |
module Timeout | |
def self.timeout(sec, klass=nil) | |
return yield(sec) if sec == nil or sec.zero? | |
thread = Thread.new { yield(sec) } | |
if thread.join(seconds).nil? | |
java_thread = JRuby.reference(thread) | |
thread.kill | |
java_thread.native_thread.interrupt | |
thread.join(0.15) | |
raise (klass || Error), 'execution expired' | |
else | |
thread.value | |
end | |
end | |
end | |
include Timeout |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: one problem with the above hack is that interrupting a blocking Java IO read (as is happening here) generally closes the underlying stream and it can no longer be used. That's why we've gone back and forth on whether to do a hard Thread interrupt or just block.