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:gridool.util.net.InterruptableInputStream.java

private int internalRead(final byte[] b, final int off, final int len) throws IOException {
    boolean ntraced = true;
    while (true) {
        try {/* w  w  w  . j  a  v  a 2 s  .c o m*/
            final int n = is.read(b, off, len);
            return n;
        } catch (SocketTimeoutException e) {
            if (Thread.interrupted()) {
                throw e;
            } else {
                Thread thread = Thread.currentThread();
                if (!thread.isDaemon()) {
                    State state = thread.getState();
                    switch (state) {
                    case BLOCKED:
                    case WAITING:
                        if (LOG.isWarnEnabled()) {
                            LOG.warn("thread (" + thread.getName() + "timeout: " + thread.getState(), e);
                        }
                        throw e;
                    default:
                        if (LOG.isTraceEnabled() && ntraced) {
                            ntraced = false;
                            LOG.trace("thread (" + thread.getName() + ") timeout: " + thread.getState());
                        }
                        break;
                    }
                }
            }
        }
    }
}

From source file:org.noroomattheinn.utils.ThreadManager.java

public synchronized void shutDown() {
    shuttingDown = true;/*from www . j a  v a  2s  .  co  m*/
    timer.cancel();
    for (Stoppable s : stopList) {
        s.stop();
    }

    int nActive;
    do {
        nActive = 0;
        logger.finest("Iterating through terminate loop");
        for (Thread t : threads) {
            Thread.State state = t.getState();
            switch (state) {
            case NEW:
            case RUNNABLE:
                nActive++;
                logger.finest("Active thread: " + t.getName());
                break;

            case TERMINATED:
                logger.finest("Terminated thread: " + t.getName());
                break;

            case BLOCKED:
            case TIMED_WAITING:
            case WAITING:
                logger.finest("About to interrupt thread: " + t.getName());
                nActive++;
                t.interrupt();
                Utils.yieldFor(100);
                break;

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

From source file:com.dianping.dpsf.jmx.DpsfRequestorMonitor.java

private int getThreadCount(State state) {
    ThreadGroup threadGroup = clientManager.getClientResponseThreadPool().getFactory().getGroup();
    Thread[] threads = new Thread[threadGroup.activeCount()];
    threadGroup.enumerate(threads, false);
    int threadCount = 0;
    for (Thread t : threads) {
        if (state == t.getState()) {
            threadCount++;/*from  ww  w . j a v  a  2s.  co  m*/
        }
    }
    return threadCount;
}

From source file:de.slub.elasticsearch.river.fedora.FedoraRiver.java

private void safeStart(Thread thread) {
    if (thread != null && thread.getState().equals(Thread.State.NEW)) {
        thread.start();/*from   w  w  w .  j av  a 2  s . c om*/
        logger.info("Started thread: [{}] {}", thread.getId(), thread.getName());
    }
}

From source file:com.dianping.dpsf.jmx.DpsfResponsorMonitor.java

private int getThreadCount(RequestProcessor requestProcessor, State state) {
    ThreadGroup threadGroup = requestProcessor.getThreadPool().getFactory().getGroup();
    Thread[] threads = new Thread[threadGroup.activeCount()];
    threadGroup.enumerate(threads, false);
    int threadCount = 0;
    for (Thread t : threads) {
        if (state == t.getState()) {
            threadCount++;//from   w  ww . ja  va2 s. c  o  m
        }
    }
    return threadCount;
}

From source file:com.dianping.dpsf.jmx.DpsfResponsorMonitor.java

private String getThreadStackTraces(RequestProcessor requestProcessor, State state, int threadCount) {
    ThreadGroup threadGroup = requestProcessor.getThreadPool().getFactory().getGroup();
    Thread[] threads = new Thread[threadGroup.activeCount()];
    threadGroup.enumerate(threads, false);
    StringBuilder builder = new StringBuilder();
    int count = 0;
    if (threads != null && threads.length > 0 && threadCount > 0) {
        for (Thread thread : threads) {
            if (state == thread.getState()) {
                count++;//from w w w . j  a  v a2  s .  c  o  m
                if (count > 1) {
                    builder.append("\r\n\r\n");
                }
                builder.append("Thread ").append(thread.getId()).append("  ").append(thread.getName())
                        .append(" (state = ").append(state).append(")").append("\r\n");
                StackTraceElement[] stackTrace = thread.getStackTrace();
                for (StackTraceElement ste : stackTrace) {
                    builder.append(ste.getClassName()).append("-").append(ste.getMethodName()).append("(")
                            .append(ste.getLineNumber()).append(")").append("\r\n");
                }
                if (count >= threadCount) {
                    break;
                }
            }
        }
    }
    return builder.toString();
}

From source file:com.hubcap.task.helpers.DefaultSearchHelper.java

@Override
public void run() {

    if (taskModel == null) {
        if (this.listener != null) {
            this.listener.processTaskHelperError(
                    new Exception("No Task Model Provided to DefaultSearchHelper, cannot run!"), false);
        }/*from w  w w  . j a  v  a  2  s  . c o m*/
        die();
        return;
    }

    CommandLine cmd = taskModel.getCommandLine();

    int cLen = cmd.getArgs().length;
    // default search arguments are in the format
    // orgname (String) count (int)

    if (cLen < 1) {
        if (this.listener != null) {
            this.listener.processTaskHelperError(
                    new Exception("Default Search requires 1 argument, Organization (optional) Count"), false);
        }
        die();
    }

    if (cLen % 2 == 0) {

        // each helper has its own HttpClient
        ProcessModel.instance().updateRateLimitData();

        for (int i = 0; i < cLen; i += 2) {

            String orgName = cmd.getArgs()[i];
            int count = 10;

            try {
                count = Integer.parseInt(cmd.getArgs()[i + 1]);
            } catch (NumberFormatException ex) {
                ErrorUtils.printStackTrace(ex);
            }

            final long remainingRate = ProcessModel.instance().getRateLimitData().rate.remaining;
            final long maxResults = opts.containsKey("maxResults")
                    ? Integer.parseInt((String) opts.get("maxResults"))
                    : (remainingRate - 1);
            int maxPages = 100;
            if (remainingRate >= maxResults) {

                // pound that API until we get what we want!!

                // breaks out of the loop after
                // max pages
                searchHelperId.incrementAndGet();

                if (searchHelperId.get() > maxPages) {
                    break;
                }

                try {
                    synchronized (droneThreads) {

                        Thread t = new Thread(
                                new GitHubOrgScavengerDrone(sewingMachine, this.taskModel, orgName, count));
                        droneThreads.add(t);
                        t.setName("drone" + String.valueOf(owner.getTaskId()) + "-"
                                + String.valueOf(new Date().getTime()));
                        t.setDaemon(false);
                        t.start();
                    }
                } catch (RejectedExecutionException ex) {
                    ErrorUtils.printStackTrace(ex);
                    break;
                }

            } else {
                System.err.println("Your rate limit is exhausted, try again later!");
            }
        }
    }

    if (ProcessModel.instance().getVerbose()) {
        System.out.println("Waiting for Drone Threads: " + droneThreads.size());
    }

    // wait for all threads to complete
    while (droneThreads.size() > 0) {
        Iterator<Thread> it = droneThreads.iterator();
        while (it.hasNext()) {
            Thread currDroneThread = it.next();

            if (currDroneThread.getState() == State.TERMINATED) {

                if (ProcessModel.instance().getVerbose()) {
                    System.err.println("Removing Drone Thread: " + currDroneThread.getName());
                }

                it.remove();
            }
        }

        // sleep and do it again
        if (!ThreadUtils.safeSleep(
                Constants.NEW_THREAD_SPAWN_BREATHING_TIME
                        + Constants.NEW_THREAD_SPAWN_BREATHING_TIME * 1 / SewingMachine.MAX_THREADS_PER_MACHINE,
                ProcessModel.instance().getVerbose())) {
            System.err.println("INTERRUPTED WAIT FOR DRONE THREADS!");
            break;
        }
    }

    System.out.println("No More Drones!");
    // wait a tad

    synchronized (taskModel) {
        Map<String, Object> aggData = taskModel.getAggregateDataMap();

        if (aggData != null) {

            for (String key : aggData.keySet()) {

                Object value = aggData.get(key);

                if (value instanceof ScavengerModel == false) {
                    continue;
                }

                // ask the model to calculate from its current state
                ScavengerModel model = (ScavengerModel) value;
                synchronized (model) {
                    model.calculate();
                }
            }

            listener.processTaskHelperData(taskModel);
        }
    }
    die();
}

From source file:org.noroomattheinn.visibletesla.AppContext.java

public Thread launchThread(Runnable r, String name) {
    Thread t = new Thread(r);
    t.setName(name == null ? ("00 VT - " + threadID++) : name);
    t.setDaemon(true);/*from   www  .ja v  a 2  s. c  o  m*/
    t.start();
    threads.add(t);

    // Clean out any old terminated threads...
    Iterator<Thread> i = threads.iterator();
    while (i.hasNext()) {
        Thread cur = i.next();
        if (cur.getState() == Thread.State.TERMINATED) {
            i.remove();
        }
    }

    return t;
}

From source file:eu.stratosphere.nephele.taskmanager.runtime.RuntimeTask.java

@Override
public boolean isTerminated() {

    final Thread executingThread = this.environment.getExecutingThread();
    if (executingThread.getState() == Thread.State.TERMINATED) {
        return true;
    }// w w w  . j  a  va  2  s.  c  o m

    return false;
}

From source file:eu.stratosphere.nephele.taskmanager.Task.java

/**
 * Checks if the state of the thread which is associated with this task is <code>TERMINATED</code>.
 * //from   w  ww .j  a va  2 s .  c  o  m
 * @return <code>true</code> if the state of this thread which is associated with this task is
 *         <code>TERMINATED</code>, <code>false</code> otherwise
 */
public boolean isTerminated() {
    final Thread executingThread = this.environment.getExecutingThread();
    if (executingThread.getState() == Thread.State.TERMINATED) {
        return true;
    }

    return false;
}