Example usage for java.lang Thread interrupt

List of usage examples for java.lang Thread interrupt

Introduction

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

Prototype

public void interrupt() 

Source Link

Document

Interrupts this thread.

Usage

From source file:org.waarp.openr66.context.task.ExecMoveTask.java

@Override
public void run() {
    /*/*from   ww  w  .  j a v  a  2 s.  c  om*/
     * First apply all replacements and format to argRule from context and argTransfer. Will
     * call exec (from first element of resulting string) with arguments as the following value
     * from the replacements. Return 0 if OK, else 1 for a warning else as an error. The last
     * line of stdout will be the new name given to the R66File in case of status 0. The
     * previous file should be deleted by the script or will be deleted in case of status 0. If
     * the status is 1, no change is made to the file.
     */
    logger.info("ExecMove with " + argRule + ":" + argTransfer + " and {}", session);
    String finalname = argRule;
    finalname = getReplacedValue(finalname, argTransfer.split(" "));
    // Force the WaitForValidation
    waitForValidation = true;
    if (Configuration.configuration.isUseLocalExec() && useLocalExec) {
        LocalExecClient localExecClient = new LocalExecClient();
        if (localExecClient.connect()) {
            localExecClient.runOneCommand(finalname, delay, waitForValidation, futureCompletion);
            LocalExecResult result = localExecClient.getLocalExecResult();
            move(result.getStatus(), result.getResult(), finalname);
            localExecClient.disconnect();
            return;
        } // else continue
    }
    String[] args = finalname.split(" ");
    File exec = new File(args[0]);
    if (exec.isAbsolute()) {
        if (!exec.canExecute()) {
            logger.error("Exec command is not executable: " + finalname);
            R66Result result = new R66Result(session, false, ErrorCode.CommandNotFound, session.getRunner());
            futureCompletion.setResult(result);
            futureCompletion.cancel();
            return;
        }
    }
    CommandLine commandLine = new CommandLine(args[0]);
    for (int i = 1; i < args.length; i++) {
        commandLine.addArgument(args[i]);
    }
    DefaultExecutor defaultExecutor = new DefaultExecutor();
    PipedInputStream inputStream = new PipedInputStream();
    PipedOutputStream outputStream = null;
    try {
        outputStream = new PipedOutputStream(inputStream);
    } catch (IOException e1) {
        try {
            inputStream.close();
        } catch (IOException e) {
        }
        logger.error("Exception: " + e1.getMessage() + " Exec in error with " + commandLine.toString(), e1);
        futureCompletion.setFailure(e1);
        return;
    }
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, null);
    defaultExecutor.setStreamHandler(pumpStreamHandler);
    int[] correctValues = { 0, 1 };
    defaultExecutor.setExitValues(correctValues);
    ExecuteWatchdog watchdog = null;

    if (delay > 0) {
        watchdog = new ExecuteWatchdog(delay);
        defaultExecutor.setWatchdog(watchdog);
    }
    LastLineReader lastLineReader = new LastLineReader(inputStream);
    Thread thread = new Thread(lastLineReader, "ExecRename" + session.getRunner().getSpecialId());
    thread.setDaemon(true);
    Configuration.configuration.getExecutorService().execute(thread);
    int status = -1;
    try {
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(Configuration.RETRYINMS);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e1) {
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                thread.interrupt();
                try {
                    inputStream.close();
                } catch (IOException e2) {
                }
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e2) {
                }
                logger.error("ExecuteException: " + e.getMessage() + " . Exec in error with "
                        + commandLine.toString());
                futureCompletion.setFailure(e);
                return;
            } catch (IOException e1) {
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                thread.interrupt();
                try {
                    inputStream.close();
                } catch (IOException e2) {
                }
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e2) {
                }
                logger.error(
                        "IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString());
                futureCompletion.setFailure(e);
                return;
            }
        } else {
            try {
                outputStream.close();
            } catch (IOException e1) {
            }
            thread.interrupt();
            try {
                inputStream.close();
            } catch (IOException e1) {
            }
            try {
                pumpStreamHandler.stop();
            } catch (IOException e2) {
            }
            logger.error(
                    "ExecuteException: " + e.getMessage() + " . Exec in error with " + commandLine.toString());
            futureCompletion.setFailure(e);
            return;
        }
    } catch (IOException e) {
        try {
            outputStream.close();
        } catch (IOException e1) {
        }
        thread.interrupt();
        try {
            inputStream.close();
        } catch (IOException e1) {
        }
        try {
            pumpStreamHandler.stop();
        } catch (IOException e2) {
        }
        logger.error("IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString());
        futureCompletion.setFailure(e);
        return;
    }
    try {
        outputStream.flush();
    } catch (IOException e) {
    }
    try {
        outputStream.close();
    } catch (IOException e) {
    }
    try {
        pumpStreamHandler.stop();
    } catch (IOException e2) {
    }
    try {
        if (delay > 0) {
            thread.join(delay);
        } else {
            thread.join();
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    try {
        inputStream.close();
    } catch (IOException e1) {
    }
    String newname = null;
    if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) {
        // kill by the watchdoc (time out)
        status = -1;
        newname = "TimeOut";
    } else {
        newname = lastLineReader.getLastLine();
        if (status == 0 && (newname == null || newname.isEmpty())) {
            status = 1;
        }
    }
    move(status, newname, commandLine.toString());
}

From source file:org.uiautomation.ios.wkrdp.ResponseFinderList.java

public JSONObject findResponse(final int id) {
    final long start = System.currentTimeMillis();
    // start all the finders.
    for (final ResponseFinder finder : finders) {
        Thread t = new Thread(new Runnable() {
            @Override/*from   w w w .  j  a v  a2 s. c  om*/
            public void run() {
                try {
                    finder.startSearch(id);
                    log.fine("finder " + finder.getClass() + " found something - "
                            + (System.currentTimeMillis() - start) + "ms");
                    try {
                        lock.lock();
                        foundIt.signal();
                    } finally {
                        lock.unlock();
                    }
                } catch (InterruptedException e) {
                    log.fine("search was interrupted.");
                }

            }
        });
        threads.add(t);
        t.start();
    }

    // when for one to finish
    try {
        try {
            lock.lock();
            foundIt.await(timeoutInMs, TimeUnit.MILLISECONDS);
            log.fine("await returns " + (System.currentTimeMillis() - start) + "ms");
        } finally {
            lock.unlock();
        }

    } catch (InterruptedException e) {
    }

    for (Thread t : threads) {
        t.interrupt();
    }
    // stop the others
    for (ResponseFinder finder : finders) {
        finder.interruptSearch();
    }
    log.fine("all finders interrupted " + (System.currentTimeMillis() - start) + "ms");
    for (ResponseFinder finder : finders) {
        JSONObject response = finder.getResponse();
        if (response != null) {
            log.fine("returns response  " + (System.currentTimeMillis() - start) + "ms");
            return response;
        }
    }

    throw new RuntimeException("bug.One of the finder should have got something.");
}

From source file:org.yccheok.jstock.gui.IndicatorScannerJPanel.java

public void stop() {
    writer.lock();// w w  w. j a va2  s  .c  o m
    try {
        /* Hacking way to make startScanThread stop within a very short time. */
        stop_button_pressed = true;

        // We must ensure there is no reader locking mechanism within 
        // startScanThread. If not, deadlock might happen.
        final Thread thread = this.startScanThread;
        this.startScanThread = null;
        if (thread != null) {
            thread.interrupt();
            try {
                thread.join();
            } catch (InterruptedException ex) {
                log.error(null, ex);
            }
        }
        final JStock m = JStock.instance();
        this.initRealTimeStockMonitor();
        this.initStockHistoryMonitor();
        this.initAlertDataStructures();
        this.initCompleteProgressDataStructures();
    } finally {
        writer.unlock();
    }

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            jButton1.setEnabled(true);
            jButton2.setEnabled(false);
        }

    });

    JStock.instance().setStatusBar(false, java.util.ResourceBundle.getBundle("org/yccheok/jstock/data/gui")
            .getString("IndicatorScannerJPanel_Connected"));
}

From source file:org.jumpmind.symmetric.AbstractSymmetricEngine.java

public synchronized void stop() {

    log.info("Stopping SymmetricDS externalId={} version={} database={}",
            new Object[] { parameterService == null ? "?" : parameterService.getExternalId(), Version.version(),
                    symmetricDialect == null ? "?" : symmetricDialect.getName() });
    if (jobManager != null) {
        jobManager.stopJobs();//from   w w w  . j a v  a 2s. c  o m
    }
    if (routerService != null) {
        routerService.stop();
    }
    if (nodeCommunicationService != null) {
        nodeCommunicationService.stop();
    }

    if (pushService != null) {
        pushService.stop();
    }

    if (dataLoaderService != null) {
        dataLoaderService.stop();
    }

    if (statisticManager != null) {
        List<ProcessInfo> infos = statisticManager.getProcessInfos();
        for (ProcessInfo processInfo : infos) {
            Thread thread = processInfo.getThread();
            if (processInfo.getStatus() != Status.OK && thread.isAlive()) {
                log.info("Trying to interrupt thread '{}' ", thread.getName());
                try {
                    thread.interrupt();
                } catch (Exception e) {
                    log.info("Caught exception while attempting to interrupt thread", e);
                }
            }
        }

        Thread.interrupted();
    }

    started = false;
    starting = false;

}

From source file:org.ulyssis.ipp.control.CommandDispatcher.java

public void run() {
    Thread statusThread = new Thread(() -> {
        try {/*from  www.ja  v a 2  s.  c  o m*/
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    JedisHelper.get(redisUri).subscribe(createResultListener(), statusChannel);
                } catch (JedisConnectionException e) {
                    // TODO: After a while, deregister the processor?
                    LOG.error("Connection with Redis was broken! Trying again in 0.5s.", e);
                    Thread.sleep(500L);
                }
            }
        } catch (InterruptedException ignored) {
        }
    });
    statusThread.start();
    while (!Thread.interrupted()) {
        try {
            Command command = commandsToSend.take();
            LOG.debug("Sending command {}", command.getCommandId());
            jedis.publish(controlChannel, Serialization.getJsonMapper().writeValueAsBytes(command));
        } catch (InterruptedException ignored) {
        } catch (JsonProcessingException e) {
            LOG.error("Error writing command as JSON object", e);
        }
    }
    statusThread.interrupt();
    try {
        statusThread.join();
    } catch (InterruptedException ignored) {
    }
}

From source file:eu.stratosphere.nephele.taskmanager.runtime.RuntimeTask.java

/**
 * Cancels or kills the task.//from  w  ww  .j a va 2s .  c o  m
 * 
 * @param cancel
 *        <code>true/code> if the task shall be canceled, <code>false</code> if it shall be killed
 */
private void cancelOrKillExecution(final boolean cancel) {

    final Thread executingThread = this.environment.getExecutingThread();

    if (executingThread == null) {
        return;
    }

    if (this.executionState != ExecutionState.RUNNING && this.executionState != ExecutionState.FINISHING) {
        return;
    }

    LOG.info((cancel ? "Canceling " : "Killing ") + this.environment.getTaskNameWithIndex());

    if (cancel) {
        this.isCanceled = true;
        // Change state
        executionStateChanged(ExecutionState.CANCELING, null);

        // Request user code to shut down
        try {
            final AbstractInvokable invokable = this.environment.getInvokable();
            if (invokable != null) {
                invokable.cancel();
            }
        } catch (Throwable e) {
            LOG.error(StringUtils.stringifyException(e));
        }
    }

    // Continuously interrupt the user thread until it changed to state CANCELED
    while (true) {

        executingThread.interrupt();

        if (!executingThread.isAlive()) {
            break;
        }

        try {
            executingThread.join(1000);
        } catch (InterruptedException e) {
        }

        if (!executingThread.isAlive()) {
            break;
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Sending repeated " + (cancel == true ? "canceling" : "killing") + " signal to "
                    + this.environment.getTaskName() + " with state " + this.executionState);
        }
    }
}

From source file:nz.govt.natlib.ndha.manualdeposit.jobmanagement.UploadJob.java

public void run() {
    Date startRunDate = new Date();
    theJobState = JobState.Running;
    Date startWaitCopyDate = new Date();
    long totalSetupTime = 0;
    long totalWriteTime = 0;
    long totalDepositTime = 0;
    while (!isCopyFinished) {
        try {//from   ww  w  .  j  a  v  a 2  s . c o  m
            Thread.sleep(100);
        } catch (Exception ex) {
        }
        if (canCancelJob) {
            jobDetailStatus = "Cancelling...";
            theJobState = JobState.Cancelled;
            return;
        }
    }
    Date endWaitCopyDate = new Date();
    try {
        String metsRootDirectory = cleanUpForID(theSystemUserID + "/" + getEntityNamePadded());
        boolean includeEntityNameInTitle;
        if (shouldCheckForIncludeName) {
            includeEntityNameInTitle = (allJobDetail.size() >= 1);
        } else {
            includeEntityNameInTitle = false;
        }
        for (String key : allJobDetail.keySet()) {
            JobDetail detail = allJobDetail.get(key);
            jobDetailStatus = "Processing " + detail.getEntityName();
            Date startDate = new Date();
            theWriter = appProperties.getApplicationData().getMetsWriter();
            theWriter.setup(detail.getEntityName(), theSavePath,
                    appProperties.getApplicationData().getMetsFTPServer(),
                    appProperties.getApplicationData().getMetsFTPUser(),
                    appProperties.getApplicationData().getMetsFTPPassword(), theIeRoot, theSystemUserID,
                    metsRootDirectory, includeEntityNameInTitle,
                    appProperties.getApplicationData().isIncludeFileDates(), theFixityType);
            for (int i = 0; i < detail.getTheMetaData().size(); i++) {
                IMetaDataTypeExtended meta = detail.getTheMetaData().getAt(i);
                if (meta.getDataType() == EDataType.ProvenanceNote) {

                    theWriter.addProvenanceNote(meta.getProvenanceNoteEventType(),
                            meta.getProvenanceEventIdentifierType(), meta.getProvenanceEventIdentifierValue(),
                            meta.getProvenanceEventOutcome(), meta.getProvenanceEventOutcomeDetail(),
                            meta.getProvenanceEventDescription(), Calendar.getInstance());

                } else if ((meta.getDataFieldValue() != null) && (meta.getWillBeUploaded())) {
                    theWriter.addDescriptiveMetaDataField(meta);
                }
            }
            theWriter.setCreator(System.getProperty(theCreator));
            theWriter.setEntities(detail.getFileGroups());
            theWriter.setStructure(detail.getStructures());
            Date endDate = new Date();
            totalSetupTime = endDate.getTime() - startDate.getTime();
            startDate = new Date();
            Thread t = new Thread(theWriter);
            t.start();
            while (!theWriter.isFinished() && !theWriter.isFailed()) {
                if (canCancelJob) {
                    t.interrupt();
                    jobDetailStatus = "Cancelling...";
                    theJobState = JobState.Cancelled;
                    return;
                } else {
                    jobDetailStatus = theWriter.getStatus();
                    Thread.sleep(100);
                }
            }
            endDate = new Date();
            totalWriteTime = endDate.getTime() - startDate.getTime();
            if (theWriter.isFailed()) {
                theJobState = JobState.Failed;
            }
            if (canCancelJob) {
                jobDetailStatus = "Cancelled";
                theJobState = JobState.Cancelled;
                break;
            } else if (theJobState.isFailure) {
                jobDetailStatus = "Job failed - " + theWriter.getFailureMessage();
                break;
            } else {
                jobDetailStatus = theWriter.getStatus();
            }
        }
        if (!theJobState.isFailure) {
            LOG.info("Depositing job");
            Date startDate = new Date();
            IDeposit deposit = appProperties.getApplicationData().getDeposit();
            ResultOfDeposit result = deposit.deposit(metsRootDirectory, theSystemUserID,
                    appProperties.getLoggedOnUserPassword(),
                    appProperties.getApplicationData().getDepositUserInstitution(), theProducerID,
                    theMaterialFlowID, appProperties.getApplicationData().getDepositSetID());
            Date endDate = new Date();
            totalDepositTime = endDate.getTime() - startDate.getTime();
            LOG.info("Job deposited");
            if (result.isSuccess()) {
                theJobState = JobState.Deposited;
                theSipID = result.getSipID();
                jobDetailStatus = "Deposited.  SIP ID " + theSipID + " added.";
            } else {
                theJobState = JobState.Failed;
                jobDetailStatus = result.getResultMessage();
            }
            // Swallow any exception - as we don't need the SIP status yet
            try {
                theSipStatus = appProperties.getApplicationData().getDeposit().getSipStatus(theSipID);
            } catch (Exception ex) {
            }
        }
        saveJob(false);
    } catch (Exception ex) {
        handleException(ex);
    }
    Date endRunDate = new Date();
    long totalTime = endRunDate.getTime() - startRunDate.getTime();
    long totalWaitTime = endWaitCopyDate.getTime() - startWaitCopyDate.getTime();
    System.out.println(String.format(
            "Total time: %d, wait time: %d, setup mets time: %d, write mets time: %d, deposit time: %d",
            totalTime, totalWaitTime, totalSetupTime, totalWriteTime, totalDepositTime));
}

From source file:eu.stratosphere.nephele.taskmanager.Task.java

/**
 * Cancels or kills the task./*from  w w w .  jav  a 2s .  co  m*/
 *
 * @param cancel <code>true/code> if the task shall be canceled, <code>false</code> if it shall be killed
 */
private void cancelOrKillExecution(boolean cancel) {
    final Thread executingThread = this.environment.getExecutingThread();

    if (executingThread == null) {
        return;
    }

    if (this.executionState != ExecutionState.RUNNING && this.executionState != ExecutionState.FINISHING) {
        return;
    }

    LOG.info((cancel ? "Canceling " : "Killing ") + this.environment.getTaskNameWithIndex());

    if (cancel) {
        this.isCanceled = true;
        // Change state
        executionStateChanged(ExecutionState.CANCELING, null);

        // Request user code to shut down
        try {
            final AbstractInvokable invokable = this.environment.getInvokable();
            if (invokable != null) {
                invokable.cancel();
            }
        } catch (Throwable e) {
            LOG.error(StringUtils.stringifyException(e));
        }
    }

    // Continuously interrupt the user thread until it changed to state CANCELED
    while (true) {

        executingThread.interrupt();

        if (!executingThread.isAlive()) {
            break;
        }

        try {
            executingThread.join(1000);
        } catch (InterruptedException e) {
        }

        if (!executingThread.isAlive()) {
            break;
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Sending repeated " + (cancel == true ? "canceling" : "killing") + " signal to "
                    + this.environment.getTaskName() + " with state " + this.executionState);
        }
    }
}

From source file:io.openvidu.server.recording.service.RecordingManager.java

public void initializeRecordingManager() throws OpenViduException {

    RecordingManager.IMAGE_TAG = openviduConfig.getOpenViduRecordingVersion();

    this.dockerManager = new DockerManager();
    this.composedRecordingService = new ComposedRecordingService(this, openviduConfig);
    this.singleStreamRecordingService = new SingleStreamRecordingService(this, openviduConfig);

    log.info("Recording module required: Downloading openvidu/openvidu-recording:"
            + openviduConfig.getOpenViduRecordingVersion() + " Docker image (350MB aprox)");

    this.checkRecordingRequirements(this.openviduConfig.getOpenViduRecordingPath(),
            this.openviduConfig.getOpenviduRecordingCustomLayout());

    if (dockerManager.dockerImageExistsLocally(IMAGE_NAME + ":" + IMAGE_TAG)) {
        log.info("Docker image already exists locally");
    } else {/*from  www.  j av a 2 s .  c  o  m*/
        Thread t = new Thread(() -> {
            boolean keep = true;
            log.info("Downloading ");
            while (keep) {
                System.out.print(".");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    keep = false;
                    log.info("\nDownload complete");
                }
            }
        });
        t.start();
        try {
            dockerManager.downloadDockerImage(IMAGE_NAME + ":" + IMAGE_TAG, 600);
        } catch (Exception e) {
            log.error("Error downloading docker image {}:{}", IMAGE_NAME, IMAGE_TAG);
        }
        t.interrupt();
        try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("Docker image available");
    }

    // Clean any stranded openvidu/openvidu-recording container on startup
    dockerManager.cleanStrandedContainers(RecordingManager.IMAGE_NAME);
}

From source file:bixo.fetcher.SimpleHttpFetcherTest.java

@Test
public final void testInterruptedFetch() throws Exception {
    // Need to read in lots of data that we get very slowly
    Server server = startServer(new RandomResponseHandler(20000, 2 * 1000L), 8089);

    // Set no response rate, so that doesn't trigger an exception
    FetcherPolicy policy = new FetcherPolicy();
    policy.setMinResponseRate(FetcherPolicy.NO_MIN_RESPONSE_RATE);

    final BaseFetcher fetcher = new SimpleHttpFetcher(1, policy, ConfigUtils.BIXO_TEST_AGENT);
    final String[] failMsg = new String[1];

    Thread t = new Thread(new Runnable() {

        @Override/*  w  ww.  j a  v  a2s. c o  m*/
        public void run() {
            String url = "http://localhost:8089/test.html";
            try {
                fetcher.get(new ScoredUrlDatum(url));
                failMsg[0] = "No exception thrown, should have thrown an aborted by interrupt exception";
            } catch (AbortedFetchException e) {
                if (e.getAbortReason() != AbortedFetchReason.INTERRUPTED) {
                    failMsg[0] = "Wrong abort exception thrown, should have thrown an aborted by interrupt exception";
                }
            } catch (BaseFetchException e) {
                failMsg[0] = "Wrong exception thrown, should have thrown an aborted by interrupt exception";
            }
        }
    });

    t.start();
    t.interrupt();

    while (t.isAlive()) {
        Thread.sleep(100);
    }

    server.stop();

    if (failMsg[0] != null) {
        fail(failMsg[0]);
    }
}