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:org.eclipse.ecr.core.event.tx.PostCommitSynchronousRunner.java

protected void runSync() {
    log.debug("Starting sync executor from Thread " + Thread.currentThread().getId());
    Thread runner = new Thread(getExecutor());
    runner.start();/*ww w . j a v a 2s.co  m*/
    try {
        runner.join(timeout);
        if (runner.isAlive()) {
            handleUnfinishedThread(runner);
        }
    } catch (InterruptedException e) {
        log.error("Exit before the end of processing", e);
    }
    log.debug("Terminated sync executor from Thread " + Thread.currentThread().getId());
}

From source file:ubic.gemma.web.controller.common.auditAndSecurity.SignupControllerTest.java

@SuppressWarnings("Duplicates") // Not in this project
@Test//from w  w  w  .j  a  v a 2  s.com
public void testSignup() throws Exception {
    int numThreads = 10; // too high and we run out of connections, which is not what we're testing.
    final int numsignupsperthread = 20;
    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 k = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int j = 0; j < numsignupsperthread; j++) {
                        MockHttpServletRequest req;
                        Thread.sleep(random.nextInt(50));
                        req = new MockHttpServletRequest("POST", "/signup.html");
                        String uname = RandomStringUtils.randomAlphabetic(10);
                        // log.info( "Signingup: " + uname + " (" + c.get() + ")" );

                        String password = RandomStringUtils.randomAlphabetic(40);
                        req.addParameter("password", password);

                        req.addParameter("passwordConfirm", password);
                        req.addParameter("username", uname);
                        String email = "foo@" + RandomStringUtils.randomAlphabetic(10) + ".edu";
                        req.addParameter("email", email);

                        req.addParameter("emailConfirm", email);
                        suc.signup(req, new MockHttpServletResponse());

                        /*
                         * Extra torture.
                         */
                        ExpressionExperiment ee = ExpressionExperiment.Factory.newInstance();
                        ee.setDescription("From test");
                        ee.setName(RandomStringUtils.randomAlphabetic(20));
                        ee.setShortName(RandomStringUtils.randomAlphabetic(20));
                        // log.info( "Making experiment" + ee.getName() );
                        expressionExperimentService.create(ee);

                        c.incrementAndGet();

                    }
                } 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 * numsignupsperthread;
    while (c.get() < expectedEventCount && !failed.get()) {
        Thread.sleep(3000);
        log.info("Waiting ... C=" + +c.get());
        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.codelibs.fess.servlet.Tomcat6ConfigServlet.java

private void waitThread(final Thread thread) {
    int count = 0;
    while (thread.isAlive() && count < 5) {
        try {/*from   w  w w . j a v a  2  s.c  om*/
            Thread.sleep(100);
        } catch (final InterruptedException e) {
        }
        count++;
    }
}

From source file:ubc.pavlab.aspiredb.server.controller.SignupControllerTest.java

@Test
public void testSignup() throws Exception {

    int numThreads = 10; // too high and we run out of connections, which is not what we're testing.
    final int numsignupsperthread = 10;
    final Random random = new Random();
    final AtomicInteger c = new AtomicInteger(0);
    final AtomicBoolean failed = new AtomicBoolean(false);
    Collection<Thread> threads = new HashSet<Thread>();
    final Collection<String> unames = Collections.synchronizedList(new ArrayList<String>());

    for (int i = 0; i < numThreads; i++) {

        Thread k = new Thread(new Runnable() {
            @Override/*from www  . j  av  a  2  s  .  com*/
            public void run() {
                try {
                    for (int j = 0; j < numsignupsperthread; j++) {
                        MockHttpServletRequest req = null;
                        Thread.sleep(random.nextInt(50));
                        req = new MockHttpServletRequest("POST", "/signup.html");
                        final String uname = RandomStringUtils.randomAlphabetic(10);

                        synchronized (unames) {
                            unames.add(uname);
                        }

                        // log.info( "Signingup: " + uname + " (" + c.get() + ")" );

                        String password = RandomStringUtils.randomAlphabetic(40);
                        req.addParameter("password", password);

                        req.addParameter("passwordConfirm", password);
                        req.addParameter("username", uname);
                        String email = "foo@" + RandomStringUtils.randomAlphabetic(10) + ".edu";
                        req.addParameter("email", email);
                        suc.signup(req, new MockHttpServletResponse());

                        // Cleanup
                        // userService.delete( userService.findByUserName( uname ) );

                        c.incrementAndGet();

                    }
                } 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 = 30;
    int expectedEventCount = numThreads * numsignupsperthread;
    while (c.get() < expectedEventCount && !failed.get()) {
        try {
            Thread.sleep(8000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("Waiting ... C=" + +c.get());
        if (++waits > maxWaits) {
            for (Thread t : threads) {
                if (t.isAlive())
                    t.interrupt();
            }
            fail("Multithreaded failure: timed out.");
        }
    }

    // cleanup
    for (String uname : unames) {
        userService.delete(userService.findByUserName(uname));
    }

    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:com.wavemaker.runtime.server.ServiceResponse.java

private void cleanup() {
    for (Map.Entry<String, Thread> entry : this.threads.entrySet()) {
        String requestId = entry.getKey();
        Thread thread = entry.getValue();
        if (!thread.isAlive()) {
            Tuple.Two<Long, JSONObject> t = this.serviceResponseTable.get(requestId);
            if (t != null) {
                long time = t.v1;
                if (System.currentTimeMillis() - time > (this.connectionTimeout - 3) * 1000 * 2) {
                    log.debug("ServiceResponse: Cleanup: Remvoving: " + requestId + " " + thread.getId()
                            + " ---");
                    this.serviceResponseTable.remove(requestId);
                    this.threads.remove(requestId);
                }/* ww w  .  j  a  va 2  s.  c  o m*/
            }
        }
    }
}

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

@Test(timeout = 5000)
public void testRunBeforeCtxClosedEvent() throws Exception {
    ContextRefreshedEvent refreshEvent = mock(ContextRefreshedEvent.class);
    inBuffer.onApplicationEvent(refreshEvent);

    ContextClosedEvent event = mock(ContextClosedEvent.class);
    when(workerManager.isUp()).thenReturn(true);
    Thread thread = new Thread(inBuffer);
    thread.start();//from  ww  w .j a va 2  s  .com

    verify(workerManager, timeout(1000).atLeastOnce()).getInBufferSize();

    inBuffer.onApplicationEvent(event);
    while (thread.isAlive()) {
        Thread.sleep(100L);
    }
}

From source file:com.github.rnewson.couchdb.lucene.LuceneServlet.java

private synchronized DatabaseIndexer getIndexer(final Database database) throws IOException, JSONException {
    DatabaseIndexer result = indexers.get(database);
    Thread thread = threads.get(database);
    if (result == null || thread == null || !thread.isAlive()) {
        result = new DatabaseIndexer(client, root, database, ini);
        thread = new Thread(result);
        thread.start();/*  w w w. j a v a  2 s  .c o m*/
        result.awaitInitialization();
        if (result.isClosed()) {
            return null;
        } else {
            indexers.put(database, result);
            threads.put(database, thread);
        }
    }

    return result;
}

From source file:org.intermine.web.logic.session.SessionMethods.java

/**
 * Executes an action and call a callback when it completes successfully. If the
 * query fails for some reason, this method returns false and ActionErrors are set on the
 * request./* ww w. java 2 s.co  m*/
 *
 * @param session   the http session
 * @param resources message resources
 * @param qid       the query id
 * @param action    the action/query to perform in a new thread
 * @param completionCallBack sets the method to call when the action successfully completes
 * @return  true if query ran successfully, false if an error occured
 * @throws  Exception if getting results info from paged results fails
 */
public static boolean runQuery(final HttpSession session, final MessageResources resources, final String qid,
        final Action action, final CompletionCallBack completionCallBack) throws Exception {
    final InterMineAPI im = getInterMineAPI(session);
    final ObjectStore os = im.getObjectStore();

    final ObjectStoreInterMineImpl ios;
    if (os instanceof ObjectStoreInterMineImpl) {
        ios = (ObjectStoreInterMineImpl) os;
    } else {
        ios = null;
    }
    Map<String, QueryMonitor> queries = getRunningQueries(session);
    QueryMonitor monitor = queries.get(qid);
    // A reference to this runnable is used as a token for registering
    // a cancelling the running query

    RunQueryThread runnable = new RunQueryThread() {
        @Override
        public void run() {
            try {

                // Register request id for query on this thread
                // We do this before setting r
                if (ios != null) {
                    LOG.debug("Registering request id " + this);
                    ios.registerRequestId(this);
                }

                // call this so that if an exception occurs we notice now rather than in the
                // JSP code
                try {
                    action.process();
                } catch (IndexOutOfBoundsException err) {
                    // no results - ignore
                    // we don't call size() first to avoid this exception because that could be
                    // very slow on a large results set
                } catch (RuntimeException e) {
                    if (e.getCause() instanceof ObjectStoreException) {
                        throw (ObjectStoreException) e.getCause();
                    }
                    throw e;
                }
            } catch (ObjectStoreException e) {
                // put stack trace in the log
                LOG.error("Exception", e);

                String key = (e instanceof ObjectStoreQueryDurationException)
                        ? "errors.query.estimatetimetoolong"
                        : "errors.query.objectstoreerror";
                recordError(resources.getMessage(key), session);

                error = true;
            } catch (Throwable err) {
                StringWriter sw = new StringWriter();
                err.printStackTrace(new PrintWriter(sw));
                recordError(sw.toString(), session);
                LOG.error("Exception", err);
                error = true;
            } finally {
                try {
                    LOG.debug("Deregistering request id " + this);
                    ((ObjectStoreInterMineImpl) os).deregisterRequestId(this);
                } catch (ObjectStoreException e1) {
                    LOG.error("Exception", e1);
                    error = true;
                }
            }
        }
    };
    Thread thread = null;
    thread = new Thread(runnable);
    thread.start();

    while (thread.isAlive()) {
        Thread.sleep(1000);
        if (monitor != null) {
            boolean cancelled = monitor.shouldCancelQuery();
            if (cancelled && ios != null) {
                LOG.debug("Cancelling request " + runnable);
                ios.cancelRequest(runnable);
                monitor.queryCancelled();
                return false;
            }
        }
    }

    if (runnable.isError()) {
        if (monitor != null) {
            monitor.queryCancelledWithError();
        }
        return false;
    }

    if (completionCallBack != null) {
        completionCallBack.complete();
    }

    if (monitor != null) {
        monitor.queryCompleted();
    }

    return true;
}

From source file:ThreadViewer.java

private void createPendingCellData() {
    Thread[] thread = findAllThreads();
    Object[][] cell = new Object[thread.length][columnCount];

    for (int i = 0; i < thread.length; i++) {
        Thread t = thread[i];
        Object[] rowCell = cell[i];

        rowCell[0] = new Integer(t.getPriority());
        rowCell[1] = new Boolean(t.isAlive());
        rowCell[2] = new Boolean(t.isDaemon());
        rowCell[3] = new Boolean(t.isInterrupted());
        rowCell[4] = t.getThreadGroup().getName();
        rowCell[5] = t.getName();//from  www . j a  v  a 2s  .co  m
    }

    synchronized (dataLock) {
        pendingCellData = cell;
    }
}

From source file:com.wavemaker.runtime.server.ServiceResponse.java

public Object getResponseFromService() {

    JSONObject result = this.getResponseBeforeTimeout();
    String status = (String) result.get("status");
    if (status.equals("processing")) {
        Thread originalThread = this.getRequestThread();
        if (originalThread == null || !originalThread.isAlive()) {
            result = this.getResponseTryOnce();
            status = (String) result.get("status");
            if (status.equals("processing")) {
                if (originalThread == null) {
                    throw new WMRuntimeException("Error: The original request thread is lost");
                } else {
                    throw new WMRuntimeException("Error: The original request thread has been terminated");
                }/*from   www.  ja  v  a2  s. c o m*/
            }
        }
    }

    if (status.equals("error")) {
        throw new WMRuntimeException((Exception) result.get("result"));
    }

    setJsonResponseStatus((String) result.get("status"));
    return result.get("result");
}