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:org.noroomattheinn.visibletesla.AppContext.java

public void shutDown() {
    shuttingDown.set(true);/*from  w ww. jav  a2s .c o  m*/
    int nActive;
    do {
        nActive = 0;
        for (Thread t : threads) {
            Thread.State state = t.getState();
            switch (state) {
            case NEW:
            case RUNNABLE:
                nActive++;
                break;

            case TERMINATED:
                break;

            case BLOCKED:
            case TIMED_WAITING:
            case WAITING:
                nActive++;
                t.interrupt();
                // Should this sleep for a very short period?
                break;

            default:
                break;
            }
        }
    } while (nActive > 0);
}

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

private void waitForThreadStateToBe(Thread thread, Thread.State state) throws InterruptedException {
    int waitCount = 0;
    while (!thread.getState().equals(state) && waitCount <= 20) {
        Thread.sleep(50);/*from  ww  w .java  2  s. c om*/
        waitCount++;
    }
}

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

/**
 * Checks if is any thread working./*from   w  w w .j a v a2 s.  c o  m*/
 * 
 * @return true, if is any thread working
 */
private boolean isAnyThreadWorking() {
    boolean someoneIsWorking = false;
    for (int i = 0; i < threads.size(); i++) {
        Thread thread = threads.get(i);
        if (thread.isAlive() && thread.getState() == State.RUNNABLE) {
            someoneIsWorking = true;
        }
    }
    return someoneIsWorking;
}

From source file:com.ricemap.spateDB.core.GridRecordWriter.java

/**
 * Close the whole writer. Finalize all cell files and concatenate them
 * into the output file.//  w ww  .  j a  v a  2 s . c o 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();
    }

    while (!closingThreads.isEmpty()) {
        try {
            Thread t = closingThreads.get(0);
            switch (t.getState()) {
            case NEW:
                t.start();
                break;
            case TERMINATED:
                closingThreads.remove(0);
                break;
            default:
                t.join(10000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

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

From source file:org.jasig.portal.portlet.rendering.worker.PortletExecutionWorker.java

@Override
public V get(long timeout) throws Exception {
    if (this.future == null) {
        throw new IllegalStateException("submit() must be called before get(long) can be called");
    }//w  w w  .  j  a va 2  s . com

    this.retrieved = true;

    try {
        final long startTime = this.waitForStart(timeout);
        final long waitTime = Math.max(0, timeout - (System.currentTimeMillis() - startTime));
        return this.future.get(waitTime, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        this.logger.warn("Execution interrupted on portlet window " + this.portletWindowId, e);
        throw e;
    } catch (ExecutionException e) {
        this.logger.warn("Execution failed on portlet window " + this.portletWindowId, e);
        throw e;
    } catch (TimeoutException e) {
        final StringBuilder errorBuilder = new StringBuilder("Execution timed out on portlet window ");
        errorBuilder.append(this.portletWindowId);

        final Thread localWorkerThread = workerThread;
        if (localWorkerThread != null) {
            final State state = localWorkerThread.getState();
            final StackTraceElement[] stackTrace = localWorkerThread.getStackTrace();

            errorBuilder.append("\n\tPortlet Thread State: ").append(state).append("\n");
            errorBuilder.append("\tPortlet Thread Stack Trace: \n");

            for (final StackTraceElement stackTraceElement : stackTrace) {
                errorBuilder.append("\t\tat ").append(stackTraceElement).append("\n");
            }

            errorBuilder.append("Portal Stack Trace:");
        }

        this.logger.warn(errorBuilder, e);

        throw e;
    }
}

From source file:org.apparatus_templi.Coordinator.java

private static void stopDrivers() {
    Log.w(TAG, "Restarting all drivers");
    Log.d(TAG, "removing all event watchers");
    eventWatchers.clear();//from  w ww. j a  v a2s.co m

    for (String driverName : loadedDrivers.keySet()) {
        Driver d = loadedDrivers.get(driverName);
        Log.d(TAG, "terminating driver " + d.getName());
        d.terminate();

        // only wake sleeping drivers, not TERMINATED ones
        wakeDriver(d.getName(), false, false);
        // loadedDrivers.remove(driverName);
    }

    // Block for a few seconds to allow all drivers to finish their
    // termination procedure. Since the drivers may call methods in this
    // thread we need to do a non-blocking wait instead of using a call to
    // Thread.sleep()
    long sleepTime = System.currentTimeMillis() + (1000 * 5);
    while (sleepTime > System.currentTimeMillis()) {
    }

    int tryCount = 0;
    while (!driverThreads.isEmpty()) {
        for (Driver d : driverThreads.keySet()) {
            Thread t = driverThreads.get(d);
            if (t.getState() == Thread.State.TERMINATED) {
                Log.d(TAG, "driver " + d.getName() + " terminated");
                driverThreads.remove(d);
            } else {
                // we don't want to block forever waiting on a non-responsive driver thread
                if (tryCount == 20) {
                    Log.w(TAG, "driver " + d.getName() + " non-responsive, interrupting thread.");
                    t.interrupt();
                    // t.notifyAll();
                }

                // Something is seriously wrong if the driver has not stopped by now. We should
                // probably notify the user that the service is experiencing problems and should
                // be restarted
                if (tryCount == 30) {
                    Log.e(TAG, "driver " + d.getName() + " still non-responsive, force stopping");
                    t.stop();
                }

                Log.d(TAG, "waiting on driver " + d.getName() + " to terminate (state: "
                        + t.getState().toString() + ")");
                d.terminate();
                wakeDriver(d.getName(), false, false);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        tryCount++;
    }
    scheduledWakeUps.clear();
    loadedDrivers.clear();

    assert driverThreads.isEmpty();
    assert loadedDrivers.isEmpty();
    Log.w(TAG, "all drivers stopped");
}

From source file:org.opencb.opencga.storage.core.variant.VariantStorageBaseTest.java

public void printActiveThreads() {
    System.out.println("=========================================");
    System.out.println("Thread.activeCount() = " + Thread.activeCount());

    Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces();
    Set<String> groups = allStackTraces.keySet().stream()
            .filter(t -> t.getThreadGroup() == null || !t.getThreadGroup().getName().equals("system"))
            .map(t -> String.valueOf(t.getThreadGroup())).collect(Collectors.toSet());

    for (String group : groups) {
        System.out.println("group = " + group);
        for (Map.Entry<Thread, StackTraceElement[]> entry : allStackTraces.entrySet()) {
            Thread thread = entry.getKey();
            if (String.valueOf(thread.getThreadGroup()).equals(group)) {
                System.out.println("\t[" + thread.getId() + "] " + thread.toString() + ":" + thread.getState());
            }//  w w  w. j  av a2s.  c  o m
        }
    }
    System.out.println("=========================================");
}

From source file:eu.stratosphere.nephele.checkpointing.ReplayTask.java

/**
 * {@inheritDoc}/*  w w w  .  j  a v a 2 s  . co  m*/
 */
@Override
public boolean isTerminated() {

    if (this.encapsulatedTask != null) {
        if (this.encapsulatedTask.isTerminated()) {

            if (this.encapsulatedExecutionState != ExecutionState.FINISHED
                    && this.encapsulatedExecutionState != ExecutionState.CANCELED
                    && this.encapsulatedExecutionState != ExecutionState.FAILED) {

                return true;
            }
        }
    }

    final Thread executingThread = this.environment.getExecutingThread();
    if (executingThread.getState() == Thread.State.TERMINATED) {

        if (this.replayTaskExecutionState != ExecutionState.FINISHED
                && this.replayTaskExecutionState != ExecutionState.CANCELED
                && this.replayTaskExecutionState != ExecutionState.FAILED) {

            return true;
        }
    }

    return false;
}

From source file:org.apparatus_templi.Coordinator.java

/**
 ** Wake the given driver, optionally creating a new thread for the {@link Driver}, optionally
 * automatically calling start() on the new thread.
 * //from   ww w.j a  va 2s . co  m
 * @param driverName
 *            the name of the {@link Driver} to wake.
 * @param autoStart
 *            if true the driver's thread will be automatically started after creation
 * @param wakeTerminated
 *            if true then drivers whose thread state is TERMINATED will have a new thread
 *            assigned.
 * @return a reference to the woken Driver.
 */
private static synchronized Driver wakeDriver(String driverName, boolean autoStart, boolean wakeTerminated) {
    assert driverName != null : "given driver name can not be null";
    // NOTE using containsKey() does not always work for String values (different hash code may
    // be generated)
    assert loadedDrivers.get(driverName) != null : "driver " + driverName
            + " must exist within the loaded drivers table";

    Driver d = loadedDrivers.get(driverName);
    Thread t = driverThreads.get(d);
    assert d != null && t != null : "the driver and its thread must be valid objects";

    if (t.getState() == Thread.State.TERMINATED && wakeTerminated) {
        Log.d(TAG, "restarting driver '" + d.getName() + "' of class '" + d.getClass() + "' of type '"
                + d.getClass().getName() + "'");
        scheduledWakeUps.remove(d);
        driverThreads.remove(d);
        Thread newThread = new Thread(d);
        newThread.setPriority(Thread.MIN_PRIORITY);
        driverThreads.put(d, newThread);
        if (autoStart) {
            newThread.start();
        }
    } else {
        try {
            scheduledWakeUps.remove(d);
            d.wake();
            Log.d(TAG, "waking driver " + driverName);
        } catch (Exception e) {
            Log.d(TAG, "could not wake driver " + driverName);
        }
    }
    return d;
}

From source file:org.dataconservancy.access.connector.MultiThreadedConnectorTest.java

/**
 * Making a request beyond the connection limit without closing any streams should block.
 *
 * @throws java.io.IOException//ww  w.java  2  s .co m
 * @throws DcsClientFault
 * @throws org.xml.sax.SAXException
 * @throws InterruptedException
 */
@Test
public void testMultipleConnectionReuseScenarioBlocksOk()
        throws IOException, DcsClientFault, SAXException, InterruptedException {
    assertTrue(new File(entitiesDir, "test1.xml").exists());
    assertTrue(config.getMaxOpenConn() > 1);
    final String entityId = config.getAccessHttpUrl() + "/entity/test1";

    // Create request threads, purposefully creating one more request thread then there are maximum allowed connections
    final List<Thread> requestThreads = createTestRequestThreads(config.getMaxOpenConn() + 1, entityId);

    // Start the threads.
    for (Thread t : requestThreads) {
        t.start();
    }

    // Sleep for 3 seconds, ensuring the threads that are able to terminate, do
    Thread.sleep(3000);

    // Verify the state of the threads.  Exactly one thread should block in the WAIT state.
    boolean foundWait = false;
    for (int i = 0; i < requestThreads.size(); i++) {
        final Thread t = requestThreads.get(i);
        if (t.getState() != Thread.State.WAITING) {
            assertEquals(Thread.State.TERMINATED, t.getState());
        } else {
            assertFalse("Multiple request threads found in the WAIT state.  Only 1 expected.", foundWait);
            assertEquals(Thread.State.WAITING, t.getState());
            foundWait = true;
        }
    }
    assertTrue("Exactly one request thread should have been found in the WAIT state", foundWait);
}