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:com.espertech.esper.dataflow.core.EPDataFlowInstanceImpl.java

public void cancel() {
    if (state == EPDataFlowState.COMPLETE || state == EPDataFlowState.CANCELLED) {
        return;//from ww  w. j  ava2s. c  o  m
    }
    if (state == EPDataFlowState.INSTANTIATED) {
        setState(EPDataFlowState.CANCELLED);
        sourceRunnables.clear();
        callOperatorClose();
        return;
    }

    // handle async start
    if (threads != null) {
        for (GraphSourceRunnable runnable : sourceRunnables) {
            runnable.shutdown();
        }
        for (Thread thread : threads) {
            if (thread.isAlive() && !thread.isInterrupted()) {
                thread.interrupt();
            }
        }
    }
    // handle run
    else {
        if (runCurrentThread != null) {
            runCurrentThread.interrupt();
        }
        runCurrentThread = null;
    }

    callOperatorClose();

    setState(EPDataFlowState.CANCELLED);
    sourceRunnables.clear();
}

From source file:org.nognog.jmatcher.server.JMatcherDaemonTest.java

/**
 * Test method for {@link org.nognog.jmatcher.JMatcherDaemon#start()}.
 * /* www .  jav a 2 s.c o m*/
 * @throws Exception
 */
@Test
public final void testStartStop() throws Exception {
    final JMatcherDaemon daemon = new JMatcherDaemon();
    try {
        daemon.start();
        fail();
    } catch (NullPointerException e) {
        // ok
    }
    daemon.init(null);
    daemon.start();
    final Thread tcpServerThread = Deencapsulation.getField(daemon, "tcpServerThread"); //$NON-NLS-1$
    final Thread udpServerThread = Deencapsulation.getField(daemon, "udpServerThread"); //$NON-NLS-1$
    assertThat(tcpServerThread.isAlive(), is(true));
    assertThat(udpServerThread.isAlive(), is(true));
    assertThat(daemon.isStopping(), is(false));
    daemon.stop();
    assertThat(daemon.isStopping(), is(true));
    Thread.sleep(3000);
    assertThat(tcpServerThread.isAlive(), is(false));
    assertThat(udpServerThread.isAlive(), is(false));
    daemon.destroy();
}

From source file:org.eclipse.smila.connectivity.framework.crawler.jdbc.test.AbstractDataEnabledJdbcCrawlerTestCase.java

/**
 * tearDown()-Implementation. Waits for the Producing-Thread of the Crawler to die in order to prevent other test
 * cases from starting (as they would causes issues when trying to re-setup the database fixture themselves) and
 * finally closes the crawler. {@inheritDoc}
 * /*from w w  w  . jav  a  2 s .  c  o  m*/
 * @see junit.framework.TestCase#tearDown()
 */
@Override
protected void tearDown() throws Exception {

    _log.debug("Waiting for Crawling Thread to terminate ...");
    final Thread thread = _crawler.getProducerThread();
    if (thread != null && thread.isAlive()) {
        thread.join();
    }
    _log.debug("Crawling Thread terminated");
    _crawler.close();
    _log.debug("Crawler closed");
    _crawler = null;
    _log.debug("Crawler object dereferenced");

}

From source file:org.ngrinder.common.util.ThreadUtilsTest.java

/**
 * Test method for//  ww w.j  av  a 2 s  .com
 * {@link ThreadUtils#stopQuietly(java.lang.Thread, java.lang.String)}.
 */
@Test
public void testStopQuietly() {
    Thread newThread = new Thread(new Runnable() {
        @Override
        public void run() {
            int i = 10;
            while (i > 0) {
                ThreadUtils.sleep(200);
            }
        }
    });
    newThread.start();
    ThreadUtils.sleep(500);
    assertThat(newThread.isAlive()).isTrue();
    ThreadUtils.stopQuietly(newThread, "STOPPED!");
    ThreadUtils.sleep(1000);
    assertThat(newThread.isAlive()).isFalse();
}

From source file:org.apache.fop.threading.FOPTestbed.java

/**
 * Starts the stress test./*ww  w.ja va2s . co  m*/
 */
public void doStressTest() {
    getLogger().info("Starting stress test...");
    long start = System.currentTimeMillis();
    this.counter = 0;

    //Initialize threads
    ThreadGroup workerGroup = new ThreadGroup("FOP workers");
    List threadList = new java.util.LinkedList();
    for (int ti = 0; ti < this.threads; ti++) {
        TaskRunner runner = new TaskRunner();
        ContainerUtil.enableLogging(runner, getLogger());
        Thread thread = new Thread(workerGroup, runner, "Worker- " + ti);
        threadList.add(thread);
    }

    //Start threads
    Iterator i = threadList.iterator();
    while (i.hasNext()) {
        ((Thread) i.next()).start();
    }

    //Wait for threads to end
    while (threadList.size() > 0) {
        Thread t = (Thread) threadList.get(0);
        if (!t.isAlive()) {
            threadList.remove(0);
            continue;
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException ie) {
            //ignore
        }
    }
    long duration = System.currentTimeMillis() - start;

    report(duration);
}

From source file:ubic.gemma.core.security.audit.AuditAdviceTest.java

@SuppressWarnings("Duplicates") // Not in this project
@Test// w w w.  jav a2 s . com
public void testAuditFindOrCreateConcurrentTorture() throws Exception {
    int numThreads = 14; // too high and we run out of connections, which is not what we're testing.
    final int numExperimentsPerThread = 5;
    final int numUpdates = 10;
    final Random random = new Random();
    final AtomicInteger c = new AtomicInteger(0);
    final AtomicBoolean failed = new AtomicBoolean(false);
    Collection<Thread> threads = new HashSet<>();
    for (int i = 0; i < numThreads; i++) {

        Thread.sleep(random.nextInt(100));

        Thread k = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int j = 0; j < numExperimentsPerThread; j++) {
                        log.debug("Starting experiment " + j);
                        ExpressionExperiment ee = ExpressionExperiment.Factory.newInstance();
                        ee.setDescription("From test");
                        ee.setShortName(RandomStringUtils.randomAlphabetic(20));
                        ee.setName(RandomStringUtils.randomAlphabetic(20));
                        ee.setTaxon(taxonService.load(1L));
                        ee = expressionExperimentService.findOrCreate(ee);

                        assertNotNull(ee.getAuditTrail());
                        assertEquals(1, ee.getAuditTrail().getEvents().size());
                        assertNotNull(ee.getCurationDetails());
                        assertNotNull(ee.getCurationDetails().getId());
                        assertNotNull(ee.getCurationDetails().getLastUpdated());
                        assertNotNull(ee.getAuditTrail().getCreationEvent().getId());

                        for (int q = 0; q < numUpdates; q++) {
                            Thread.sleep(random.nextInt(5));
                            log.debug("Update: experiment " + j);
                            expressionExperimentService.update(ee);
                            c.incrementAndGet();
                        }
                        log.debug("Done with experiment " + j);
                    }
                } catch (Exception e) {
                    failed.set(true);
                    log.error("!!!!!!!!!!!!!!!!!!!!!! FAILED: " + e.getMessage());
                    log.debug(e, e);
                    throw new RuntimeException(e);
                }
                log.debug("Thread done.");
            }
        });
        threads.add(k);

        k.start();
    }

    int waits = 0;
    int maxWaits = 20;
    int expectedEventCount = numThreads * numExperimentsPerThread * numUpdates;
    while (c.get() < expectedEventCount && !failed.get()) {
        Thread.sleep(1000);
        log.info("Waiting ...");
        if (++waits > maxWaits) {
            for (Thread t : threads) {
                if (t.isAlive())
                    t.interrupt();
            }
            fail("Multithreaded failure: timed out.");
        }
    }

    log.debug(" &&&&& DONE &&&&&");

    for (Thread thread : threads) {
        if (thread.isAlive())
            thread.interrupt();
    }

    if (failed.get() || c.get() != expectedEventCount) {
        fail("Multithreaded loading failure: check logs for failure to recover from deadlock?");
    } else {
        log.info("TORTURE TEST PASSED!");
    }

}

From source file:org.hyperic.hq.measurement.agent.server.MeasurementCommandsServer.java

private void interruptThread(Thread t) throws InterruptedException {
    if (t.isAlive()) {
        t.interrupt();//  w  w w.j  a va 2s  . co m
        t.join(THREAD_JOIN_WAIT);

        if (t.isAlive()) {
            this.log.warn(t.getName() + " did not die within the " + "timeout period.  Killing it");
            t.stop();
        }
    }
}

From source file:org.apache.hadoop.hbase.TestMetaTableLocator.java

private void startWaitAliveThenWaitItLives(final Thread t, final int ms) {
    t.start();//from w ww .  j  a  v a  2 s .  c o m
    while (!t.isAlive()) {
        // Wait
    }
    // Wait one second.
    Threads.sleep(ms);
    assertTrue("Assert " + t.getName() + " still waiting", t.isAlive());
}

From source file:org.apache.hadoop.mapreduce.v2.app.commit.CommitterEventHandler.java

private synchronized void cancelJobCommit() {
    Thread threadCommitting = jobCommitThread;
    if (threadCommitting != null && threadCommitting.isAlive()) {
        LOG.info("Cancelling commit");
        threadCommitting.interrupt();/*from  ww  w  .j  a v a 2 s . c o m*/

        // wait up to configured timeout for commit thread to finish
        long now = context.getClock().getTime();
        long timeoutTimestamp = now + commitThreadCancelTimeoutMs;
        try {
            while (jobCommitThread == threadCommitting && now > timeoutTimestamp) {
                wait(now - timeoutTimestamp);
                now = context.getClock().getTime();
            }
        } catch (InterruptedException e) {
        }
    }
}

From source file:net.bpelunit.framework.control.run.TestCaseRunner.java

private void interruptAllThreads(final List<Thread> threads) {
    fLogger.debug("Trying to interrupt all threads...");
    for (Thread t : threads) {
        if (t.isAlive()) {
            t.interrupt();/*from ww  w.  j  a  va 2  s  .  co  m*/
        }
    }
    fLogger.debug("All threads interrupted. Waiting for threads...");
}