1

I have an API that returns handles to background processes. These handles themselves have some threads as instance variables. I want to avoid forcing the user to call an explicit cleanup method to call .join on the threads. The threads themselves will finish their work sooner or later. Here are my questions:

  • What happens if there are no remaining references in the program to my object? Will it get garbage collected as usual? Do the threads get stopped in some way?
  • What happens if I don't call .join on a thread, but it finishes its work? Does it get garbage collected and totally cleaned up as I'd called .join anyways?

1 Answer 1

1

Taken from ruby-doc:

If we don't call thr.join before the main thread terminates, then all other threads including thr will be killed.

You can observe this yourself:

#!/usr/bin/env ruby

# Example worker thread with a pretend workload
Thread.new do
  puts "Secondary thread working"
  sleep(100)
  puts "Secondary thread finished"
ensure
  puts "Secondary thread exiting"
end

# Main thread with a pretend workload
puts "Main thread working"
sleep(1)
puts "Main thread finished"

__END__
Example output:
  Main thread working
  Secondary thread working
  Main thread finished
  Secondary thread exiting

Threads, even those without references to them, will not be garbage collected until they complete their work and exit. A thread that has already finished its work and exit does not need to be explicitly #joined

Sign up to request clarification or add additional context in comments.

1 Comment

I don't think we can infer from the docs the answer to my question. I'm trying to understand if they get garbage collected after they're done, but not necessarily at process end. However, it seems like you know that, regardless of the docs, they do get garbage collected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.