Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Just because you call <code>cancel()</code> on <code>Future</code> doesn't mean that the task will stop automatically. You have to do some work within the task to make sure that it will stop:</p> <ul> <li>Use <code>cancel(true)</code> so that an interrupt is sent to the task.</li> <li>Handle <code>InterruptedException</code>. If a function in your task throws an <code>InterruptedException</code>, make sure you exit gracefully as soon as possible upon catching the exception.</li> <li>Periodically check <code>Thread.currentThread().isInterrupted()</code> if the task does continuous computation.</li> </ul> <p>For example:</p> <pre><code>class LongTask implements Callable&lt;Double&gt; { public Double call() { // Sleep for a while; handle InterruptedException appropriately try { Thread.sleep(10000); } catch (InterruptedException ex) { System.out.println("Exiting gracefully!"); return null; } // Compute for a while; check Thread.isInterrupted() periodically double sum = 0.0; for (long i = 0; i &lt; 10000000; i++) { sum += 10.0 if (Thread.currentThread().isInterrupted()) { System.out.println("Exiting gracefully"); return null; } } return sum; } } </code></pre> <p>Also, as other posts have mentioned: <code>ConcurrentModificationException</code> can be thrown even if using the thread-safe <code>Vector</code> class, because iterators you obtain from <code>Vector</code> are not thread-safe, and thus need to be synchronized. The advanced for-loop uses iterators, so watch out:</p> <pre><code>final Vector&lt;Double&gt; vector = new Vector&lt;Double&gt;(); vector.add(1.0); vector.add(2.0); // Not thread safe! If another thread modifies "vector" during the loop, then // a ConcurrentModificationException will be thrown. for (Double num : vector) { System.out.println(num); } // You can try this as a quick fix, but it might not be what you want: synchronized (vector) { // "vector" must be final for (Double num : vector) { System.out.println(num); } } </code></pre>
    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. 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