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.abs_models.backend.erlang.ErlangTestDriver.java

/**
 * Executes mainModule//from   ww w . j a v a 2s  .  c o  m
 *
 * To detect faults, we have a Timeout process which will kill the
 * runtime system after 10 seconds
 */
private String run(File workDir, String mainModule) throws Exception {
    String val = null;
    String runFileName = ErlangBackend.isWindows() ? "run.bat" : "run";
    File runFile = new File(workDir, runFileName);
    ProcessBuilder pb = new ProcessBuilder(runFile.getAbsolutePath(), mainModule);
    pb.directory(workDir);
    pb.redirectErrorStream(true);
    Process p = pb.start();

    Thread t = new Thread(new TimeoutThread(p));
    t.start();
    // Search for result
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    while (true) {
        String line = br.readLine();
        if (line == null)
            break;
        if (line.startsWith("RES=")) // see `genCode' above
            val = line.split("=")[1];
    }
    int res = p.waitFor();
    t.interrupt();
    if (res != 0)
        return null;
    return val;

}

From source file:org.apache.tika.parser.ocr.TesseractOCRParser.java

/**
 * Run external tesseract-ocr process./*from w w w  . java2s.  co  m*/
 *
 * @param input
 *          File to be ocred
 * @param output
 *          File to collect ocr result
 * @param config
 *          Configuration of tesseract-ocr engine
 * @throws TikaException
 *           if the extraction timed out
 * @throws IOException
 *           if an input error occurred
 */
private void doOCR(File input, File output, TesseractOCRConfig config) throws IOException, TikaException {
    String[] cmd = { config.getTesseractPath() + getTesseractProg(), input.getPath(), output.getPath(), "-l",
            config.getLanguage(), "-psm", config.getPageSegMode() };

    ProcessBuilder pb = new ProcessBuilder(cmd);
    setEnv(config, pb);
    final Process process = pb.start();

    process.getOutputStream().close();
    InputStream out = process.getInputStream();
    InputStream err = process.getErrorStream();

    logStream("OCR MSG", out, input);
    logStream("OCR ERROR", err, input);

    FutureTask<Integer> waitTask = new FutureTask<Integer>(new Callable<Integer>() {
        public Integer call() throws Exception {
            return process.waitFor();
        }
    });

    Thread waitThread = new Thread(waitTask);
    waitThread.start();

    try {
        waitTask.get(config.getTimeout(), TimeUnit.SECONDS);

    } catch (InterruptedException e) {
        waitThread.interrupt();
        process.destroy();
        Thread.currentThread().interrupt();
        throw new TikaException("TesseractOCRParser interrupted", e);

    } catch (ExecutionException e) {
        // should not be thrown

    } catch (TimeoutException e) {
        waitThread.interrupt();
        process.destroy();
        throw new TikaException("TesseractOCRParser timeout", e);
    }

}

From source file:org.openspaces.maven.plugin.RunPUMojo.java

/**
 * Executed the Mojo./*from   w w w  .  j  av a  2s .  c o  m*/
 */
public void executeMojo() throws MojoExecutionException, MojoFailureException {
    // Remove white spaces from ClassLoader's URLs
    ClassLoader currentCL = Thread.currentThread().getContextClassLoader();
    try {
        Utils.changeClassLoaderToSupportWhiteSpacesRepository(currentCL);
    } catch (Exception e) {
        PluginLog.getLog().info("Unable to update ClassLoader. Proceeding with processing unit invocation.", e);
    }

    Utils.handleSecurity();
    try {
        ClassUtils.forName("com.gigaspaces.logger.GSLogConfigLoader", null).getMethod("getLoader", new Class[0])
                .invoke(null, new Object[0]);
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to configure logging", e);
    }

    // get a list of project to execute in the order set by the reactor
    List projects = Utils.getProjectsToExecute(reactorProjects, module);

    for (Iterator projIt = projects.iterator(); projIt.hasNext();) {
        MavenProject proj = (MavenProject) projIt.next();
        executePU(proj);
    }

    final Thread mainThread = Thread.currentThread();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                for (int i = (containers.size() - 1); i >= 0; --i) {
                    ((Thread) containers.get(i)).interrupt();
                }
            } finally {
                mainThread.interrupt();
            }
        }
    });

    while (!mainThread.isInterrupted()) {
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException e) {
            // do nothing, simply exit
        }
    }
}

From source file:org.springframework.integration.channel.QueueChannelTests.java

@Test
public void testBlockingSendWithNoTimeout() throws Exception {
    final QueueChannel channel = new QueueChannel(1);
    boolean result1 = channel.send(new GenericMessage<String>("test-1"));
    assertTrue(result1);/*w  ww  .  j  a  v a 2s . c om*/
    final AtomicBoolean sendInterrupted = new AtomicBoolean(false);
    final CountDownLatch latch = new CountDownLatch(1);
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            channel.send(new GenericMessage<String>("test-2"));
            sendInterrupted.set(true);
            latch.countDown();
        }
    });
    t.start();
    assertFalse(sendInterrupted.get());
    t.interrupt();
    latch.await();
    assertTrue(sendInterrupted.get());
}

From source file:org.apache.hadoop.mapred.MiniMRCluster.java

/**
 * Kill the tasktracker./* w  w w .  j  av a2s. com*/
 */
public void stopTaskTracker(int id) {
    TaskTrackerRunner tracker = taskTrackerList.remove(id);
    tracker.shutdown();

    Thread thread = taskTrackerThreadList.remove(id);
    thread.interrupt();

    try {
        thread.join();
        // This will break the wait until idle loop
        tracker.isDead = true;
        --numTaskTrackers;
    } catch (InterruptedException ex) {
        LOG.error("Problem waiting for task tracker to finish", ex);
    }
}

From source file:org.silverpeas.core.util.DBUtilIntegrationTest.java

private int nextUniqueIdUpdateForAnExistingTableShouldWorkAndConcurrency(final String tableName,
        final int nbThreads) throws SQLException, InterruptedException {
    Logger.getAnonymousLogger().info("Start at " + System.currentTimeMillis() + " with " + nbThreads
            + " threads for table " + tableName);
    final Thread[] threads = new Thread[nbThreads];
    for (int i = 0; i < nbThreads; i++) {
        threads[i] = new Thread(() -> {
            try {
                int nextId = DBUtil.getNextId(tableName, "id");
                Logger.getAnonymousLogger().info(
                        "Next id for " + tableName + " is " + nextId + " at " + System.currentTimeMillis());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }// w  ww.ja  v  a  2 s  .  c o m
        });
    }

    try {
        for (Thread thread : threads) {
            thread.start();
            Thread.sleep(5);
        }
        for (Thread thread : threads) {
            thread.join();
        }
        return actualMaxIdInUniqueIdFor(tableName);
    } finally {
        for (Thread thread : threads) {
            if (thread.isAlive()) {
                thread.interrupt();
            }
        }
    }
}

From source file:org.springframework.integration.channel.QueueChannelTests.java

@Test
public void testBlockingSendWithTimeout() throws Exception {
    final QueueChannel channel = new QueueChannel(1);
    boolean result1 = channel.send(new GenericMessage<String>("test-1"));
    assertTrue(result1);//ww  w .  j  a va 2 s  . c  om
    final AtomicBoolean sendInterrupted = new AtomicBoolean(false);
    final CountDownLatch latch = new CountDownLatch(1);
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            channel.send(new GenericMessage<String>("test-2"), 10000);
            sendInterrupted.set(true);
            latch.countDown();
        }
    });
    t.start();
    assertFalse(sendInterrupted.get());
    t.interrupt();
    latch.await();
    assertTrue(sendInterrupted.get());
}

From source file:com.andybotting.tubechaser.activity.Home.java

/**
 * //from w w  w .  j  a  v a  2  s.c  o  m
 */
public synchronized void stopRefreshThread() {
    if (mRefreshThread != null) {
        if (LOGV)
            Log.v(TAG, "Stopping refresh thread");
        Thread killThread = mRefreshThread;
        mRefreshThread = null;
        killThread.interrupt();
        mInfoWindowFirstUpdate = true;
    }
}

From source file:de.hybris.platform.cronjob.jalo.TriggerableJobTest.java

private void waitToFinish(final CronJob cronJob) {
    final Thread thread = Thread.currentThread();
    final long maxWaitTime = System.currentTimeMillis() + (triggerPerformWaitSeconds * 1000);
    while (!cronJob.isFinished() && !thread.isInterrupted() && System.currentTimeMillis() < maxWaitTime) {
        try {/*from  ww w  . j a  v  a  2s .c o  m*/
            Thread.sleep(500);
        } catch (final InterruptedException e) {
            thread.interrupt();
        }
    }
}

From source file:net.sf.taverna.t2.servicedescriptions.impl.ServiceDescriptionRegistryImpl.java

@Override
public synchronized void removeServiceDescriptionProvider(ServiceDescriptionProvider provider) {
    if (!userAddedProviders.remove(provider))
        // Not previously added - must be a default one.. but should we remove it?
        if (loading || serviceDescriptionsConfig.isRemovePermanently()
                && serviceDescriptionsConfig.isIncludeDefaults())
            userRemovedProviders.add(provider);
    if (allServiceProviders.remove(provider)) {
        synchronized (providerDescriptions) {
            Thread thread = serviceDescriptionThreads.remove(provider);
            if (thread != null)
                thread.interrupt();
            providerDescriptions.remove(provider);
        }//from w ww . jav a2 s  .co  m
        observers.notify(new RemovedProviderEvent(provider));
    }
    if (!loading)
        saveServiceDescriptions();
}