Example usage for java.lang Thread getState

List of usage examples for java.lang Thread getState

Introduction

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

Prototype

public State getState() 

Source Link

Document

Returns the state of this thread.

Usage

From source file:edu.uci.ics.crawler4j.crawler.CrawlController.java

/**
 * Start./*from  w  w  w  .  jav  a2 s  .c o  m*/
 * 
 * @param <T>
 *            the generic type
 * @param _c
 *            the _c
 * @param numberOfCrawlers
 *            the number of crawlers
 */
public <T extends WebCrawler> void start(Class<T> _c, int numberOfCrawlers) {
    try {

        crawlersLocalData.clear();
        threads = new ArrayList<Thread>();
        List<T> crawlers = new ArrayList<T>();
        int numberofCrawlers = numberOfCrawlers;
        for (int i = 1; i <= numberofCrawlers; i++) {
            T crawler = _c.newInstance();
            Thread thread = new Thread(crawler, "Crawler " + i);
            logger.info("Thread state1 = " + thread.getState().toString());

            crawler.setThread(thread);
            crawler.setMyId(i);
            crawler.setMyController(this);
            thread.start();
            logger.info("Thread state2 = " + thread.getState().toString());
            crawlers.add(crawler);
            threads.add(thread);
            logger.info("Crawler " + i + " started.");
        }

        while (true) {
            sleep(DELAY);
            boolean someoneIsWorking = false;

            for (int i = 0; i < threads.size(); i++) {
                Thread thread = threads.get(i);
                if (!thread.isAlive()) {
                    recreateThread(_c, crawlers, i);
                } else if (thread.getState() == State.RUNNABLE) {
                    someoneIsWorking = true;
                    logger.info("Thread " + i + " was RUNNABLE.");
                } else if (thread.getState() == State.WAITING) {
                    logger.info("Thread " + i + " was WAITING.");
                    // thread.interrupt();
                    // thread.join();
                } else {
                    logger.info("Thread " + i + thread.getState().toString());
                    // recreateThread(_c, crawlers, i);
                }
            }

            if (!someoneIsWorking) {
                // Make sure again that none of the threads are alive.
                logger.info("It looks like no thread is working, waiting for 20 second to make sure...");
                sleep(DELAY);

                if (!isAnyThreadWorking()) {
                    long queueLength = Frontier.getQueueLength();
                    if (queueLength > 0) {
                        continue;
                    }
                    logger.info(
                            "No thread is working and no more URLs are in queue waiting for another 20 second to make sure...");
                    sleep(DELAY);
                    queueLength = Frontier.getQueueLength();
                    if (queueLength > 0) {
                        continue;
                    }
                    logger.info("All of the crawlers are stopped. Finishing the process...");
                    for (T crawler : crawlers) {
                        crawler.onBeforeExit();
                        crawlersLocalData.add(crawler.getMyLocalData());
                    }

                    // At this step, frontier notifies the threads that were waiting for new URLs and they should
                    // stop
                    // We will wait a few seconds for them and then return.
                    Frontier.finish();
                    logger.info("Waiting for 1 second before final clean up...");
                    sleep(DELAY);

                    try {
                        Frontier.close();
                        env.close();

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    /*
                     * for (int i = 0; i < threads.size(); i++) { Thread thread = threads.get(i);
                     * logger.info("Thread state = " + thread.getState().toString()); if (thread.isAlive()) {
                     * logger.info("Wait for live thread to die"); thread.join(); }
                     * 
                     * }
                     */
                    // PageFetcher.stopConnectionMonitorThread();
                    return;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.umn.cs.spatialHadoop.core.GridRecordWriter.java

/**
 * Close the whole writer. Finalize all cell files and concatenate them
 * into the output file.//  w  ww  .ja va 2s  .co  m
 */
public synchronized void close(Progressable progressable) throws IOException {
    // Close all output files
    for (int cellIndex = 0; cellIndex < intermediateCellStreams.length; cellIndex++) {
        if (intermediateCellStreams[cellIndex] != null) {
            closeCell(cellIndex);
        }
        // Indicate progress. Useful if closing a single cell takes a long time
        if (progressable != null)
            progressable.progress();
    }
    LOG.info("Closing record writer with " + closingThreads.size() + " remaining threads");

    while (!closingThreads.isEmpty()) {
        try {
            Thread t = closingThreads.get(0);
            switch (t.getState()) {
            case NEW:
                t.start();
                break;
            case TERMINATED:
                closingThreads.remove(0);
                break;
            default:
                // Use limited time join to indicate progress frequently
                t.join(10000);
            }
            // Indicate progress. Useful if closing a single cell takes a long time
            if (progressable != null)
                progressable.progress();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    if (masterFile != null)
        masterFile.close();
}

From source file:com.datatorrent.lib.appdata.query.SimpleDoneQueryQueueManagerTest.java

private Thread testBlockingNoStop(SimpleDoneQueueManager<Query, Void> sdqqm,
        ExceptionSaverExceptionHandler eseh) throws InterruptedException {
    Thread thread = new Thread(new BlockedThread<>(sdqqm));
    thread.setUncaughtExceptionHandler(eseh);
    thread.start();/*w  ww .j  a v a  2  s .  c  o m*/
    Thread.sleep(100);

    Assert.assertEquals(Thread.State.WAITING, thread.getState());

    return thread;
}

From source file:edu.uci.ics.crawler4j.crawler.CrawlController.java

/**
 * Recreate thread./* w w w . j  a  va  2  s  .c om*/
 * 
 * @param <T>
 *            the generic type
 * @param _c
 *            the _c
 * @param crawlers
 *            the crawlers
 * @param i
 *            the i
 * @throws InstantiationException
 *             the instantiation exception
 * @throws IllegalAccessException
 *             the illegal access exception
 */
private <T extends WebCrawler> void recreateThread(Class<T> _c, List<T> crawlers, int i)
        throws InstantiationException, IllegalAccessException {
    Thread thread;
    logger.info("Thread " + i + " was dead, I'll recreate it.");
    T crawler = _c.newInstance();
    thread = new Thread(crawler, "Crawler " + (i + 1));
    logger.info("Thread state3 = " + thread.getState().toString());
    threads.remove(i);
    threads.add(i, thread);
    crawler.setThread(thread);
    crawler.setMyId(i + 1);
    crawler.setMyController(this);
    thread.start();
    logger.info("Thread state4 = " + thread.getState().toString());
    crawlers.remove(i);
    crawlers.add(i, crawler);
}

From source file:com.datatorrent.lib.appdata.query.SimpleDoneQueryQueueManagerTest.java

@SuppressWarnings({ "deprecation", "CallToThreadStopSuspendOrResumeManager" })
private void testBlocking(SimpleDoneQueueManager<Query, Void> sdqqm) throws InterruptedException {
    Thread thread = new Thread(new BlockedThread<Query, Void, MutableBoolean>(sdqqm));
    //thread.setUncaughtExceptionHandler(new RethrowExceptionHandler(Thread.currentThread()));
    thread.start();// w w  w.j  a  v  a 2s .c  om
    Thread.sleep(100);

    Assert.assertEquals(Thread.State.WAITING, thread.getState());

    thread.stop();
}

From source file:io.cloudslang.worker.management.services.OutboundBufferTest.java

/**
 * Checks that the buffer will block when having no messages and continues when the first message arrives
 *
 * @throws InterruptedException//  ww  w .ja  v a2s. c o m
 */
@Test
public void testConsumerBlocking() throws InterruptedException {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            buffer.drain();
        }
    });
    thread.start();

    // draining the buffer should block since it is empty
    waitForThreadStateToBe(thread, Thread.State.WAITING);
    Assert.assertEquals("reading thread should be in a waiting state when inserting to full buffer",
            Thread.State.WAITING, thread.getState());

    // insert 2 new messages
    Message[] messages = new Message[] { new DummyMsg1(), new DummyMsg2() };
    buffer.put(messages);

    // thread should be released now
    waitForThreadStateToBe(thread, Thread.State.TERMINATED);
    Assert.assertEquals("reading thread should be in a terminated after a message was inserted to the buffer",
            Thread.State.TERMINATED, thread.getState());

    thread.join();
    verify(dispatcherService).dispatch(
            (List<? extends Serializable>) argThat(new MessagesSizeMatcher(Arrays.asList(messages))),
            anyString(), anyString(), anyString());
}

From source file:io.cloudslang.worker.management.services.OutboundBufferTest.java

/**
 * checks that when inserting messages to a full buffer,
 * the inserting thread will block until the buffer is emptied
 *
 * @throws InterruptedException/*from   ww w.  j a  v  a 2 s.c o  m*/
 */
@Test
public void testProducerBlocking() throws InterruptedException {
    // buffer capacity is 10, put messages in it until it is full
    while (buffer.getWeight() < MAX_BUFFER_WEIGHT) {
        buffer.put(new DummyMsg1());
    }

    // the next insert to buffer will block because it's full, do it on a different thread
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                buffer.put(new DummyMsg1());
            } catch (InterruptedException e) {
                //ignore
            }
        }
    });
    thread.start();

    // wait for that thread to block
    waitForThreadStateToBe(thread, Thread.State.WAITING);
    Assert.assertEquals("inserting thread should be in a waiting state when inserting to full buffer",
            Thread.State.WAITING, thread.getState());

    // drain the buffer -> will send the first 10 messages and release the blocking thread
    buffer.drain();
    waitForThreadStateToBe(thread, Thread.State.TERMINATED);
    Assert.assertEquals("inserting thread should be in a terminated state after inserting to buffer",
            Thread.State.TERMINATED, thread.getState());
    thread.join();
}

From source file:com.intuit.tank.harness.APITestHarness.java

/**
 * check the agent threads if simulation time has been met.
 *///from w  ww . j  a va2  s  . c  om
public void checkAgentThreads() {
    int activeCount = threadGroup.activeCount();
    Thread[] threads = new Thread[activeCount];
    threadGroup.enumerate(threads);
    int activeThreads = 0;
    for (Thread t : threads) {
        if (t != null) {
            if (t.getState() == Thread.State.TIMED_WAITING || t.getState() == Thread.State.WAITING) {
                activeThreads++;
            }
        }
    }
    LOG.info(LogUtil.getLogMessage("Have " + activeThreads + " of " + activeCount
            + " active Threads in thread group " + threadGroup.getName(), LogEventType.System));
    if (agentRunData.getSimulationTime() != 0 && hasMetSimulationTime() && doneSignal.getCount() != 0) {
        boolean exceededTimeLimit = System.currentTimeMillis() > getMaxSimulationEndTimeMillis();
        if (exceededTimeLimit) {
            LOG.info(LogUtil.getLogMessage("Max simulation time has been met and there are "
                    + doneSignal.getCount() + " threads not reporting done."));
            for (Thread t : sessionThreads) {
                if (t.isAlive()) {
                    if (exceededTimeLimit) {
                        LOG.warn(
                                LogUtil.getLogMessage(
                                        "thread " + t.getName() + '-' + t.getId()
                                                + " is still running with a State of " + t.getState().name(),
                                        LogEventType.System));
                        t.interrupt();
                        doneSignal.countDown();
                    }
                }
            }
        }
    }
}

From source file:org.apache.hadoop.hive.metastore.MetaStoreUtils.java

private static String getAllThreadStacksAsString() {
    Map<Thread, StackTraceElement[]> threadStacks = Thread.getAllStackTraces();
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<Thread, StackTraceElement[]> entry : threadStacks.entrySet()) {
        Thread t = entry.getKey();
        sb.append(System.lineSeparator());
        sb.append("Name: ").append(t.getName()).append(" State: ").append(t.getState());
        addStackString(entry.getValue(), sb);
    }/*from  www. j  a  va2  s  .c om*/
    return sb.toString();
}