Check thread execution by waiting its end, and re-throw exception if has.

@param thread The thread reference.
@param reference The thread exception referencer.
971399
private static void check(Thread thread, AtomicReference<Throwable> reference)
    {
        try
        {
            thread.join();
        }
        catch (final InterruptedException exception)
        {
            Thread.currentThread().interrupt();
            throw new LionEngineException(exception, ERROR_TASK_STOPPED);
        }
        final Throwable throwable = reference.get();
        if (throwable != null)
        {
            Engine.terminate();
            if (throwable instanceof LionEngineException)
            {
                throw (LionEngineException) throwable;
            }
            throw new LionEngineException(throwable);
        }
    }
335207
def thread_exception(self, raised_exception):
		
		print('Thread execution was stopped by the exception. Exception: %s' % str(raised_exception))
		print('Traceback:')
		print(traceback.format_exc())
1025700
def _try_join_cancelled_thread(thread):
    """"""
    thread.join(10)
    if thread.is_alive():
        logging.warning("Thread %s did not terminate within grace period after cancellation",
                        thread.name)
1306755
public void uncaughtException(Thread thread, Throwable throwable) {
		logger.error("Uncaught Exception in thread "+ thread.getName(), throwable);
	}
1240114
public void threadAccepted(IVdmThread thread, boolean first)
	{
		if (first)
		{
			DebugEventHelper.fireExtendedEvent(this, ExtendedDebugEventDetails.BEFORE_CODE_LOADED);
			initialized = true;
			fireTargetInitialized();
		}
	}
360469
@VisibleForTesting
    protected void executionComplete(Throwable exception) {
        Collection<QueueItem> toFail = null;
        Throwable failEx = null;
        synchronized (this.stateLock) {
            // Release the spot occupied by this item's execution.
            this.activeCount--;
            if (exception != null && !this.closed) {
                // Need to fail all future items and close to prevent new items from being processed.
                failEx = new ProcessingException("A previous item failed to commit. Cannot process new items.", exception);
                toFail = new ArrayList<>(this.pendingItems);
                this.pendingItems.clear();
                this.closed = true;
            }

            if (this.emptyNotifier != null && this.activeCount == 0 && this.pendingItems.isEmpty()) {
                // We were asked to notify when we were empty.
                this.emptyNotifier.release();
                this.emptyNotifier = null;
            }
        }

        if (toFail != null) {
            for (QueueItem q : toFail) {
                q.result.completeExceptionally(failEx);
            }

            return;
        }

        // We need to ensure the items are still executed in order. Once out of the main sync block, it is possible that
        // this callback may be invoked concurrently after various completions. As such, we need a special handler for
        // these, using its own synchronization, different from the main one, so that we don't hold that stateLock for too long.
        synchronized (this.processingLock) {
            while (true) {
                QueueItem toProcess;
                synchronized (this.stateLock) {
                    if (hasCapacity() && !this.pendingItems.isEmpty()) {
                        // We have spare capacity and we have something to process. Dequeue it and reserve the spot.
                        toProcess = this.pendingItems.pollFirst();
                        this.activeCount++;
                    } else {
                        // No capacity left or no more pending items.
                        break;
                    }
                }

                Futures.completeAfter(() -> processInternal(toProcess.data), toProcess.result);
            }
        }
    }
711621
@NullSafe
  public static void interrupt(Thread thread) {
    Optional.ofNullable(thread).ifPresent(Thread::interrupt);
  }
61711
protected void interruptThread() {
        Thread currentThread = thread;
        if (currentThread == null) {
            interrupted = true;
        } else {
            currentThread.interrupt();
        }
    }
209384
private void invokeAndWait(Runnable run) {
        if(!SwingUtilities.isEventDispatchThread()) {
            try {
                SwingUtilities.invokeAndWait(run);
            } catch(Exception e) {
                // shouldn't happen
                e.printStackTrace();
            }
        } else {
            run.run();
        }
    }
6244
public void stop() throws Exception {
    if (mSecondaryMasterThread != null) {
      mSecondaryMaster.stop();
      while (mSecondaryMasterThread.isAlive()) {
        LOG.info("Stopping thread {}.", mSecondaryMasterThread.getName());
        mSecondaryMasterThread.join(1000);
      }
      mSecondaryMasterThread = null;
    }
    if (mMasterThread != null) {
      mMasterProcess.stop();
      while (mMasterThread.isAlive()) {
        LOG.info("Stopping thread {}.", mMasterThread.getName());
        mMasterThread.interrupt();
        mMasterThread.join(1000);
      }
      mMasterThread = null;
    }
    clearClients();
    System.clearProperty("alluxio.web.resources");
    System.clearProperty("alluxio.master.min.worker.threads");
  }
629801
public void         takeException(Exception exception) throws Exception
    {
        boolean     rethrow = true;
        if ( isRetryException(exception) )
        {
            if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) )
            {
                log.debug("Retry-able exception received", exception);
            }

            if ( retryPolicy.allowRetry(retryCount++, System.currentTimeMillis() - startTimeMs, sleeper) )
            {
                new EventTrace("retries-allowed", tracer.get()).commit();
                if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) )
                {
                    log.debug("Retrying operation");
                }
                rethrow = false;
            }
            else
            {
                new EventTrace("retries-disallowed", tracer.get()).commit();
                if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) )
                {
                    log.debug("Retry policy not allowing retry");
                }
            }
        }

        if ( rethrow )
        {
            throw exception;
        }
    }
753205
public @CheckForNull V start() throws Exception {
        V result = null;
        int currentAttempt = 0;
        boolean success = false;

        while (currentAttempt < attempts && !success) {
            currentAttempt++;
            try {
                if (LOGGER.isLoggable(Level.INFO)) {
                    LOGGER.log(Level.INFO, Messages.Retrier_Attempt(currentAttempt, action));
                }
                result = callable.call();

            } catch (Exception e) {
                if(duringActionExceptions == null || Stream.of(duringActionExceptions).noneMatch(exception -> exception.isAssignableFrom(e.getClass()))) {
                    // if the raised exception is not considered as a controlled exception doing the action, rethrow it
                    LOGGER.log(Level.WARNING, Messages.Retrier_ExceptionThrown(currentAttempt, action), e);
                    throw e;
                } else {
                    // if the exception is considered as a failed action, notify it to the listener
                    LOGGER.log(Level.INFO, Messages.Retrier_ExceptionFailed(currentAttempt, action), e);
                    if (duringActionExceptionListener != null) {
                        LOGGER.log(Level.INFO, Messages.Retrier_CallingListener(e.getLocalizedMessage(), currentAttempt, action));
                        result = duringActionExceptionListener.apply(currentAttempt, e);
                    }
                }
            }

            // After the call and the call to the listener, which can change the result, test the result
            success = checkResult.test(currentAttempt, result);
            if (!success) {
                if (currentAttempt < attempts) {
                    LOGGER.log(Level.WARNING, Messages.Retrier_AttemptFailed(currentAttempt, action));
                    LOGGER.log(Level.FINE, Messages.Retrier_Sleeping(delay, action));
                    try {
                        Thread.sleep(delay);
                    } catch (InterruptedException ie) {
                        LOGGER.log(Level.FINE, Messages.Retrier_Interruption(action));
                        Thread.currentThread().interrupt(); // flag this thread as interrupted
                        currentAttempt = attempts; // finish
                    }
                } else {
                    // Failed to perform the action
                    LOGGER.log(Level.INFO, Messages.Retrier_NoSuccess(action, attempts));
                }
            } else {
                LOGGER.log(Level.INFO, Messages.Retrier_Success(action, currentAttempt));
            }
        }

        return result;
    }
333214
@Override
    public void postToMainThread(Runnable runnable) {
        if (mMainHandler == null) {
            synchronized (mLock) {
                if (mMainHandler == null) {
                    mMainHandler = new Handler(Looper.getMainLooper());
                }
            }
        }
        //noinspection ConstantConditions
        mMainHandler.post(runnable);
    }
1105539
@Override
    public void attachThreadToDevice(Thread thread, Integer deviceId) {
        attachThreadToDevice(thread.getId(), deviceId);
    }
949123
public static void waitForDie(Thread thread) {
		boolean dead = false;
		do {
			try {
				thread.join();
				dead = true;
			} catch (InterruptedException e) {
				// ignore
			}
		} while (!dead);
	}
387762
public void waitTransformThread() throws SAXException
  {

    // This is called to make sure the task is done.
    // It is possible that the thread has been reused -
    // but for a different transformation. ( what if we 
    // recycle the transformer ? Not a problem since this is
    // still in use. )
    Thread transformThread = this.getTransformThread();

    if (null != transformThread)
    {
      try
      {
        ThreadControllerWrapper.waitThread(transformThread, this);

        if (!this.hasTransformThreadErrorCatcher())
        {
          Exception e = this.getExceptionThrown();

          if (null != e)
          {
            e.printStackTrace();
            throw new org.xml.sax.SAXException(e);
          }
        }

        this.setTransformThread(null);
      }
      catch (InterruptedException ie){}
    }
  }
609115
public void setThreadCount(int thread) {
		this.threadCount = thread;
		getConfig().setProperty(SPIDER_THREAD, Integer.toString(this.threadCount));
	}