Search code examples
javamultithreadingthread-safety

Why is start() method of Thread.java synchronized?


As I understand, when we create a Thread, we use the new keyword. The start() is invoked on a new Thread object everytime when we want to start a Thread.

This has lead me to ask the question, Why is the start() of Thread class in Java synchronized.


Solution

  • Why is the start() of Thread class in Java synchronized.

    You cannot start a thread more than once. But it would be even worse if two threads simultaneously attempted to start the same thread.

    Why?

    Because that would break the logic that prevents an application starting a thread twice!

    So ... they declared start as synchronized and the awkward race condition is avoided.


    I think you are assuming that threads are always started like this:

    new Thread(...).start();
    

    but the language allows you the create a Thread on one thread and pass it to another thread which starts it. I don't know why one would need to do that, but I'd be surprised if someone hasn't tried it.