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:com.chiorichan.updater.Download.java

@Override
public void run() {
    ReadableByteChannel rbc = null;
    FileOutputStream fos = null;/*from w  w w.ja  va  2  s.co  m*/
    try {
        HttpURLConnection conn = NetworkFunc.openHttpConnection(url);
        int response = conn.getResponseCode();
        int responseFamily = response / 100;

        if (responseFamily == 3)
            throw new DownloadException(
                    "The server issued a redirect response which the Updater failed to follow.");
        else if (responseFamily != 2)
            throw new DownloadException("The server issued a " + response + " response code.");

        InputStream in = getConnectionInputStream(conn);

        size = conn.getContentLength();
        outFile = new File(outPath);
        outFile.delete();

        rbc = Channels.newChannel(in);
        fos = new FileOutputStream(outFile);

        stateChanged();

        Thread progress = new MonitorThread(Thread.currentThread(), rbc);
        progress.start();

        fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE);
        in.close();
        rbc.close();
        progress.interrupt();
        if (size > 0) {
            if (size == outFile.length())
                result = Result.SUCCESS;
        } else
            result = Result.SUCCESS;

        stateDone();
    } catch (DownloadDeniedException e) {
        exception = e;
        result = Result.PERMISSION_DENIED;
    } catch (DownloadException e) {
        exception = e;
        result = Result.FAILURE;
    } catch (Exception e) {
        exception = e;
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(rbc);
    }

    if (exception != null)
        AutoUpdater.getLogger().severe("Download Resulted in an Exception", exception);
}

From source file:lockstep.LockstepServer.java

/**
 * Frees all resources tied to the server, that is networking threads and
 * sockets.//from www .  j  a v  a  2s  .com
 */
private void closeResources() {
    for (Thread transmitter : transmitters.values())
        transmitter.interrupt();

    try {
        for (Thread receiver : receivers.values()) {
            receiver.join();
        }

        for (Thread transmitter : transmitters.values()) {
            transmitter.join();
        }
    } catch (InterruptedException intEx) {
        //shouldn't be interrupted
        LOG.fatal("Interrupted during termination!!");
        LOG.fatal(intEx);
    }
}

From source file:org.apache.tika.parser.mock.MockParserTest.java

@Test
public void testNonInterruptibleSleep() {
    ParserRunnable r = new ParserRunnable("sleep_not_interruptible.xml");
    Thread t = new Thread(r);
    t.start();/* ww w . j  ava2  s.c o  m*/
    long start = new Date().getTime();
    try {
        //make sure that the thread has actually started
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        //swallow
    }
    t.interrupt();
    try {
        t.join(20000);
    } catch (InterruptedException e) {
        //swallow
    }
    long elapsed = new Date().getTime() - start;
    boolean longEnough = elapsed >= 3000;//the xml file specifies 3000, this sleeps 1000
    assertTrue("elapsed (" + elapsed + " millis) was not long enough", longEnough);
}

From source file:org.lilyproject.runtime.LilyRuntime.java

public void stop() {
    if (state != LifeCycle.STARTED) {
        throw new LilyRTException(
                "Cannot stop the runtime, it is in state " + state + " instead of " + LifeCycle.STARTED);
    }//from  ww w  . j a  v  a2 s .com

    // TODO temporarily disabled because FAM.stop() is slow
    // See JCI jira patch: https://issues.apache.org/jira/browse/JCI-57 (the newer one in commons-io has the same problem)
    // fam.stop();
    // Added the following workaround:
    if (System.getSecurityManager() == null) {
        try {
            Field famRunningField = fam.getClass().getDeclaredField("running");
            famRunningField.setAccessible(true);
            Field threadField = fam.getClass().getDeclaredField("thread");
            threadField.setAccessible(true);
            Thread famThread = (Thread) threadField.get(fam);
            if (famThread != null) {
                famRunningField.setBoolean(fam, false);
                famThread.interrupt();
                fam.stop();
            }
        } catch (Exception e) {
            infolog.error("Error stopping FilesystemAlterationMonitor", e);
        }
    } else {
        infolog.warn(
                "Unable to stop the FilesystemAlterationMonitor using workaround since a security manager is installed.");
    }

    // In case starting the runtime failed, modules might be null
    if (modules != null) {
        infolog.info("Shutting down the modules.");
        List<Module> reversedModules = new ArrayList<Module>(this.modules);
        Collections.reverse(reversedModules);
        this.modules = null;
        this.javaServiceManager.stop();

        for (Module module : reversedModules) {
            try {
                module.shutdown();
            } catch (Throwable t) {
                infolog.error("Error shutting down module " + module.getDefinition().getId(), t);
            }
        }
    }

    settings.getConfManager().shutdown();

}

From source file:uk.ac.kcl.tika.parsers.TesseractOCRParser.java

/**
 * Run external tesseract-ocr process./*from  w  w  w. j  a va  2  s. com*/
 *
 * @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:lockstep.LockstepServer.java

/**
 * This method puts the server in waiting for client connections. It returns
 * when the expected number of clients have successfully completed the 
 * handshake.//from   w ww .j a v a 2s .c  om
 * Parallel threads are started to handle the handshakes.
 * In case of failure, all threads are interrupted and then the exception is
 * propagated.
 * 
 * @throws IOException In case of failure on opening the ServerSocket and 
 * accepting connections through it 
 * @throws InterruptedException In case of failure during the handshake 
 * sessions
 */
private void handshakePhase() throws IOException, InterruptedException {
    ServerSocket tcpServerSocket = new ServerSocket(tcpPort);

    CyclicBarrier barrier = new CyclicBarrier(this.clientsNumber);
    CountDownLatch latch = new CountDownLatch(this.clientsNumber);

    //Each session of the protocol starts with a different random frame number
    int firstFrameNumber = (new Random()).nextInt(1000) + 100;

    Thread[] handshakeSessions = new Thread[clientsNumber];

    for (int i = 0; i < clientsNumber; i++) {
        Socket tcpConnectionSocket = tcpServerSocket.accept();
        LOG.info("Connection " + i + " accepted from " + tcpConnectionSocket.getInetAddress().getHostAddress());
        handshakeSessions[i] = new Thread(
                () -> serverHandshakeProtocol(tcpConnectionSocket, firstFrameNumber, barrier, latch, this));
        handshakeSessions[i].start();
    }
    try {
        latch.await();
    } catch (InterruptedException inEx) {
        for (Thread handshakeSession : handshakeSessions)
            handshakeSession.interrupt();

        for (Thread handshakeSession : handshakeSessions)
            handshakeSession.join();

        throw new InterruptedException();
    }
    LOG.info("All handshakes completed");
}

From source file:org.polymap.core.runtime.UIJob.java

/**
 * This cancels the job and, if this does not succeeded, it interrupts the
 * thread of the job. This gives NIO request the chance to cancel.
 *///from   w  w  w  . jav  a 2  s  . c om
public boolean cancelAndInterrupt() {
    boolean result = cancel();
    if (!result) {
        Thread jobThread = UIJob.this.getThread();
        if (jobThread != null && jobThread.isAlive()) {
            jobThread.interrupt();
        }
    }
    return result;
}

From source file:com.alibaba.napoli.metamorphosis.client.consumer.SimpleFetchManager.java

@Override
public void stopFetchRunner() throws InterruptedException {
    topicPartitionRegInfos = null;/*from  w ww . j  a  v a  2 s  . c  o m*/
    this.shutdown = true;
    // 
    if (this.fetchRunners != null) {
        for (final Thread thread : this.fetchRunners) {
            if (thread != null) {
                thread.interrupt();
                try {
                    thread.join(5000);
                } catch (final InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }

        }
    }
    // ?
    if (this.requestQueue != null) {
        while (this.requestQueue.size() != this.fetchRequestCount) {
            Thread.sleep(50);
        }
    }

}

From source file:jenkins.plugins.publish_over_ssh.BapSshClient.java

private void waitForExec(final ChannelExec exec, final long timeout) {
    final long start = System.currentTimeMillis();
    final Thread waiter = new ExecCheckThread(exec);
    waiter.start();//w w w .j a v  a  2  s.c om
    try {
        waiter.join(timeout);
    } catch (InterruptedException ie) {
    }
    final long duration = System.currentTimeMillis() - start;
    if (waiter.isAlive()) {
        waiter.interrupt();
    }
    if (!exec.isClosed())
        throw new BapPublisherException(Messages.exception_exec_timeout(duration));
    buildInfo.println(Messages.console_exec_completed(duration));
}

From source file:net.technicpack.launchercore.mirror.download.Download.java

@Override
@SuppressWarnings("unused")
public void run() {
    ReadableByteChannel rbc = null;
    FileOutputStream fos = null;//from w  ww . ja v  a2s . c  o  m
    try {
        HttpURLConnection conn = Utils.openHttpConnection(url);
        int response = conn.getResponseCode();
        int responseFamily = response / 100;

        if (responseFamily == 3) {
            String redirUrlText = conn.getHeaderField("Location");
            if (redirUrlText != null && !redirUrlText.isEmpty()) {
                URL redirectUrl = null;
                try {
                    redirectUrl = new URL(redirUrlText);
                } catch (MalformedURLException ex) {
                    throw new DownloadException("Invalid Redirect URL: " + url, ex);
                }

                conn = Utils.openHttpConnection(redirectUrl);
                response = conn.getResponseCode();
                responseFamily = response / 100;
            }
        }

        if (responseFamily != 2) {
            throw new DownloadException("The server issued a " + response + " response code.");
        }

        InputStream in = getConnectionInputStream(conn);

        size = conn.getContentLength();
        outFile = new File(outPath);
        outFile.delete();

        rbc = Channels.newChannel(in);
        fos = new FileOutputStream(outFile);

        stateChanged();

        Thread progress = new MonitorThread(Thread.currentThread(), rbc);
        progress.start();

        fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE);
        in.close();
        rbc.close();
        progress.interrupt();

        synchronized (timeoutLock) {
            if (isTimedOut) {
                return;
            }
        }

        if (size > 0) {
            if (size == outFile.length()) {
                result = Result.SUCCESS;
            }
        } else {
            result = Result.SUCCESS;
        }
    } catch (ClosedByInterruptException ex) {
        result = Result.FAILURE;
        return;
    } catch (PermissionDeniedException e) {
        exception = e;
        result = Result.PERMISSION_DENIED;
    } catch (DownloadException e) {
        exception = e;
        result = Result.FAILURE;
    } catch (Exception e) {
        exception = e;
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(rbc);
    }
}