aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/build/lib/concurrent/AbstractQueueVisitor.java
blob: 21c1c66111e3d61197ac5803dc11cebeb0057232 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.concurrent;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * AbstractQueueVisitor is a wrapper around {@link ThreadPoolExecutor} which
 * delays thread pool shutdown until entire visitation is complete.
 * This is useful for cases in which worker tasks may submit additional tasks.
 *
 * <p>Consider the following example:
 * <pre>
 *   ThreadPoolExecutor executor = <...>
 *   executor.submit(myRunnableTask);
 *   executor.shutdown();
 *   executor.awaitTermination();
 * </pre>
 *
 * <p>This won't work properly if {@code myRunnableTask} submits additional
 * tasks to the executor, because it may already have shut down
 * by that point.
 *
 * <p>AbstractQueueVisitor supports interruption. If the main thread is
 * interrupted, tasks will no longer be added to the queue, and the
 * {@link #work(boolean)} method will throw {@link InterruptedException}.
 */
public class AbstractQueueVisitor {

  /**
   * Configuration parameters for {@link ThreadPoolExecutor} construction.
   */
  public static class ThreadPoolExecutorParams {
    private final int corePoolSize;
    private final int maxPoolSize;
    private final long keepAliveTime;
    private final TimeUnit units;
    private final String poolName;
    private final BlockingQueue<Runnable> workQueue;

    public ThreadPoolExecutorParams(int corePoolSize, int maxPoolSize, long keepAliveTime,
        TimeUnit units, String poolName, BlockingQueue<Runnable> workQueue) {
      this.corePoolSize = corePoolSize;
      this.maxPoolSize = maxPoolSize;
      this.keepAliveTime = keepAliveTime;
      this.units = units;
      this.poolName = poolName;
      this.workQueue = workQueue;
    }

    public int getCorePoolSize() {
      return corePoolSize;
    }

    public int getMaxPoolSize() {
      return maxPoolSize;
    }

    public long getKeepAliveTime() {
      return keepAliveTime;
    }

    public TimeUnit getUnits() {
      return units;
    }

    public String getPoolName() {
      return poolName;
    }

    public BlockingQueue<Runnable> getWorkQueue() {
      return workQueue;
    }
  }

  /**
   * Default factory function for constructing {@link ThreadPoolExecutor}s.
   */
  public static final Function<ThreadPoolExecutorParams, ThreadPoolExecutor> EXECUTOR_FACTORY =
      new Function<ThreadPoolExecutorParams, ThreadPoolExecutor>() {
        @Override
        public ThreadPoolExecutor apply(ThreadPoolExecutorParams p) {
          return new ThreadPoolExecutor(p.getCorePoolSize(), p.getMaxPoolSize(),
              p.getKeepAliveTime(), p.getUnits(), p.getWorkQueue(),
              new ThreadFactoryBuilder().setNameFormat(p.getPoolName() + " %d").build());
        }
      };

  /**
   * The first unhandled exception thrown by a worker thread.  We save it
   * and re-throw it from the main thread to detect bugs faster;
   * otherwise worker threads just quietly die.
   *
   * Field updates are synchronized; it's
   * important to save the first one as it may be more informative than a
   * subsequent one, and this is not a performance-critical path.
   */
  private volatile Throwable unhandled = null;

  /**
   * An uncaught exception when submitting a job to the ThreadPool is catastrophic, and usually
   * indicates a lack of stack space on which to allocate a native thread. The JDK
   * ThreadPoolExecutor may reach an inconsistent state in such circumstances, so we avoid blocking
   * on its termination when this field is non-null.
   */
  private volatile Throwable catastrophe;

  /**
   * Enables concurrency.  For debugging or testing, set this to false
   * to avoid thread creation and concurrency. Any deviation in observed
   * behaviour is a bug.
   */
  private final boolean concurrent;

  // Condition variable for remainingTasks==0, and a lock for it.
  private final Object zeroRemainingTasks = new Object();
  private long remainingTasks = 0;

  // Map of thread ==> number of jobs executing in the thread.
  // Currently used only for interrupt handling.
  private final Map<Thread, Long> jobs = Maps.newConcurrentMap();

  /**
   * The thread pool. If !concurrent, always null. Created lazily on first
   * call to {@link #enqueue(Runnable)}, and removed after call to
   * {@link #work(boolean)}.
   */
  private final ThreadPoolExecutor pool;

  /**
   * Flag used to record when the main thread (the thread which called
   * {@link #work(boolean)}) is interrupted.
   *
   * When this is true, adding tasks to the thread pool will
   * fail quietly as a part of the process of shutting down the
   * worker threads.
   */
  private volatile boolean threadInterrupted = false;

  /**
   * Latches used to signal when the visitor has been interrupted or
   * seen an exception. Used only for testing.
   */
  private final CountDownLatch interruptedLatch = new CountDownLatch(1);
  private final CountDownLatch exceptionLatch = new CountDownLatch(1);

  /**
   * If true, don't run new actions after an uncaught exception.
   */
  private final boolean failFastOnException;

  /**
   * If true, don't run new actions after an interrupt.
   */
  private final boolean failFastOnInterrupt;

  /**
   * If true, we must shut down the thread pool on completion.
   */
  private final boolean ownThreadPool;

  /**
   * Flag used to record when all threads were killed by failed action execution.
   *
   * <p>May only be accessed in a synchronized block.
   */
  private boolean jobsMustBeStopped = false;

  /**
   * Create the AbstractQueueVisitor.
   *
   * @param concurrent true if concurrency should be enabled. Only set to
   *                   false for debugging.
   * @param corePoolSize the core pool size of the thread pool. See
   *                     {@link ThreadPoolExecutor#ThreadPoolExecutor(int, int, long, TimeUnit,
   *                     BlockingQueue)}
   * @param maxPoolSize the max number of threads in the pool.
   * @param keepAliveTime the keep-alive time for the thread pool.
   * @param units the time units of keepAliveTime.
   * @param failFastOnException if true, don't run new actions after
   *                            an uncaught exception.
   * @param failFastOnInterrupt if true, don't run new actions after interrupt.
   * @param poolName sets the name of threads spawn by this thread pool. If {@code null}, default
   *                    thread naming will be used.
   */
  public AbstractQueueVisitor(boolean concurrent, int corePoolSize, int maxPoolSize,
      long keepAliveTime, TimeUnit units, boolean failFastOnException,
      boolean failFastOnInterrupt, String poolName) {
    this(concurrent, corePoolSize, maxPoolSize, keepAliveTime, units, failFastOnException,
        failFastOnInterrupt, poolName, EXECUTOR_FACTORY);
  }

  /**
   * Create the AbstractQueueVisitor.
   *
   * @param concurrent true if concurrency should be enabled. Only set to
   *                   false for debugging.
   * @param corePoolSize the core pool size of the thread pool. See
   *                     {@link ThreadPoolExecutor#ThreadPoolExecutor(int, int, long, TimeUnit,
   *                     BlockingQueue)}
   * @param maxPoolSize the max number of threads in the pool.
   * @param keepAliveTime the keep-alive time for the thread pool.
   * @param units the time units of keepAliveTime.
   * @param failFastOnException if true, don't run new actions after an uncaught exception.
   * @param failFastOnInterrupt if true, don't run new actions after interrupt.
   * @param poolName sets the name of threads spawn by this thread pool. If {@code null}, default
   *                    thread naming will be used.
   * @param executorFactory the factory for constructing the thread pool if {@code concurrent} is
   *                        true.
   */
  public AbstractQueueVisitor(boolean concurrent, int corePoolSize, int maxPoolSize,
      long keepAliveTime, TimeUnit units, boolean failFastOnException,
      boolean failFastOnInterrupt, String poolName,
      Function<ThreadPoolExecutorParams, ThreadPoolExecutor> executorFactory) {
    Preconditions.checkNotNull(poolName);
    Preconditions.checkNotNull(executorFactory);
    this.concurrent = concurrent;
    this.failFastOnException = failFastOnException;
    this.failFastOnInterrupt = failFastOnInterrupt;
    this.ownThreadPool = true;
    this.pool = concurrent
      ? executorFactory.apply(new ThreadPoolExecutorParams(corePoolSize, maxPoolSize,
        keepAliveTime, units, poolName, getWorkQueue()))
      : null;
  }

  /**
   * Create the AbstractQueueVisitor.
   *
   * @param concurrent true if concurrency should be enabled. Only set to
   *                   false for debugging.
   * @param corePoolSize the core pool size of the thread pool. See
   *                     {@link ThreadPoolExecutor#ThreadPoolExecutor(int, int, long, TimeUnit,
   *                     BlockingQueue)}
   * @param maxPoolSize the max number of threads in the pool.
   * @param keepAliveTime the keep-alive time for the thread pool.
   * @param units the time units of keepAliveTime.
   * @param failFastOnException if true, don't run new actions after
   *                            an uncaught exception.
   * @param poolName sets the name of threads spawn by this thread pool. If {@code null}, default
   *                    thread naming will be used.
   */
  public AbstractQueueVisitor(boolean concurrent, int corePoolSize, int maxPoolSize,
      long keepAliveTime, TimeUnit units, boolean failFastOnException, String poolName) {
    this(concurrent, corePoolSize, maxPoolSize, keepAliveTime, units, failFastOnException, true,
        poolName);
  }

  /**
   * Create the AbstractQueueVisitor.
   *
   * @param executor The ThreadPool to use.
   * @param shutdownOnCompletion If true, pass ownership of the Threadpool to
   *                             this class. The pool will be shut down after a
   *                             call to work(). Callers must not shutdown the
   *                             threadpool while queue visitors use it.
   * @param failFastOnException if true, don't run new actions after
   *                            an uncaught exception.
   * @param failFastOnInterrupt if true, don't run new actions after interrupt.
   */
  public AbstractQueueVisitor(ThreadPoolExecutor executor, boolean shutdownOnCompletion,
                              boolean failFastOnException, boolean failFastOnInterrupt) {
    this(/*concurrent=*/true, executor, shutdownOnCompletion, failFastOnException,
        failFastOnInterrupt);
  }

  /**
   * Create the AbstractQueueVisitor.
   *
   * @param concurrent if false, run tasks inline instead of using the thread pool.
   * @param executor The ThreadPool to use.
   * @param shutdownOnCompletion If true, pass ownership of the Threadpool to
   *                             this class. The pool will be shut down after a
   *                             call to work(). Callers must not shut down the
   *                             threadpool while queue visitors use it.
   * @param failFastOnException if true, don't run new actions after
   *                            an uncaught exception.
   * @param failFastOnInterrupt if true, don't run new actions after interrupt.
   */
  public AbstractQueueVisitor(boolean concurrent, ThreadPoolExecutor executor,
                              boolean shutdownOnCompletion, boolean failFastOnException,
                              boolean failFastOnInterrupt) {
    this.concurrent = concurrent;
    this.failFastOnException = failFastOnException;
    this.failFastOnInterrupt = failFastOnInterrupt;
    this.pool = executor;
    this.ownThreadPool = shutdownOnCompletion;
  }

  public AbstractQueueVisitor(ThreadPoolExecutor executor, boolean failFastOnException) {
    this(executor, true, failFastOnException, true);
  }

  /**
   * Create the AbstractQueueVisitor.
   *
   * @param concurrent true if concurrency should be enabled. Only set to
   *                   false for debugging.
   * @param corePoolSize the core pool size of the thread pool. See
   *                     {@link ThreadPoolExecutor#ThreadPoolExecutor(int, int, long, TimeUnit,
   *                     BlockingQueue)}
   * @param maxPoolSize the max number of threads in the pool.
   * @param keepAliveTime the keep-alive time for the thread pool.
   * @param units the time units of keepAliveTime.
   * @param poolName sets the name of threads spawn by this thread pool. If {@code null}, default
   *                    thread naming will be used.
   */
  public AbstractQueueVisitor(boolean concurrent, int corePoolSize, int maxPoolSize,
      long keepAliveTime, TimeUnit units, String poolName) {
    this(concurrent, corePoolSize, maxPoolSize, keepAliveTime, units, false, poolName);
  }

  /**
   * Create the AbstractQueueVisitor with concurrency enabled.
   *
   * @param corePoolSize the core pool size of the thread pool. See
   *                     {@link ThreadPoolExecutor#ThreadPoolExecutor(int, int, long, TimeUnit,
   *                     BlockingQueue)}
   * @param maxPoolSize the max number of threads in the pool.
   * @param keepAlive the keep-alive time for the thread pool.
   * @param units the time units of keepAliveTime.
   * @param poolName sets the name of threads spawn by this thread pool. If {@code null}, default
   *                    thread naming will be used.
   */
  public AbstractQueueVisitor(int corePoolSize, int maxPoolSize, long keepAlive, TimeUnit units,
      String poolName) {
    this(true, corePoolSize, maxPoolSize, keepAlive, units, poolName);
  }

  protected BlockingQueue<Runnable> getWorkQueue() {
    return new LinkedBlockingQueue<>();
  }

  /**
   * Executes all tasks on the queue, and optionally shuts the pool down and deletes it.
   *
   * <p>Throws (the same) unchecked exception if any worker thread failed unexpectedly. If the pool
   * is interrupted and a worker also throws an unchecked exception, the unchecked exception is
   * rethrown, since it may indicate a programming bug. If callers handle the unchecked exception,
   * they may check the interrupted bit to see if the pool was interrupted.
   *
   * @param interruptWorkers if true, interrupt worker threads if main thread gets an interrupt or
   *        if a worker throws a critical error (see {@link #isCriticalError(Throwable)}). If
   *        false, just wait for them to terminate normally.
   */
  protected void work(boolean interruptWorkers) throws InterruptedException {
    if (concurrent) {
      awaitTermination(interruptWorkers);
    } else {
      if (Thread.currentThread().isInterrupted()) {
        throw new InterruptedException();
      }
    }
  }

  /**
   * Schedules a call.
   * Called in a worker thread if concurrent.
   */
  protected void enqueue(Runnable runnable) {
    if (concurrent) {
      AtomicBoolean ranTask = new AtomicBoolean(false);
      try {
        pool.execute(wrapRunnable(runnable, ranTask));
      } catch (Throwable e) {
        if (!ranTask.get()) {
          // Note that keeping track of ranTask is necessary to disambiguate the case where
          // execute() itself failed, vs. a caller-runs policy on pool exhaustion, where the
          // runnable threw. To be extra cautious, we decrement the task count in a finally
          // block, even though the CountDownLatch is unlikely to throw.
          recordError(e);
        }
      }
    } else {
      runnable.run();
    }
  }

  private void recordError(Throwable e) {
    catastrophe = e;
    try {
      synchronized (this) {
        if (unhandled == null) { // save only the first one.
          unhandled = e;
          exceptionLatch.countDown();
        }
      }
    } finally {
      decrementRemainingTasks();
    }
  }

  private Runnable wrapRunnable(final Runnable runnable, final AtomicBoolean ranTask) {
    synchronized (zeroRemainingTasks) {
      remainingTasks++;
    }
    return new Runnable() {
      @Override
      public void run() {
        Thread thread = null;
        boolean addedJob = false;
        try {
          ranTask.set(true);
          thread = Thread.currentThread();
          addJob(thread);
          addedJob = true;
          if (blockNewActions()) {
            // Make any newly enqueued tasks quickly die. We check after adding to the jobs map so
            // that if another thread is racing to kill this thread and didn't make it before this
            // conditional, it will be able to find and kill this thread anyway.
            return;
          }
          runnable.run();
        } catch (Throwable e) {
          synchronized (AbstractQueueVisitor.this) {
            if (unhandled == null) { // save only the first one.
              unhandled = e;
              exceptionLatch.countDown();
            }
            markToStopAllJobsIfNeeded(e);
          }
        } finally {
          try {
            if (thread != null && addedJob) {
              removeJob(thread);
            }
          } finally {
            decrementRemainingTasks();
          }
        }
      }
    };
  }

  private final void addJob(Thread thread) {
    // Note: this looks like a check-then-act race but it isn't, because each
    // key implies thread-locality.
    long count = jobs.containsKey(thread) ? jobs.get(thread) + 1 : 1;
    jobs.put(thread, count);
  }

  private final void removeJob(Thread thread) {
    Long boxedCount = Preconditions.checkNotNull(jobs.get(thread),
        "Can't retrieve job after successfully adding it");
    long count = boxedCount - 1;
    if (count == 0) {
      jobs.remove(thread);
    } else {
      jobs.put(thread, count);
    }
  }

  /**
   * Set an internal flag to show that an interrupt was detected.
   */
  private void setInterrupted() {
    threadInterrupted = true;
    setRejectedExecutionHandler();
  }

  private final void decrementRemainingTasks() {
    synchronized (zeroRemainingTasks) {
      if (--remainingTasks == 0) {
        zeroRemainingTasks.notify();
      }
    }
  }

  /**
   * If this returns true, don't enqueue new actions.
   */
  protected boolean blockNewActions() {
    return (failFastOnInterrupt && isInterrupted()) || (unhandled != null && failFastOnException);
  }

  /**
   * Await interruption.  Used only in tests.
   */
  @VisibleForTesting
  public boolean awaitInterruptionForTestingOnly(long timeout, TimeUnit units)
      throws InterruptedException {
    return interruptedLatch.await(timeout, units);
  }

  /** Get latch that is released when exception is received by visitor. Used only in tests. */
  @VisibleForTesting
  public CountDownLatch getExceptionLatchForTestingOnly() {
    return exceptionLatch;
  }

  /** Get latch that is released when interruption is received by visitor. Used only in tests. */
  @VisibleForTesting
  public CountDownLatch getInterruptionLatchForTestingOnly() {
    return interruptedLatch;
  }

  /**
   * Get the value of the interrupted flag.
   */
  @ThreadSafety.ThreadSafe
  protected boolean isInterrupted() {
    return threadInterrupted;
  }

  /**
   * Get number of jobs remaining. Note that this can increase in value
   * if running tasks submit further jobs.
   */
  @VisibleForTesting
  protected long getTaskCount() {
    synchronized (zeroRemainingTasks) {
      return remainingTasks;
    }
  }

  /**
   * Waits for the task queue to drain, then shuts down the thread pool and
   * waits for it to terminate.  Throws (the same) unchecked exception if any
   * worker thread failed unexpectedly.
   */
  private void awaitTermination(boolean interruptWorkers) throws InterruptedException {
    Preconditions.checkState(failFastOnInterrupt || !interruptWorkers);
    Throwables.propagateIfPossible(catastrophe);
    try {
      synchronized (zeroRemainingTasks) {
        while (remainingTasks != 0 && !jobsMustBeStopped) {
          zeroRemainingTasks.wait();
        }
      }
    } catch (InterruptedException e) {
      // Mark the visitor, so that it's known to be interrupted, and
      // then break out of here, stop the worker threads and return ASAP,
      // sending the interruption to the parent thread.
      setInterrupted();
    }

    reallyAwaitTermination(interruptWorkers);

    if (isInterrupted()) {
      // Set interrupted bit on current thread so that callers can see that it was interrupted. Note
      // that if the thread was interrupted while awaiting termination, we might not hit this
      // codepath, but then the current thread's interrupt bit is already set, so we are fine.
      Thread.currentThread().interrupt();
    }
    // Throw the first unhandled (worker thread) exception in the main thread. We throw an unchecked
    // exception instead of InterruptedException if both are present because an unchecked exception
    // may indicate a catastrophic failure that should shut down the program. The caller can
    // check the interrupted bit if they will handle the unchecked exception without crashing.
    Throwables.propagateIfPossible(unhandled);

    if (Thread.interrupted()) {
      throw new InterruptedException();
    }
  }

  private void reallyAwaitTermination(boolean interruptWorkers) {
    // TODO(bazel-team): verify that interrupt() is safe for every use of
    // AbstractQueueVisitor and remove the interruptWorkers flag.
    if (interruptWorkers && !jobs.isEmpty()) {
      interruptInFlightTasks();
    }

    if (isInterrupted()) {
      interruptedLatch.countDown();
    }

    Throwables.propagateIfPossible(catastrophe);
    synchronized (zeroRemainingTasks) {
      while (remainingTasks != 0) {
        try {
          zeroRemainingTasks.wait();
        } catch (InterruptedException e) {
          setInterrupted();
        }
      }
    }

    if (ownThreadPool) {
      pool.shutdown();
      for (;;) {
        try {
          Throwables.propagateIfPossible(catastrophe);
          pool.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
          break;
        } catch (InterruptedException e) {
          setInterrupted();
        }
      }
    }
  }

  private void interruptInFlightTasks() {
    Thread thisThread = Thread.currentThread();
    for (Thread thread : jobs.keySet()) {
      if (thisThread != thread) {
        thread.interrupt();
      }
    }
  }

  /**
   * Makes the visitation terminate prematurely.
   */
  public void interrupt() {
    setInterrupted();
    reallyAwaitTermination(true);
  }

  /**
   * If this returns true, that means the exception {@code e} is critical
   * and all running actions should be stopped. {@link Error}s are always considered critical.
   *
   * <p>Default value - always false. If different behavior is needed
   * then we should override this method in subclasses.
   *
   * @param e the exception object to check
   */
  protected boolean isCriticalError(Throwable e) {
    return false;
  }

  private boolean isCriticalErrorInternal(Throwable e) {
    return isCriticalError(e) || (e instanceof Error);
  }

  private void setRejectedExecutionHandler() {
    if (ownThreadPool) {
      pool.setRejectedExecutionHandler(new RejectedExecutionHandler() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
          decrementRemainingTasks();
        }
      });
    }
  }

  /**
   * If exception is critical then set a flag which signals
   * to stop all jobs inside {@link #awaitTermination(boolean)}.
   */
  private synchronized void markToStopAllJobsIfNeeded(Throwable e) {
    if (isCriticalErrorInternal(e) && !jobsMustBeStopped) {
      jobsMustBeStopped = true;
      synchronized (zeroRemainingTasks) {
        zeroRemainingTasks.notify();
      }
    }
  }
}