Search code examples
javamultithreadingjava-threads

Can you throw an exception to the parent thread


I am supposed to implement a primitive multithreaded server that starts a new thread for each connection.

It should be possible that one of the thread gets the message to shut down the server.

Is it possible to notify the parent thread from one of the child threads to stop accepting new connections and shut the server down?


Solution

  • There are several ways for inter thread communication :

    1. You can keep a shared state (root of evils in multithreading) and update it and let the main thread check that state several times (use volatile or barriers)
    2. While creating worker thread you can pass an instance of main thread and if any thread at any point wants to stop the main thread it can call a method on main thread to stop accepting further requests (more optimized than previous solution).