Example usage for java.lang Thread isAlive

List of usage examples for java.lang Thread isAlive

Introduction

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

Prototype

public final native boolean isAlive();

Source Link

Document

Tests if this thread is alive.

Usage

From source file:de.fu_berlin.inf.dpp.Saros.java

/**
 * This method is called when the plug-in is stopped
 *///from w  ww. j ava2  s . c  o  m
@Override
public void stop(BundleContext context) throws Exception {

    // TODO Devise a general way to stop and dispose our components
    saveGlobalPreferences();
    saveSecurePrefs();

    if (dotMonitor != null) {
        File file = ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile();
        file = new File(file, ".metadata"); //$NON-NLS-1$
        file = new File(file, "saros-" + sarosFeatureID + ".dot"); //$NON-NLS-1$ //$NON-NLS-2$
        log.info("Saving Saros architecture diagram dot file: " + file.getAbsolutePath());
        dotMonitor.save(file);
    }

    try {
        Thread shutdownThread = ThreadUtils.runSafeAsync("ShutdownProcess", log, new Runnable() { //$NON-NLS-1$
            @Override
            public void run() {

                try {

                    sessionManager.stopSarosSession();
                    connectionHandler.disconnect();
                } finally {
                    /*
                     * Always shutdown the network to ensure a proper
                     * cleanup(currently only UPNP)
                     */

                    /*
                     * This will cause dispose() to be called on all
                     * components managed by PicoContainer which
                     * implement {@link Disposable}.
                     */
                    sarosContext.dispose();
                }
            }
        });

        shutdownThread.join(10000);
        if (shutdownThread.isAlive())
            log.error("could not shutdown Saros gracefully");

    } finally {
        super.stop(context);
    }

    isInitialized = false;
    setDefault(null);
}

From source file:org.apache.hadoop.hbase.client.TestClientOperationInterrupt.java

@Test
public void testInterrupt50Percent() throws IOException, InterruptedException {
    final AtomicInteger noEx = new AtomicInteger(0);
    final AtomicInteger badEx = new AtomicInteger(0);
    final AtomicInteger noInt = new AtomicInteger(0);
    final AtomicInteger done = new AtomicInteger(0);
    List<Thread> threads = new ArrayList<Thread>();

    final int nbThread = 100;

    for (int i = 0; i < nbThread; i++) {
        Thread t = new Thread() {
            @Override//w ww  . j a v  a  2 s .c o m
            public void run() {
                try {
                    HTable ht = new HTable(conf, tableName);
                    Result r = ht.get(new Get(row1));
                    noEx.incrementAndGet();
                } catch (IOException e) {
                    LOG.info("exception", e);
                    if (!(e instanceof InterruptedIOException) || (e instanceof SocketTimeoutException)) {
                        badEx.incrementAndGet();
                    } else {
                        if (Thread.currentThread().isInterrupted()) {
                            noInt.incrementAndGet();
                            LOG.info("The thread should NOT be with the 'interrupt' status.");
                        }
                    }
                } finally {
                    done.incrementAndGet();
                }
            }
        };
        t.setName("TestClientOperationInterrupt #" + i);
        threads.add(t);
        t.start();
    }

    for (int i = 0; i < nbThread / 2; i++) {
        threads.get(i).interrupt();
    }

    boolean stillAlive = true;
    while (stillAlive) {
        stillAlive = false;
        for (Thread t : threads) {
            if (t.isAlive()) {
                stillAlive = true;
            }
        }
        Threads.sleep(10);
    }

    Assert.assertFalse(Thread.currentThread().isInterrupted());

    Assert.assertTrue(" noEx: " + noEx.get() + ", badEx=" + badEx.get() + ", noInt=" + noInt.get(),
            noEx.get() == nbThread / 2 && badEx.get() == 0);

    // The problem here is that we need the server to free its handlers to handle all operations
    while (done.get() != nbThread) {
        Thread.sleep(1);
    }

    HTable ht = new HTable(conf, tableName);
    Result r = ht.get(new Get(row1));
    Assert.assertFalse(r.isEmpty());
}

From source file:org.deegree.tools.coverage.gridifier.RasterTreeGridifier.java

private void generateCells(RasterLevel level) throws IOException, InterruptedException {

    double metersPerPixel = level.getNativeScale();
    double cellWidth = tileWidth * metersPerPixel;
    double cellHeight = tileHeight * metersPerPixel;

    int columns = (int) Math.ceil(domainWidth / cellWidth);
    int rows = (int) Math.ceil(domainWidth / cellHeight);

    bytesPerTile = tileWidth * tileHeight * 3;
    dataSize = (long) rows * (long) columns * tileWidth * tileHeight * 3L;
    int numberOfBlobs = (int) Math.ceil((double) dataSize / (double) maxBlobSize);

    // prepare output directory
    currentOutputDir = new File(outputDir, "" + metersPerPixel);
    if (!currentOutputDir.exists()) {
        if (!currentOutputDir.mkdir()) {
            LOG.warn("Could not create directory {}.", currentOutputDir);
        }/*from  ww  w. ja  va  2s  .  c  om*/
    }

    LOG.info("\nGridifying level: " + level.getLevel() + "\n");
    LOG.info("- meters per pixel: " + metersPerPixel);
    LOG.info("- cell width (world units): " + cellWidth);
    LOG.info("- cell height (world units): " + cellHeight);
    LOG.info("- number of columns: " + columns);
    LOG.info("- number of rows: " + rows);
    LOG.info("- output directory: " + currentOutputDir);
    LOG.info("- total amount of data: " + dataSize);
    LOG.info("- number of blobs: " + numberOfBlobs);

    Envelope env = geomFactory.createEnvelope(minX, minY, minX + columns * cellWidth, minY + rows * cellHeight,
            null);
    RasterGeoReference renv = RasterGeoReference.create(originLocation, env, columns * tileWidth,
            rows * tileHeight);

    writeMetaInfoFile(new File(currentOutputDir, GridMetaInfoFile.METAINFO_FILE_NAME), renv, columns, rows);

    // start writer daemon thread
    BlobWriterThread writer = new BlobWriterThread(rows * columns);
    Thread writerThread = new Thread(writer);
    writerThread.start();

    // generate and store cell data in separate worker threads
    ExecutorService exec = Executors.newFixedThreadPool(numWorkerThreads);

    for (int row = 0; row < rows; row++) {
        for (int column = 0; column < columns; column++) {
            double cellMinX = minX + column * cellWidth;
            double cellMinY = minY + (rows - row - 1) * cellHeight;
            double cellMaxX = cellMinX + cellWidth;
            double cellMaxY = cellMinY + cellHeight;
            int cellId = row * columns + column;
            Worker worker = new Worker(cellId, cellMinX, cellMinY, cellMaxX, cellMaxY, metersPerPixel, writer);
            exec.execute(worker);
        }
    }
    exec.shutdown();

    while (writerThread.isAlive()) {
        Thread.sleep(1000);
    }
}

From source file:org.sakaiproject.status.StatusServlet.java

protected void reportThreadDetails(HttpServletResponse response) throws Exception {
    PrintWriter pw = response.getWriter();

    for (Thread thread : findAllThreads()) {
        if (thread != null) {
            String threadLocation = "";
            try {
                StackTraceElement ste = thread.getStackTrace()[0];
                StackTraceElement ste2 = thread.getStackTrace()[1];
                threadLocation = ste.getClassName() + "." + ste.getMethodName() + "()," + ste.getFileName()
                        + ":" + ste.getLineNumber() + "," + ste2.getClassName() + "." + ste2.getMethodName()
                        + "()," + ste2.getFileName() + ":" + ste2.getLineNumber();
            } catch (Exception e) {
                threadLocation = "?,?,?,?";
            }/*from  ww w.j av  a  2 s .c  o  m*/
            pw.print(thread.getThreadGroup().getName() + "," + thread.getId() + "," + thread.getName() + ","
                    + thread.getPriority() + "," + thread.getState().name() + ","
                    + (thread.isAlive() ? "" : "notalive") + "," + (thread.isDaemon() ? "daemon" : "") + ","
                    + (thread.isInterrupted() ? "interrupted" : "") + "," + threadLocation + "\n");
        }
    }
}

From source file:org.apache.bookkeeper.replication.TestLedgerUnderreplicationManager.java

/**
 * Test that as the hierarchy gets cleaned up, it doesn't interfere
 * with the marking of other ledgers as underreplicated
 *///from   w ww.  j  a va  2s.  com
@Test(timeout = 90000)
public void testHierarchyCleanupInterference() throws Exception {
    final LedgerUnderreplicationManager replicaMgr1 = lmf1.newLedgerUnderreplicationManager();
    final LedgerUnderreplicationManager replicaMgr2 = lmf2.newLedgerUnderreplicationManager();

    final int iterations = 100;
    final AtomicBoolean threadFailed = new AtomicBoolean(false);
    Thread markUnder = new Thread() {
        public void run() {
            long l = 1;
            try {
                for (int i = 0; i < iterations; i++) {
                    replicaMgr1.markLedgerUnderreplicated(l, "localhost:3181");
                    l += 10000;
                }
            } catch (Exception e) {
                LOG.error("markUnder Thread failed with exception", e);
                threadFailed.set(true);
                return;
            }
        }
    };
    final AtomicInteger processed = new AtomicInteger(0);
    Thread markRepl = new Thread() {
        public void run() {
            try {
                for (int i = 0; i < iterations; i++) {
                    long l = replicaMgr2.getLedgerToRereplicate();
                    replicaMgr2.markLedgerReplicated(l);
                    processed.incrementAndGet();
                }
            } catch (Exception e) {
                LOG.error("markRepl Thread failed with exception", e);
                threadFailed.set(true);
                return;
            }
        }
    };
    markRepl.setDaemon(true);
    markUnder.setDaemon(true);

    markRepl.start();
    markUnder.start();
    markUnder.join();
    assertFalse("Thread failed to complete", threadFailed.get());

    int lastProcessed = 0;
    while (true) {
        markRepl.join(10000);
        if (!markRepl.isAlive()) {
            break;
        }
        assertFalse("markRepl thread not progressing", lastProcessed == processed.get());
    }
    assertFalse("Thread failed to complete", threadFailed.get());

    List<String> children = zkc1.getChildren(urLedgerPath, false);
    for (String s : children) {
        LOG.info("s: {}", s);
    }
    assertEquals("All hierarchies should be cleaned up", 0, children.size());
}

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

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

    try {/*from   w ww  . j ava  2  s.com*/
        // Inflate 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);

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

        final Thread inflateToDirectoryThread = new Thread(() -> {
            try {
                // Inflate Fast file to a temporary directory
                inflateFromFile(fileIn, tmpOutputDirectory);

                // Inflate Directory to a zip file
                inflateFromDirectory(tmpOutputDirectory, fileOut);

                // Clean up IO
                close();
                System.gc();
                Thread.sleep(100);

                // Clean up temporary directory
                FileUtils.deleteDirectory(tmpOutputDirectory);

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

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

                // Clean up IO
                close();
                System.gc();
                Thread.sleep(100);

                synchronized (this) {
                    while (inflateToDirectoryThread.isAlive())
                        this.wait();
                }

            } catch (final IOException | InterruptedException e) {
                e.printStackTrace();
            } finally {
                // Clean up temporary directory
                FileUtils.deleteQuietly(tmpOutputDirectory);
                // Clean up INCOMPLETE output file
                FileUtils.deleteQuietly(fileOut);
                System.out.println();
            }

        }, "Inflation_Cleaning_Thread");

        cleanHookAtomic.set(cleanHook);

        Runtime.getRuntime().addShutdownHook(cleanHook);

        inflateToDirectoryThread.start();
        inflateToDirectoryThread.join();

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

    return fileOut;
}

From source file:com.datatorrent.stram.engine.StreamingContainer.java

private void processNodeRequests(boolean flagInvalid) {
    for (StramToNodeRequest req : nodeRequests) {
        if (req.isDeleted()) {
            continue;
        }/*w w w  . ja  va 2 s.co m*/
        if (req instanceof StramToNodeChangeLoggersRequest) {
            handleChangeLoggersRequest((StramToNodeChangeLoggersRequest) req);
            continue;
        }

        Node<?> node = nodes.get(req.getOperatorId());
        if (node == null) {
            logger.warn("Node for operator {} is not found, probably not deployed yet", req.getOperatorId());
            continue;
        }

        Thread thread = node.context.getThread();
        if (thread == null || !thread.isAlive()) {
            if (flagInvalid) {
                logger.warn("Received request with invalid operator id {} ({})", req.getOperatorId(), req);
                req.setDeleted(true);
            }
        } else {
            logger.debug("request received: {}", req);
            OperatorRequest requestExecutor = requestFactory.getRequestExecutor(nodes.get(req.operatorId), req);
            if (requestExecutor != null) {
                node.context.request(requestExecutor);
            } else {
                logger.warn("No executor identified for the request {}", req);
            }
            req.setDeleted(true);
        }
    }
}

From source file:com.datatorrent.stram.engine.StreamingContainer.java

public synchronized void deactivate() {
    ArrayList<Thread> activeThreads = new ArrayList<Thread>();
    ArrayList<Integer> activeOperators = new ArrayList<Integer>();

    for (Map.Entry<Integer, Node<?>> e : nodes.entrySet()) {
        Thread t = e.getValue().context.getThread();
        if (t == null || !t.isAlive()) {
            disconnectNode(e.getKey());// ww w .jav  a 2  s .c om
        } else {
            activeThreads.add(t);
            activeOperators.add(e.getKey());
            e.getValue().shutdown();
        }
    }

    try {
        Iterator<Integer> iterator = activeOperators.iterator();
        for (Thread t : activeThreads) {
            t.join(1000);
            if (!t.getState().equals(State.TERMINATED)) {
                t.interrupt();
            }
            disconnectNode(iterator.next());
        }
    } catch (InterruptedException ex) {
        logger.warn("Aborting wait for operators to get deactivated!", ex);
    }

    for (WindowGenerator wg : activeGenerators.keySet()) {
        wg.deactivate();
    }
    activeGenerators.clear();

    for (Stream stream : activeStreams.keySet()) {
        stream.deactivate();
    }
    activeStreams.clear();
}

From source file:com.datatorrent.stram.engine.StreamingContainer.java

private synchronized void undeploy(List<Integer> nodeList) {
    /**/*from   w ww.ja v  a  2 s .c o m*/
     * make sure that all the operators which we are asked to undeploy are in this container.
     */
    HashMap<Integer, Node<?>> toUndeploy = new HashMap<Integer, Node<?>>();
    for (Integer operatorId : nodeList) {
        Node<?> node = nodes.get(operatorId);
        if (node == null) {
            throw new IllegalArgumentException("Node " + operatorId + " is not hosted in this container!");
        } else if (toUndeploy.containsKey(operatorId)) {
            throw new IllegalArgumentException(
                    "Node " + operatorId + " is requested to be undeployed more than once");
        } else {
            toUndeploy.put(operatorId, node);
        }
    }

    ArrayList<Thread> joinList = new ArrayList<Thread>();
    ArrayList<Integer> discoList = new ArrayList<Integer>();
    for (Integer operatorId : nodeList) {
        Thread t = nodes.get(operatorId).context.getThread();
        if (t == null || !t.isAlive()) {
            disconnectNode(operatorId);
        } else {
            joinList.add(t);
            discoList.add(operatorId);
            nodes.get(operatorId).shutdown();
        }
    }

    try {
        Iterator<Integer> iterator = discoList.iterator();
        for (Thread t : joinList) {
            t.join(1000);
            if (!t.getState().equals(State.TERMINATED)) {
                t.interrupt();
            }
            disconnectNode(iterator.next());
        }
        logger.info("Undeploy complete.");
    } catch (InterruptedException ex) {
        logger.warn("Aborting wait for operators to get deactivated!", ex);
    }

    for (Integer operatorId : nodeList) {
        nodes.remove(operatorId);
    }
}

From source file:com.gargoylesoftware.htmlunit.javascript.JavaScriptEngineTest.java

/**
 * @throws Exception if the test fails/*from  w  w w .j  a v  a  2  s . com*/
 */
@Test
public void timeout() throws Exception {
    final WebClient client = getWebClient();
    final long timeout = 2000;
    final long oldTimeout = client.getJavaScriptTimeout();
    client.setJavaScriptTimeout(timeout);

    try {
        client.setThrowExceptionOnScriptError(false);

        final String content = "<html><body><script>while(1) {}</script></body></html>";
        final MockWebConnection webConnection = new MockWebConnection();
        webConnection.setDefaultResponse(content);
        client.setWebConnection(webConnection);

        final Exception[] exceptions = { null };
        final Thread runner = new Thread() {
            @Override
            public void run() {
                try {
                    client.getPage(URL_FIRST);
                } catch (final Exception e) {
                    exceptions[0] = e;
                }
            }
        };

        runner.start();

        runner.join(timeout * 2);
        if (runner.isAlive()) {
            runner.interrupt();
            fail("Script was still running after timeout");
        }
        assertNull(exceptions[0]);
    } finally {
        client.setJavaScriptTimeout(oldTimeout);
    }
}