Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Workaround for JRuby's timeout not working well with IO.popen
# 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
@toddthomas

This comment has been minimized.

Copy link

commented Apr 4, 2013

Thank you so much for this! Fixes timeout for me in a case where it wasn't working. I had to change seconds on line 13 to sec.

@arielvalentin

This comment has been minimized.

Copy link

commented Aug 23, 2013

Did you file a bug with the JRuby team?

@headius

This comment has been minimized.

Copy link

commented Aug 18, 2014

The test case provided appears to work fine with JRuby master (9000) which has reimplemented process-launching. I'll see if there's anything that can be done with the interrupt logic on 1.7.x.

@headius

This comment has been minimized.

Copy link

commented Aug 18, 2014

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.