Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK not to call Thread#join?

Is it OK not to call Thread#join? In this case, I don't care if the thread blows up - I just want Unicorn to keep processing.

class MyMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    t = Thread.new { sleep 1 }
    t.join # is it ok if I skip this?
    @app.call env
  end
end

Will I get "zombie threads" or something like that?

like image 943
Seamus Abshere Avatar asked Oct 26 '11 16:10

Seamus Abshere


People also ask

Do you have to call thread join?

Not necessarily - depends on your design and OS. Join() is actively hazardous in GUI apps - tend If you don't need to know, or don't care, about knowing if one thread has terminated from another thread, you don't need to join it.

What happens if you don't join a thread?

If you don't join these threads, you might end up using more resources than there are concurrent tasks, making it harder to measure the load. To be clear, if you don't call join , the thread will complete at some point anyway, it won't leak or anything.

When should I worry about thread safety?

Thread safety becomes a concern if there is at least a single entry point which can be accessed by multiple threads. If a piece of code is accessed by multiple threads and is calling other method/class/etc., then all this code tree becomes vulnerable.

What will happen when calling thread run instead of calling thread start?

If we call directly the run() method, it will be treated as a normal overridden method of a thread class (or runnable interface) and it will be executed within the context of the current thread, not in a new thread.


1 Answers

It's perfectly fine to not call join - in fact, join is often not needed at all with multithreaded code. You should only call join if you need to block until the new thread completes.

You won't get a "zombie" thread. The new thread will run until completion, then clean itself up for you.

like image 133
Reed Copsey Avatar answered Sep 21 '22 05:09

Reed Copsey