Example usage for java.lang Thread interrupted

List of usage examples for java.lang Thread interrupted

Introduction

In this page you can find the example usage for java.lang Thread interrupted.

Prototype

public static boolean interrupted() 

Source Link

Document

Tests whether the current thread has been interrupted.

Usage

From source file:net.sf.jasperreports.engine.export.oasis.JROdtExporter.java

/**
 *
 *//* w w  w .ja v a 2 s .co m*/
protected void exportReportToOasisZip(OutputStream os) throws JRException, IOException {
    OasisZip oasisZip = new OdtZip();

    ExportZipEntry tempBodyEntry = new FileBufferedZipEntry(null);
    ExportZipEntry tempStyleEntry = new FileBufferedZipEntry(null);

    tempBodyWriter = new WriterHelper(jasperReportsContext, tempBodyEntry.getWriter());
    tempStyleWriter = new WriterHelper(jasperReportsContext, tempStyleEntry.getWriter());

    documentBuilder = new OdtDocumentBuilder(oasisZip);

    styleCache = new StyleCache(jasperReportsContext, tempStyleWriter, getExporterKey());

    WriterHelper stylesWriter = new WriterHelper(jasperReportsContext, oasisZip.getStylesEntry().getWriter());

    List<ExporterInputItem> items = exporterInput.getItems();

    StyleBuilder styleBuilder = new StyleBuilder(stylesWriter);

    styleBuilder.buildBeforeAutomaticStyles(jasperPrint);

    pageFormatIndex = -1;

    for (reportIndex = 0; reportIndex < items.size(); reportIndex++) {
        ExporterInputItem item = items.get(reportIndex);
        rowStyles.clear();
        columnStyles.clear();

        setCurrentExporterInputItem(item);

        List<JRPrintPage> pages = jasperPrint.getPages();
        if (pages != null && pages.size() > 0) {
            PageRange pageRange = getPageRange();
            int startPageIndex = (pageRange == null || pageRange.getStartPageIndex() == null) ? 0
                    : pageRange.getStartPageIndex();
            int endPageIndex = (pageRange == null || pageRange.getEndPageIndex() == null) ? (pages.size() - 1)
                    : pageRange.getEndPageIndex();

            PrintPageFormat oldPageFormat = null;
            JRPrintPage page = null;
            for (pageIndex = startPageIndex; pageIndex <= endPageIndex; pageIndex++) {
                if (Thread.interrupted()) {
                    throw new ExportInterruptedException();
                }

                PrintPageFormat pageFormat = jasperPrint.getPageFormat(pageIndex);

                if (oldPageFormat != pageFormat) {
                    styleBuilder.buildPageLayout(++pageFormatIndex, pageFormat);
                    oldPageFormat = pageFormat;
                }

                page = pages.get(pageIndex);

                exportPage(page);
            }
        }
    }

    styleBuilder.buildMasterPages(pageFormatIndex);

    stylesWriter.flush();
    tempBodyWriter.flush();
    tempStyleWriter.flush();

    stylesWriter.close();
    tempBodyWriter.close();
    tempStyleWriter.close();

    /*   */
    ContentBuilder contentBuilder = new ContentBuilder(oasisZip.getContentEntry(), tempStyleEntry,
            tempBodyEntry, styleCache.getFontFaces(), OasisZip.MIME_TYPE_ODT);
    contentBuilder.build();

    tempStyleEntry.dispose();
    tempBodyEntry.dispose();

    oasisZip.zipEntries(os);

    oasisZip.dispose();
}

From source file:org.archive.modules.fetcher.CookieStoreTest.java

public void testConcurrentLoad() throws IOException, InterruptedException {
    bdbCookieStore().clear();/*from   w  w  w  . j  av  a  2s .c  om*/
    basicCookieStore().clear();
    final Random rand = new Random();

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                while (!Thread.interrupted()) {
                    BasicClientCookie cookie = new BasicClientCookie(UUID.randomUUID().toString(),
                            UUID.randomUUID().toString());
                    cookie.setDomain("d" + rand.nextInt(20) + ".example.com");
                    bdbCookieStore().addCookie(cookie);
                    basicCookieStore().addCookie(cookie);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };

    Thread[] threads = new Thread[200];
    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Thread(runnable);
        threads[i].setName("cookie-load-test-" + i);
        threads[i].start();
    }

    Thread.sleep(1000);

    for (int i = 0; i < threads.length; i++) {
        threads[i].interrupt();
    }
    for (int i = 0; i < threads.length; i++) {
        threads[i].join();
    }

    ArrayList<Cookie> bdbCookieArrayList = new ArrayList<Cookie>(bdbCookieStore().getCookies());
    Map<String, Integer> domainCounts = new HashMap<String, Integer>();
    for (Cookie cookie : bdbCookieArrayList) {
        if (domainCounts.get(cookie.getDomain()) == null) {
            domainCounts.put(cookie.getDomain(), 1);
        } else {
            domainCounts.put(cookie.getDomain(), domainCounts.get(cookie.getDomain()) + 1);
        }
    }

    for (String domain : domainCounts.keySet()) {
        assertTrue(domainCounts.get(domain) <= BdbCookieStore.MAX_COOKIES_FOR_DOMAIN + 25);
    }
}

From source file:at.bitfire.davdroid.syncadapter.ContactsSyncManager.java

@Override
protected void downloadRemote() throws IOException, HttpException, DavException, ContactsStorageException {
    App.log.info("Downloading " + toDownload.size() + " contacts (" + MAX_MULTIGET + " at once)");

    // prepare downloader which may be used to download external resource like contact photos
    Contact.Downloader downloader = new ResourceDownloader(collectionURL);

    // download new/updated VCards from server
    for (DavResource[] bunch : ArrayUtils.partition(toDownload.toArray(new DavResource[toDownload.size()]),
            MAX_MULTIGET)) {/*from   w w w . j  ava  2s. c o  m*/
        if (Thread.interrupted())
            return;

        App.log.info("Downloading " + StringUtils.join(bunch, ", "));

        if (bunch.length == 1) {
            // only one contact, use GET
            DavResource remote = bunch[0];

            ResponseBody body = remote
                    .get("text/vcard;version=4.0, text/vcard;charset=utf-8;q=0.8, text/vcard;q=0.5");

            // CardDAV servers MUST return ETag on GET [https://tools.ietf.org/html/rfc6352#section-6.3.2.3]
            GetETag eTag = (GetETag) remote.properties.get(GetETag.NAME);
            if (eTag == null || StringUtils.isEmpty(eTag.eTag))
                throw new DavException("Received CardDAV GET response without ETag for " + remote.location);

            Charset charset = Charsets.UTF_8;
            MediaType contentType = body.contentType();
            if (contentType != null)
                charset = contentType.charset(Charsets.UTF_8);

            @Cleanup
            InputStream stream = body.byteStream();
            processVCard(remote.fileName(), eTag.eTag, stream, charset, downloader);

        } else {
            // multiple contacts, use multi-get
            List<HttpUrl> urls = new LinkedList<>();
            for (DavResource remote : bunch)
                urls.add(remote.location);
            davAddressBook().multiget(urls.toArray(new HttpUrl[urls.size()]), hasVCard4);

            // process multiget results
            for (DavResource remote : davCollection.members) {
                String eTag;
                GetETag getETag = (GetETag) remote.properties.get(GetETag.NAME);
                if (getETag != null)
                    eTag = getETag.eTag;
                else
                    throw new DavException("Received multi-get response without ETag");

                Charset charset = Charsets.UTF_8;
                GetContentType getContentType = (GetContentType) remote.properties.get(GetContentType.NAME);
                if (getContentType != null && getContentType.type != null) {
                    MediaType type = MediaType.parse(getContentType.type);
                    if (type != null)
                        charset = type.charset(Charsets.UTF_8);
                }

                AddressData addressData = (AddressData) remote.properties.get(AddressData.NAME);
                if (addressData == null || addressData.vCard == null)
                    throw new DavException("Received multi-get response without address data");

                @Cleanup
                InputStream stream = new ByteArrayInputStream(addressData.vCard.getBytes());
                processVCard(remote.fileName(), eTag, stream, charset, downloader);
            }
        }
    }
}

From source file:com.ngdata.hbaseindexer.indexer.FusionPipelineClient.java

protected ArrayList<String> getAvailableEndpoints() throws Exception {
    ArrayList<String> mutable = null;
    synchronized (this) {
        mutable = new ArrayList<String>(sessions.keySet());
    }//  w ww  . j av  a  2 s  .co m

    if (mutable.isEmpty()) {
        // completely hosed ... try to re-establish all sessions
        synchronized (this) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ie) {
                Thread.interrupted();
            }

            sessions = establishSessions(originalEndpoints, fusionUser, fusionPass, fusionRealm);
            mutable = new ArrayList<String>(sessions.keySet());
        }
        if (mutable.isEmpty())
            throw new IllegalStateException("No available endpoints! "
                    + "Check log for previous errors as to why there are no more endpoints available. This is a fatal error.");
    }

    return mutable;
}

From source file:org.apache.jackrabbit.oak.plugins.segment.CompactionAndCleanupIT.java

/**
 * Regression test for OAK-2192 testing for mixed segments. This test does not
 * cover OAK-3348. I.e. it does not assert the segment graph is free of cross
 * gc generation references.//from ww  w .  j a  v a  2  s .co m
 */
@Test
public void testMixedSegments() throws Exception {
    FileStore store = FileStore.builder(getFileStoreFolder()).withMaxFileSize(2).withMemoryMapping(true)
            .build();
    final SegmentNodeStore nodeStore = SegmentNodeStore.builder(store).build();
    final AtomicBoolean compactionSuccess = new AtomicBoolean(true);
    CompactionStrategy strategy = new CompactionStrategy(true, false, CLEAN_NONE, 0, (byte) 5) {
        @Override
        public boolean compacted(Callable<Boolean> setHead) throws Exception {
            compactionSuccess.set(nodeStore.locked(setHead, 1, MINUTES));
            return compactionSuccess.get();
        }
    };
    strategy.setForceAfterFail(true);
    store.setCompactionStrategy(strategy);

    NodeBuilder root = nodeStore.getRoot().builder();
    createNodes(root.setChildNode("test"), 10, 3);
    nodeStore.merge(root, EmptyHook.INSTANCE, CommitInfo.EMPTY);

    final Set<UUID> beforeSegments = new HashSet<UUID>();
    collectSegments(store.getHead(), beforeSegments);

    final AtomicReference<Boolean> run = new AtomicReference<Boolean>(true);
    final List<String> failedCommits = newArrayList();
    Thread[] threads = new Thread[10];
    for (int k = 0; k < threads.length; k++) {
        final int threadId = k;
        threads[k] = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int j = 0; run.get(); j++) {
                    String nodeName = "b-" + threadId + "," + j;
                    try {
                        NodeBuilder root = nodeStore.getRoot().builder();
                        root.setChildNode(nodeName);
                        nodeStore.merge(root, EmptyHook.INSTANCE, CommitInfo.EMPTY);
                        Thread.sleep(5);
                    } catch (CommitFailedException e) {
                        failedCommits.add(nodeName);
                    } catch (InterruptedException e) {
                        Thread.interrupted();
                        break;
                    }
                }
            }
        });
        threads[k].start();
    }
    store.compact();
    run.set(false);
    for (Thread t : threads) {
        t.join();
    }
    store.flush();

    assumeTrue("Failed to acquire compaction lock", compactionSuccess.get());
    assertTrue("Failed commits: " + failedCommits, failedCommits.isEmpty());

    Set<UUID> afterSegments = new HashSet<UUID>();
    collectSegments(store.getHead(), afterSegments);
    try {
        for (UUID u : beforeSegments) {
            assertFalse("Mixed segments found: " + u, afterSegments.contains(u));
        }
    } finally {
        store.close();
    }
}

From source file:org.apache.hadoop.mapreduce.v2.app.job.impl.TestJobImpl.java

@Test(timeout = 20000)
public void testKilledDuringSetup() throws Exception {
    Configuration conf = new Configuration();
    conf.set(MRJobConfig.MR_AM_STAGING_DIR, stagingDir);
    AsyncDispatcher dispatcher = new AsyncDispatcher();
    dispatcher.init(conf);/*  w  ww  .j ava  2s. c  om*/
    dispatcher.start();
    OutputCommitter committer = new StubbedOutputCommitter() {
        @Override
        public synchronized void setupJob(JobContext jobContext) throws IOException {
            while (!Thread.interrupted()) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
    };
    CommitterEventHandler commitHandler = createCommitterEventHandler(dispatcher, committer);
    commitHandler.init(conf);
    commitHandler.start();

    JobImpl job = createStubbedJob(conf, dispatcher, 2, null);
    JobId jobId = job.getID();
    job.handle(new JobEvent(jobId, JobEventType.JOB_INIT));
    assertJobState(job, JobStateInternal.INITED);
    job.handle(new JobStartEvent(jobId));
    assertJobState(job, JobStateInternal.SETUP);

    job.handle(new JobEvent(job.getID(), JobEventType.JOB_KILL));
    assertJobState(job, JobStateInternal.KILLED);
    dispatcher.stop();
    commitHandler.stop();
}

From source file:com.tasktop.c2c.server.ssh.server.commands.AbstractInteractiveProxyCommand.java

protected void performCommand(Environment env, ProjectService service, String projectId, String path,
        String requestPath, RequestHeadersSupport headers) throws CommandException {
    String internalProxyUri = service.computeInternalProxyBaseUri(false);
    if (internalProxyUri == null) {
        throw new IllegalStateException();
    }/*from w w w.j av  a2 s.com*/
    URI targetUri;
    try {
        if (!internalProxyUri.endsWith("/")) {
            internalProxyUri += "/";
        }
        internalProxyUri += getName() + '/' + path;

        targetUri = new URI(internalProxyUri);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    String host = targetUri.getHost();
    int port = targetUri.getPort();
    if (port < 0) {
        port = 80;
    }
    if (targetUri.getScheme() == null || !targetUri.getScheme().equalsIgnoreCase("http")) {
        throw new IllegalStateException("scheme " + targetUri.getScheme() + " is not supported");
    }
    HeaderGroup headerGroup = computeHeaders(targetUri);
    for (Entry<String, List<String>> headerEntry : headers.getRequestHeaders().entrySet()) {
        for (String value : headerEntry.getValue()) {
            headerGroup.addHeader(new Header(headerEntry.getKey(), value));
        }
    }
    getLogger().info("Proxying " + getName() + " to " + targetUri);
    try {
        Socket socket = socketFactory.openConnection(host, port);
        try {
            // initiate an HTTP request with Transfer-Encoding: chunked
            OutputStream proxyOut = socket.getOutputStream();
            emitHttpRequestLine(proxyOut, targetUri);
            emitHeaders(proxyOut, headerGroup);

            proxyOut.flush();

            List<Callable<Void>> tasks = new ArrayList<Callable<Void>>(3);
            FlushingChunkedOutputStream chunkedRequestOut = new FlushingChunkedOutputStream(proxyOut);
            tasks.add(new InputPipe(in, chunkedRequestOut, bufferSize, Thread.currentThread()).flush(true));

            // start these pipes
            ExecutorService executor = Executors.newFixedThreadPool(tasks.size());
            try {
                for (Callable<Void> task : tasks) {
                    executor.submit(task);
                }

                InputStream proxyInput = socket.getInputStream();
                try {
                    readHttpResponse(proxyInput);
                    MultiplexingInputStream input = new MultiplexingInputStream(
                            new ChunkedInputStream(proxyInput));
                    for (;;) {
                        PacketType packetType = input.getPacketType();
                        if (packetType == null) {
                            break;
                        }
                        int length = input.getPacketLength();

                        processData(input, packetType, length);
                    }
                } finally {
                    try {
                        executor.shutdown();
                        executor.awaitTermination(1000L, TimeUnit.MILLISECONDS);
                    } catch (InterruptedException e) {
                        // ignore
                    }
                }
            } finally {
                executor.shutdownNow();
                try {
                    executor.awaitTermination(3000L, TimeUnit.MILLISECONDS);
                } catch (InterruptedException e) {
                    // ignore
                }
                Thread.interrupted();

                try {
                    // attempt to close the chunked output, since this will make us a well-behaved client
                    // by sending the closing chunk.
                    chunkedRequestOut.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        } finally {
            socket.close();
        }
    } catch (ConnectException e) {
        getLogger().error(e.getMessage(), e);
        throw new CommandException(-1, "Service temporarily unavailable");
    } catch (IOException e) {
        getLogger().warn(e.getMessage(), e);
        throw new CommandException(-1, e.getMessage());
    }
}

From source file:info.novatec.inspectit.rcp.storage.util.DataRetriever.java

/**
 * Returns cached data for the storage from the CMR if the cached data exists for given hash. If
 * data does not exist <code>null</code> is returned.
 * //from ww w.j a va  2  s. c o m
 * @param <E>
 *            Type of the objects are wanted.
 * @param cmrRepositoryDefinition
 *            {@link CmrRepositoryDefinition}.
 * @param storageData
 *            {@link StorageData} that points to the wanted storage.
 * @param hash
 *            Hash under which the cached data is stored.
 * @return Returns cached data for the storage from the CMR if the cached data exists for given
 *         hash. If data does not exist <code>null</code> is returned.
 * @throws BusinessException
 *             If {@link BusinessException} occurred.
 * @throws SerializationException
 *             If {@link SerializationException} occurs.
 * @throws IOException
 *             If {@link IOException} occurs.
 */
@SuppressWarnings("unchecked")
public <E extends DefaultData> List<E> getCachedDataViaHttp(CmrRepositoryDefinition cmrRepositoryDefinition,
        StorageData storageData, int hash) throws BusinessException, IOException, SerializationException {
    String cachedFileLocation = cmrRepositoryDefinition.getStorageService()
            .getCachedStorageDataFileLocation(storageData, hash);
    if (null == cachedFileLocation) {
        return null;
    } else {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(getServerUri(cmrRepositoryDefinition) + cachedFileLocation);
        ISerializer serializer = null;
        try {
            serializer = serializerQueue.take();
        } catch (InterruptedException e) {
            Thread.interrupted();
        }
        InputStream inputStream = null;
        Input input = null;
        try {
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            inputStream = entity.getContent();
            input = new Input(inputStream);
            Object object = serializer.deserialize(input);
            List<E> receivedData = (List<E>) object;
            return receivedData;
        } finally {
            if (null != inputStream) {
                inputStream.close();
            }
            if (null != input) {
                input.close();
            }
            serializerQueue.add(serializer);
        }
    }
}

From source file:com.sillelien.dollar.api.types.DollarList.java

@NotNull
@Override/*from w w  w  .  jav a 2s .  c  o  m*/
public var _fix(int depth, boolean parallel) {
    if (depth <= 1) {
        return this;
    } else {
        ImmutableList<var> result;
        if (parallel) {
            try {
                result = ImmutableList.copyOf(executor.submit(() -> $stream(parallel)
                        .map(v -> v._fix(depth - 1, parallel)).collect(Collectors.toList())).get());

            } catch (InterruptedException e) {
                Thread.interrupted();
                result = ImmutableList.<var>of(DollarFactory.failure(ErrorType.INTERRUPTED, e, false));

            } catch (ExecutionException e) {
                result = ImmutableList
                        .of(DollarFactory.failure(ErrorType.EXECUTION_FAILURE, e.getCause(), false));

            }
            return new DollarList(errors(), result);
        } else {
            return new DollarList(errors(), ImmutableList.copyOf(
                    $stream(parallel).map(v -> v._fix(depth - 1, parallel)).collect(Collectors.toList())));
        }
    }

}

From source file:org.apache.tez.runtime.task.TezTaskRunner2.java

/**
 * Throws an exception only when there was a communication error reported by
 * the TaskReporter.//from   w  ww  .  j a va  2 s  .c  om
 *
 * Otherwise, this takes care of all communication with the AM for a a running task - which
 * includes informing the AM about Failures and Success.
 *
 * If a kill request is made to the task, it will not communicate this information to
 * the AM - since a task KILL is an external event, and whoever invoked it should
 * be able to track it.
 *
 * @return the taskRunner result
 */
public TaskRunner2Result run() {
    try {
        Future<TaskRunner2CallableResult> future = null;
        synchronized (this) {
            // All running state changes must be made within a synchronized block to ensure
            // kills are issued or the task is not setup.
            if (isRunningState()) {
                // Safe to do this within a synchronized block because we're providing
                // the handler on which the Reporter will communicate back. Assuming
                // the register call doesn't end up hanging.
                taskRunnerCallable = new TaskRunner2Callable(task, ugi);
                taskReporter.registerTask(task, umbilicalAndErrorHandler);
                future = executor.submit(taskRunnerCallable);
            }
        }

        if (future == null) {
            return logAndReturnEndResult(firstEndReason, firstTaskFailureType, firstException,
                    stopContainerRequested.get());
        }

        TaskRunner2CallableResult executionResult = null;
        // The task started. Wait for it to complete.
        try {
            executionResult = future.get();
        } catch (Throwable e) {
            if (e instanceof ExecutionException) {
                e = e.getCause();
            }
            synchronized (this) {
                if (isRunningState()) {
                    trySettingEndReason(EndReason.TASK_ERROR);
                    registerFirstException(TaskFailureType.NON_FATAL, e, null);
                    LOG.warn("Exception from RunnerCallable", e);
                }
            }
        }
        processCallableResult(executionResult);

        switch (firstEndReason) {
        case SUCCESS:
            try {
                taskReporter.taskSucceeded(task.getTaskAttemptID());
                return logAndReturnEndResult(EndReason.SUCCESS, null, null, stopContainerRequested.get());
            } catch (IOException e) {
                // Comm failure. Task can't do much.
                handleFinalStatusUpdateFailure(e, "success");
                return logAndReturnEndResult(EndReason.COMMUNICATION_FAILURE, firstTaskFailureType, e,
                        stopContainerRequested.get());
            } catch (TezException e) {
                // Failure from AM. Task can't do much.
                handleFinalStatusUpdateFailure(e, "success");
                return logAndReturnEndResult(EndReason.COMMUNICATION_FAILURE, firstTaskFailureType, e,
                        stopContainerRequested.get());
            }
        case CONTAINER_STOP_REQUESTED:
            // Don't need to send any more communication updates to the AM.
            return logAndReturnEndResult(firstEndReason, firstTaskFailureType, null,
                    stopContainerRequested.get());
        case KILL_REQUESTED:
            // This was an external kill called directly on the task runner
            return logAndReturnEndResult(firstEndReason, firstTaskFailureType, null,
                    stopContainerRequested.get());
        case TASK_KILL_REQUEST:
            // Task reported a self kill
            return logAndReturnEndResult(firstEndReason, firstTaskFailureType, firstException,
                    stopContainerRequested.get());
        case COMMUNICATION_FAILURE:
            // Already seen a communication failure. There's no point trying to report another one.
            return logAndReturnEndResult(firstEndReason, firstTaskFailureType, firstException,
                    stopContainerRequested.get());
        case TASK_ERROR:
            // Don't report an error again if it was reported via signalFatalError
            if (errorReporterToAm.get()) {
                return logAndReturnEndResult(firstEndReason, firstTaskFailureType, firstException,
                        stopContainerRequested.get());
            } else {
                String message;
                if (firstException instanceof FSError) {
                    message = "Encountered an FSError while executing task: " + task.getTaskAttemptID();
                } else if (firstException instanceof Error) {
                    message = "Encountered an Error while executing task: " + task.getTaskAttemptID();
                } else {
                    message = "Error while running task ( failure ) : " + task.getTaskAttemptID();
                }
                try {
                    taskReporter.taskFailed(task.getTaskAttemptID(), firstTaskFailureType, firstException,
                            message, exceptionSourceInfo);
                    return logAndReturnEndResult(firstEndReason, firstTaskFailureType, firstException,
                            stopContainerRequested.get());
                } catch (IOException e) {
                    // Comm failure. Task can't do much.
                    handleFinalStatusUpdateFailure(e, "failure");
                    return logAndReturnEndResult(firstEndReason, firstTaskFailureType, firstException,
                            stopContainerRequested.get());
                } catch (TezException e) {
                    // Failure from AM. Task can't do much.
                    handleFinalStatusUpdateFailure(e, "failure");
                    return logAndReturnEndResult(firstEndReason, firstTaskFailureType, firstException,
                            stopContainerRequested.get());
                }
            }
        default:
            LOG.error("Unexpected EndReason. File a bug");
            return logAndReturnEndResult(EndReason.TASK_ERROR, firstTaskFailureType,
                    new RuntimeException("Unexpected EndReason"), stopContainerRequested.get());

        }
    } finally {
        // Clear the interrupted status of the blocking thread, in case it is set after the
        // InterruptedException was invoked.
        oobSignalLock.lock();
        try {
            while (oobSignalErrorInProgress) {
                try {
                    oobSignalCondition.await();
                } catch (InterruptedException e) {
                    LOG.warn("Interrupted while waiting for OOB fatal error to complete");
                    Thread.currentThread().interrupt();
                }
            }
        } finally {
            oobSignalLock.unlock();
        }
        taskReporter.unregisterTask(task.getTaskAttemptID());
        if (taskKillStartTime != 0) {
            LOG.info("Time taken to interrupt task={}", (System.currentTimeMillis() - taskKillStartTime));
        }
        if (localExecutor != null) {
            localExecutor.shutdown();
        }
        Thread.interrupted();
    }
}