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.ulyssis.ipp.reader.Reader.java

/**
 * Run the reader. Reader implements runnable, so that we can
 * do this in its own thread./*w  w w .  jav a  2s. co  m*/
 */
@Override
public void run() {
    LOG.info("Spinning up reader!");
    ReaderConfig.Type type = Config.getCurrentConfig().getReader(options.getId()).getType();
    if (type == ReaderConfig.Type.LLRP) {
        initSpeedway();
        if (!speedwayInitialized) {
            shutdownHook();
            return;
        }
    } else if (type == ReaderConfig.Type.SIMULATOR) {
        initSimulator();
    }
    Thread commandThread = new Thread(commandProcessor);
    commandThread.start();
    statusReporter.broadcast(new StatusMessage(StatusMessage.MessageType.STARTED_UP,
            String.format("Started up reader %s!", options.getId())));
    try {
        while (!Thread.currentThread().isInterrupted()) {
            Duration maxUpdateInterval = Duration.ofMillis(Config.getCurrentConfig().getMaxUpdateInterval());
            if (maxUpdateInterval.minus(Duration.between(lastUpdate, Instant.now())).isNegative()) {
                lastUpdate = Instant.now();
                LOG.warn("No update received in {} seconds!", maxUpdateInterval.getSeconds());
                statusReporter.broadcast(new StatusMessage(StatusMessage.MessageType.NO_UPDATES,
                        String.format("No update received in %s seconds!", maxUpdateInterval.getSeconds())));
            }
            Thread.sleep(1000L);
        }
    } catch (InterruptedException e) {
        // We don't care about this exception
    }
    commandProcessor.stop();
    commandThread.interrupt();
    try {
        commandThread.join();
    } catch (InterruptedException ignored) {
    }
    shutdownHook();
}

From source file:org.lsc.AbstractSynchronize.java

public final synchronized void shutdownAsynchronousSynchronize2Ldap(final String syncName, boolean forceStop) {
    Thread asyncThread = asynchronousThreads.get(syncName);
    long startTime = System.currentTimeMillis();

    if (asyncThread == null) {
        LOGGER.info("Trying to stop a non running asynchronous task: " + syncName);
        return;//from   www  .j a  va  2 s. c om
    }

    while (asyncThread.isAlive()) {
        try {
            asyncThread.join(1000);
            if ((System.currentTimeMillis() - startTime) > 5000) {
                if (forceStop) {
                    // After 5 secondes, leaving
                    asyncThread.interrupt();
                    asyncThread.join(1000);
                } else {
                    break;
                }
            }
        } catch (InterruptedException ie) {
            // Thread has been interrupted, doing nothing
        }
    }
    if (!asyncThread.isAlive()) {
        asynchronousThreads.remove(syncName);
        mapSTasks.remove(syncName);
    }
}

From source file:uk.ac.gla.terrier.probos.controller.ControllerServer.java

private void closeThread(Thread t) {
    if (t != null && t.isAlive()) {
        LOG.info("Stopping " + t.getName());
        t.interrupt();
        try {//  w  ww.  j  a  v  a 2s .  com
            t.join();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:org.lilyproject.hadooptestfw.HBaseProxy.java

public void stop() throws Exception {
    if (mode == Mode.EMBED) {
        // Since HBase mini cluster shutdown has a tendency of sometimes failing (hanging waiting on master
        // to end), add a protection for this so that we do not run indefinitely. Especially important not to
        // annoy the other projects on our Hudson server.
        Thread stopHBaseThread = new Thread() {
            @Override/*  ww  w . j  av  a2s  . c o  m*/
            public void run() {
                try {
                    hbaseTestUtil.shutdownMiniCluster();
                    hbaseTestUtil = null;
                } catch (Exception e) {
                    System.out.println("Error shutting down mini cluster.");
                    e.printStackTrace();
                }
            }
        };
        stopHBaseThread.start();
        stopHBaseThread.join(60000);
        if (stopHBaseThread.isAlive()) {
            System.err.println("Unable to stop embedded mini cluster within predetermined timeout.");
            System.err.println("Dumping stack for future investigation.");
            ReflectionUtils.printThreadInfo(new PrintWriter(System.out), "Thread dump");
            System.out.println(
                    "Will now try to interrupt the mini-cluster-stop-thread and give it some more time to end.");
            stopHBaseThread.interrupt();
            stopHBaseThread.join(20000);
            throw new Exception("Failed to stop the mini cluster within the predetermined timeout.");
        }
    }

    // Close connections with HBase and HBase's ZooKeeper handles
    //HConnectionManager.deleteConnectionInfo(CONF, true);
    HConnectionManager.deleteAllConnections(true);

    // Close all HDFS connections
    FileSystem.closeAll();

    conf = null;

    if (clearData && testHome != null) {
        TestHomeUtil.cleanupTestHome(testHome);
    }

    ManagementFactory.getPlatformMBeanServer()
            .unregisterMBean(new ObjectName("LilyHBaseProxy:name=ReplicationPeer"));
}

From source file:edu.rit.flick.genetics.FastFileDeflator.java

@Override
public File deflate(final Configuration configuration, final File fileIn, final File fileOut) {
    assert fileIn.exists();

    try {//w  ww.  j  av a 2  s  .c  o  m
        // Deflate to Directory
        final String outputDirectoryPath = fileOut.getPath()
                .replaceAll("." + Files.getFileExtension(fileOut.getPath()), FLICK_FAST_FILE_TMP_DIR_SUFFIX);

        final File tmpOutputDirectory = new File(outputDirectoryPath);
        if (tmpOutputDirectory.exists())
            FileUtils.deleteDirectory(tmpOutputDirectory);
        tmpOutputDirectory.mkdirs();

        final AtomicReference<Thread> cleanHookAtomic = new AtomicReference<Thread>();

        // Deflate Fast file to a temporary directory
        final Thread deflateToDirectoryThread = new Thread(() -> {
            try {
                // Deflate Fast file to a temporary directory
                deflateToDirectory(fileIn, tmpOutputDirectory);

                // Remove unused buffer space
                removeUnusedBufferSpace(outputDirectoryPath);

                // Compress Directory to a zip file
                deflateToFile(tmpOutputDirectory, fileOut);

                Runtime.getRuntime().removeShutdownHook(cleanHookAtomic.get());
            } catch (final Exception e) {
                if (!interrupted)
                    System.err.println(e.getMessage());
            }
        }, "Default_Deflation_Thread");

        // Make cleaning hook
        final Thread cleanHook = new Thread(() -> {
            interrupted = true;
            configuration.setFlag(VERBOSE_FLAG, false);
            configuration.setFlag(DELETE_FLAG, false);
            try {
                if (deflateToDirectoryThread.isAlive())
                    deflateToDirectoryThread.interrupt();

                // Remove unused buffer space
                removeUnusedBufferSpace(outputDirectoryPath);

                // Delete files that were not able to be processed
                FileUtils.deleteQuietly(tmpOutputDirectory);
                System.out.println();
            } catch (final IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }, "Deflation_Cleaning_Thread");

        cleanHookAtomic.set(cleanHook);

        Runtime.getRuntime().addShutdownHook(cleanHook);

        deflateToDirectoryThread.start();
        deflateToDirectoryThread.join();

    } catch (final IOException | InterruptedException e) {
        e.printStackTrace();
    }

    return fileOut;
}

From source file:com.android.exchange.SyncManager.java

static public void reloadFolderList(Context context, long accountId, boolean force) {
    SyncManager syncManager = INSTANCE;/*www.java2  s .c om*/
    if (syncManager == null)
        return;
    Cursor c = context.getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
            MailboxColumns.ACCOUNT_KEY + "=? AND " + MailboxColumns.TYPE + "=?",
            new String[] { Long.toString(accountId), Long.toString(Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) }, null);
    try {
        if (c.moveToFirst()) {
            synchronized (sSyncLock) {
                Mailbox m = new Mailbox().restore(c);
                Account acct = Account.restoreAccountWithId(context, accountId);
                if (acct == null) {
                    reloadFolderListFailed(accountId);
                    return;
                }
                String syncKey = acct.mSyncKey;
                // No need to reload the list if we don't have one
                if (!force && (syncKey == null || syncKey.equals("0"))) {
                    reloadFolderListFailed(accountId);
                    return;
                }

                // Change all ping/push boxes to push/hold
                ContentValues cv = new ContentValues();
                cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH_HOLD);
                context.getContentResolver().update(Mailbox.CONTENT_URI, cv,
                        WHERE_PUSH_OR_PING_NOT_ACCOUNT_MAILBOX, new String[] { Long.toString(accountId) });
                log("Set push/ping boxes to push/hold");

                long id = m.mId;
                AbstractSyncService svc = syncManager.mServiceMap.get(id);
                // Tell the service we're done
                if (svc != null) {
                    synchronized (svc.getSynchronizer()) {
                        svc.stop();
                    }
                    // Interrupt the thread so that it can stop
                    Thread thread = svc.mThread;
                    thread.setName(thread.getName() + " (Stopped)");
                    thread.interrupt();
                    // Abandon the service
                    syncManager.releaseMailbox(id);
                    // And have it start naturally
                    kick("reload folder list");
                }
            }
        }
    } finally {
        c.close();
    }
}

From source file:edu.brown.benchmark.auctionmark.AuctionMarkLoader.java

/**
 * Call by the benchmark framework to load the table data
 *///from w  ww  . j av a  2s. c  o m
@Override
public void runLoop() {
    final EventObservableExceptionHandler handler = new EventObservableExceptionHandler();
    final List<Thread> threads = new ArrayList<Thread>();
    for (AbstractTableGenerator generator : this.generators.values()) {
        // if (isSubGenerator(generator)) continue;
        Thread t = new Thread(generator);
        t.setUncaughtExceptionHandler(handler);
        threads.add(t);
        // Make sure we call init first before starting any thread
        generator.init();
    } // FOR
    assert (threads.size() > 0);
    handler.addObserver(new EventObserver<Pair<Thread, Throwable>>() {
        @Override
        public void update(EventObservable<Pair<Thread, Throwable>> o, Pair<Thread, Throwable> t) {
            for (Thread thread : threads)
                thread.interrupt();
        }
    });

    // Construct a new thread to load each table
    // Fire off the threads and wait for them to complete
    // If debug is set to true, then we'll execute them serially
    try {
        for (Thread t : threads) {
            t.start();
        } // FOR
        for (Thread t : threads) {
            t.join();
        } // FOR
    } catch (InterruptedException e) {
        LOG.fatal("Unexpected error", e);
    } finally {
        if (handler.hasError()) {
            throw new RuntimeException("Error while generating table data.", handler.getError());
        }
    }

    profile.saveProfile(this);
    LOG.info("Finished generating data for all tables");
    if (debug.val)
        LOG.debug("Table Sizes:\n" + this.getTableTupleCounts());
}

From source file:com.streamsets.pipeline.stage.origin.hdfs.cluster.ClusterHDFSSourceIT.java

@Test(timeout = 30000)
public void testProduce() throws Exception {
    ClusterHdfsConfigBean conf = new ClusterHdfsConfigBean();
    conf.hdfsUri = miniDFS.getURI().toString();
    conf.hdfsDirLocations = Arrays.asList(dir.toUri().getPath());
    conf.hdfsConfigs = new HashMap<>();
    conf.hdfsKerberos = false;/*w w  w  . j a  v a 2 s  .c  om*/
    conf.hdfsConfDir = hadoopConfDir;
    conf.recursive = false;
    conf.produceSingleRecordPerMessage = false;
    conf.dataFormat = DataFormat.TEXT;
    conf.dataFormatConfig.textMaxLineLen = 1024;

    SourceRunner sourceRunner = new SourceRunner.Builder(ClusterHdfsDSource.class, createSource(conf))
            .addOutputLane("lane").setExecutionMode(ExecutionMode.CLUSTER_BATCH).setResourcesDir(resourcesDir)
            .build();

    sourceRunner.runInit();

    List<Map.Entry> list = new ArrayList<>();
    list.add(new Pair(new LongWritable(1), new Text("aaa")));
    list.add(new Pair(new LongWritable(2), new Text("bbb")));
    list.add(new Pair(new LongWritable(3), new Text("ccc")));

    Thread th = createThreadForAddingBatch(sourceRunner, list);
    try {
        StageRunner.Output output = sourceRunner.runProduce(null, 5);

        String newOffset = output.getNewOffset();
        Assert.assertEquals("3", newOffset);
        List<Record> records = output.getRecords().get("lane");
        Assert.assertEquals(3, records.size());

        for (int i = 0; i < records.size(); i++) {
            Assert.assertNotNull(records.get(i).get("/text"));
            LOG.info("Header " + records.get(i).getHeader().getSourceId());
            Assert.assertTrue(!records.get(i).get("/text").getValueAsString().isEmpty());
            Assert.assertEquals(list.get(i).getValue().toString(),
                    records.get(i).get("/text").getValueAsString());
        }

        if (sourceRunner != null) {
            sourceRunner.runDestroy();
        }
    } finally {
        th.interrupt();
    }
}

From source file:com.alfaariss.oa.authentication.password.digest.HtPasswdMD5Digest.java

private void testCommand() throws OAException {
    Runtime r = Runtime.getRuntime();
    Thread t = null;

    String[] saCommand = null;// w ww .ja va  2s. c o  m
    try {
        saCommand = resolveCommand(_sCommand, "salt", "password");

        _systemLogger.debug("Executing test command: " + resolveCommand(saCommand));
        final Process p = r.exec(saCommand);
        t = new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(3000);
                    p.destroy();
                    _systemLogger.warn("Destroyed process");
                } catch (InterruptedException e) {
                    _systemLogger.debug("Thread interrupted");
                }
            }
        });

        t.start();
        int exitCode = p.waitFor();
        if (exitCode != 0) {
            StringBuffer sbError = new StringBuffer("Configured command returned exit code '");
            sbError.append(exitCode);
            sbError.append("': ");
            sbError.append(resolveCommand(saCommand));
            _systemLogger.error(sbError.toString());
            throw new OAException(SystemErrors.ERROR_INIT);
        }
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _systemLogger.error("Could not execute command: " + resolveCommand(saCommand), e);
        throw new OAException(SystemErrors.ERROR_INIT);
    } finally {
        if (t != null)
            t.interrupt();
    }
}

From source file:com.aurel.track.admin.customize.category.report.execute.ReportBeansToLaTeXConverter.java

/**
 *
 * @param workDir//from   ww w.ja  v  a 2  s.  c om
 * @param latexFile
 */
protected int runPdflatex(File workDir, File latexFile, int nrOfRuns) {

    if (latexCmd == null) {
        return -99;
    }

    int exitValue = 0;

    try {

        String[] cmd = new String[] { latexCmd, "--halt-on-error", "-output-directory=" + workDir,
                latexFile.getAbsolutePath() };

        String texpath = new File((new File(latexCmd)).getParent()).getAbsolutePath();

        ProcessBuilder latexProcessBuilder = new ProcessBuilder(cmd);
        latexProcessBuilder.directory(workDir);
        Map<String, String> env = latexProcessBuilder.environment();
        String path = env.get("PATH");
        if (path != null) {
            path = texpath + ":" + path;
            env.put("PATH", path);
        }

        File stdoutlog = new File(workDir + File.separator + "stdout.log");
        latexProcessBuilder.redirectOutput(Redirect.appendTo(stdoutlog));

        File stderrlog = new File(workDir + File.separator + "stderr.log");
        latexProcessBuilder.redirectError(Redirect.appendTo(stderrlog));

        ProcessExecutor latexProcessExecutor = new ProcessExecutor(latexProcessBuilder);

        Thread executionThread = new Thread(latexProcessExecutor);

        long timeout = 20000;

        LOGGER.debug("Run xelatex thread started!");

        long startTime = System.currentTimeMillis();

        executionThread.start();

        int imod = 0;
        while (executionThread.isAlive()) {
            ++imod;
            if (imod % 5 == 0) {
                LOGGER.debug("Run xelatex thread is alive");
            }

            if (((System.currentTimeMillis() - startTime) > timeout) && executionThread.isAlive()) {
                executionThread.interrupt();

                LOGGER.debug("Run xelatex thread interrupted!");

                latexProcessExecutor.killProcess();
            }
            Thread.sleep(100);
        }

        LOGGER.debug("Run xelatex done!");

        exitValue = latexProcessExecutor.getExitValue();

        try {
            Thread.sleep(1000);
        } catch (Exception ex) {
            LOGGER.error(ExceptionUtils.getStackTrace(ex), ex);
        }
    } catch (Exception ex) {
        LOGGER.error(ExceptionUtils.getStackTrace(ex), ex);
    }

    return exitValue;
}