Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>Is while(true) good enough?</p> </blockquote> <p>Oops. @Cratylus makes a good point that you should always use:</p> <pre><code> while (!Thread.currentThread().isInterrupted()) { </code></pre> <p>You need to be religious with the catching of exceptions -- possibly even catching <code>RuntimeException</code> and maybe even <code>Throwable</code>. At least you should consider catching and logging a message before quitting.</p> <blockquote> <p>What to do when I get an InterruptedException so that I can try to resume what I was doing?</p> </blockquote> <p>It depends on what you want the thread to do. IMO, when a thread is interrupted it should be (uh) interrupted. Since <code>thread.stop()</code> is deprecated for lots of reasons, <code>thread.interrupt()</code> really is the only way to stop a thread from running. This means that it should clean up and exit.</p> <pre><code>} catch (InterruptedException ex) { // always a good practice to re-interrupt Thread.currentThread().interrupt(); // but now what to do? I vote for stopping the thread return; } </code></pre> <blockquote> <p>What happens if the thread hangs?</p> </blockquote> <p>This should never happen unless you have bugs in your program. It may wait forever on <code>queue.take()</code> but an interrupt should kick it out.</p> <p>Be careful of multiple <code>synchronized</code> sections to protect against deadlock. Be sure to use the <code>java.util.concurrent.*</code> classes (<code>BlockingQueue</code>, <code>Executors</code>, ...) to lesson the chance of user code causing problems. Use the <code>Atomic*</code> classes. All data shared between threads need to be properly <code>synchronized</code> or <code>volatile</code>.</p> <blockquote> <p>What happens if the thread terminates due to an exception?</p> </blockquote> <p>What do you want to happen? You should (again) religiously catch exceptions if that is what you want to do. If you want the thread to stop when it sees an exception then I'd catch the exception, log it, and then clean up and return. There is no easy answer to exception handling.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload