Skip to content

Instantly share code, notes, and snippets.

@headius
Created September 23, 2011 05:55
Show Gist options
  • Save headius/1236833 to your computer and use it in GitHub Desktop.
Save headius/1236833 to your computer and use it in GitHub Desktop.
Thread dumping signal implemented in Ruby code? No problem!
system ~/projects/jruby $ jruby -rjruby/thread_dump -e "Thread.new{ loop{ 'hello' } }.join"
^Z
[1]+ Stopped jruby -rjruby/thread_dump -e "Thread.new{ loop{ 'hello' } }.join"
system ~/projects/jruby $ bg
[1]+ jruby -rjruby/thread_dump -e "Thread.new{ loop{ 'hello' } }.join" &
system ~/projects/jruby $ kill -USR2 %1 ; sleep 1
Ruby Thread Dump
================
* Thread: main
* Stack:
RuntimeError: thread dump
join at org/jruby/RubyThread.java:521
(root) at -e:1
* Thread: RubyThread-1: -e:1
* Stack:
RuntimeError: thread dump
__file__ at -e:1
loop at org/jruby/RubyKernel.java:1343
__file__ at -e:1
call at org/jruby/RubyProc.java:270
call at org/jruby/RubyProc.java:224
require 'jruby'
begin
handler = proc do
cur_thread = Thread.current
$stderr.puts "\nRuby Thread Dump\n================\n"
thread_service = JRuby.runtime.thread_service
trace_type = org.jruby.runtime.backtrace.TraceType
for thread in thread_service.active_ruby_threads
next if thread == cur_thread
thread_r = JRuby.reference(thread)
$stderr.puts "* Thread: #{thread_r.native_thread.name}"
$stderr.puts "* Stack:"
thread_r = JRuby.reference(thread)
thread_context = thread_r.context
unless thread_context
$stderr.puts " [dead]\n"
next
end
ex = RuntimeError.new('thread dump')
ex_r = JRuby.reference(ex)
gather = trace_type::Gather::NORMAL
format = trace_type::Format::JRUBY
ex_r.backtrace_data = gather.get_backtrace_data(thread_context, thread_r.native_thread, true)
$stderr.puts format.print_backtrace(ex, false)
$stderr.puts
end
end
Signal.__jtrap_kernel(handler, 'USR2')
rescue ArgumentError
$stderr.puts "failed handling USR2; 'jruby -J-XX:+UseAltSigs ...' to disable JVM's handler"
rescue Exception
warn $!.message
warning $!.backtrace
end
@scizo
Copy link

scizo commented Mar 3, 2014

@headius Do you have something like this that would work for jruby-1.7.8? I got the following error when trying to run this:

NameError: no method 'getBacktraceData' for arguments (org.jruby.runtime.ThreadContext,java.lang.Thread,org.jruby.RubyBoolean.True) on Java::OrgJrubyRuntimeBacktrace::TraceType::Gather::
    from (irb):34:in `evaluate'
    from org/jruby/java/proxies/ArrayJavaProxy.java:138:in `each'
    from (irb):12:in `evaluate'
    from org/jruby/RubyProc.java:271:in `call'
    from (irb):50:in `evaluate'
    from org/jruby/RubyKernel.java:1123:in `eval'
    from org/jruby/RubyKernel.java:1519:in `loop'
    from org/jruby/RubyKernel.java:1284:in `catch'
    from org/jruby/RubyKernel.java:1284:in `catch'
    from /Users/snielsen/.rbenv/versions/jruby-1.7.8/bin/irb:13:in `(root)'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment