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:net.doubledoordev.cmd.CurseModpackDownloader.java

private void waitTillDone() throws IOException {
    if (installerProcess != null) {
        try {//from   ww w  .ja  va 2 s .  c  om
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(installerProcess.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                logger.println(line);
            }

            installerProcess.waitFor();
            if (installerFile.exists())
                installerFile.delete();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    boolean done;
    do {
        done = true;
        for (Thread thread : threadObjects) {
            if (thread.isAlive()) {
                done = false;
                break;
            }
        }
        smallDelay();
    } while (!done);

    if (failCounter.get() != 0)
        logger.println("!!!     Some mod downloads failed       !!!");
    else
        logger.println("This was a triumph.");
}

From source file:jenkins.plugins.publish_over_ssh.BapSshClient.java

private void waitForExec(final ChannelExec exec, final long timeout) {
    final long start = System.currentTimeMillis();
    final Thread waiter = new ExecCheckThread(exec);
    waiter.start();//from  ww  w.j a v  a 2 s. co  m
    try {
        waiter.join(timeout);
    } catch (InterruptedException ie) {
    }
    final long duration = System.currentTimeMillis() - start;
    if (waiter.isAlive()) {
        waiter.interrupt();
    }
    if (!exec.isClosed())
        throw new BapPublisherException(Messages.exception_exec_timeout(duration));
    buildInfo.println(Messages.console_exec_completed(duration));
}

From source file:dk.netarkivet.harvester.harvesting.controller.AbstractJMXHeritrixController.java

/**
 * Waits for the Heritrix process to exit.
 *///from   w w  w.  j  a va  2  s  .  com
protected void waitForHeritrixProcessExit() {
    final long maxWait = Settings.getLong(CommonSettings.PROCESS_TIMEOUT);
    final int maxJmxRetries = JMXUtils.getMaxTries();
    Integer exitValue = ProcessUtils.waitFor(heritrixProcess, maxWait);
    if (exitValue != null) {
        log.info("Heritrix process of " + this + " exited with exit code " + exitValue);
    } else {
        log.warn("Heritrix process of " + this + " not dead after " + maxWait + " millis, killing it");
        heritrixProcess.destroy();
        exitValue = ProcessUtils.waitFor(heritrixProcess, maxWait);
        if (exitValue != null) {
            log.info("Heritrix process of " + this + " exited with exit code " + exitValue);
        } else {
            // If it's not dead now, there's little we can do.
            log.fatal(
                    "Heritrix process of " + this + " not dead after destroy. " + "Exiting harvest controller. "
                            + "Make sure you kill the runaway Heritrix " + "before you restart.");
            NotificationsFactory.getInstance().notify(
                    "Heritrix process of " + this + " not dead after destroy. " + "Exiting harvest controller. "
                            + "Make sure you kill the runaway Heritrix " + "before you restart.",
                    NotificationType.ERROR);
            System.exit(1);
        }
    }
    Runtime.getRuntime().removeShutdownHook(processKillerHook);
    // Wait until all collection threads are dead or until we have
    // tried JMXUtils.MAX_TRIES times.
    int attempt = 0;
    do {
        boolean anyAlive = false;
        for (Thread t : collectionThreads) {
            if (t.isAlive()) {
                anyAlive = true;
            }
        }
        if (!anyAlive) {
            break;
        }
        TimeUtils.exponentialBackoffSleep(attempt);
    } while (attempt++ < maxJmxRetries);
}

From source file:org.hobbit.core.components.BenchmarkControllerTest.java

@Test
public void test() throws Exception {
    environmentVariables.set(Constants.RABBIT_MQ_HOST_NAME_KEY, TestConstants.RABBIT_HOST);
    environmentVariables.set(Constants.HOBBIT_SESSION_ID_KEY, sessionId);
    environmentVariables.set(Constants.BENCHMARK_PARAMETERS_MODEL_KEY,
            "{ \"@id\" : \"http://w3id.org/hobbit/experiments#New\", \"@type\" : \"http://w3id.org/hobbit/vocab#Experiment\" }");
    environmentVariables.set(Constants.HOBBIT_EXPERIMENT_URI_KEY, Constants.EXPERIMENT_URI_NS + sessionId);
    // Needed for the generators
    environmentVariables.set(Constants.GENERATOR_ID_KEY, "0");
    environmentVariables.set(Constants.GENERATOR_COUNT_KEY, "1");

    final DummyPlatformController dummyPlatformController = new DummyPlatformController(sessionId);
    try {/*from w w  w  .  ja  va 2s .  c o m*/
        DummyComponentExecutor dummyPlatformExecutor = new DummyComponentExecutor(dummyPlatformController);
        Thread dummyPlatformThread = new Thread(dummyPlatformExecutor);
        dummyPlatformThread.start();
        dummyPlatformController.waitForControllerBeingReady();

        AbstractBenchmarkController controller = this;
        DummyComponentExecutor controllerExecutor = new DummyComponentExecutor(controller);
        Thread controllerThread = new Thread(controllerExecutor);
        controllerThread.start();
        // wait for the benchmark controller to start

        Thread.sleep(10000);
        dummyPlatformController.sendToCmdQueue(Constants.HOBBIT_SESSION_ID_FOR_BROADCASTS,
                Commands.DOCKER_CONTAINER_TERMINATED,
                RabbitMQUtils.writeByteArrays(null,
                        new byte[][] { RabbitMQUtils.writeString(SYSTEM_CONTAINER_ID) },
                        new byte[] { (byte) 0 }),
                null);
        Thread.sleep(10000);

        for (Thread t : dummyPlatformController.dataGenThreads) {
            t.join(10000);
            Assert.assertFalse(t.isAlive());
        }
        for (Thread t : dummyPlatformController.taskGenThreads) {
            t.join(10000);
            Assert.assertFalse(t.isAlive());
        }

        for (DummyComponentExecutor executor : dummyPlatformController.dataGenExecutors) {
            Assert.assertTrue(executor.isSuccess());
        }
        for (DummyComponentExecutor executor : dummyPlatformController.taskGenExecutors) {
            Assert.assertTrue(executor.isSuccess());
        }

        // Make sure that the benchmark controller terminates during the
        // next seconds
        controllerThread.join(5000);
        Assert.assertFalse(controllerThread.isAlive());
    } finally {
        dummyPlatformController.terminate();
        for (DummyComponentExecutor executor : dummyPlatformController.dataGenExecutors) {
            try {
                IOUtils.closeQuietly(executor.getComponent());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        for (DummyComponentExecutor executor : dummyPlatformController.taskGenExecutors) {
            try {
                IOUtils.closeQuietly(executor.getComponent());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        close();
    }
}

From source file:com.samknows.measurement.ManualTest.java

@Override
public void run() {
    isExecuting = true;//from   w w  w.j  av  a 2s.  c om
    // Start collectors for the passive metrics
    // Start tests
    long startTime = System.currentTimeMillis();
    JSONObject batch = new JSONObject();
    TestContext tc = TestContext.create(ctx);
    TestExecutor te = new TestExecutor(tc);
    List<JSONObject> testsResults = new ArrayList<JSONObject>();
    List<JSONObject> passiveMetrics = new ArrayList<JSONObject>();
    te.startInBackGround();
    Message msg;
    long testsBytes = 0;
    for (TestDescription td : mTestDescription) {
        // check if a stop command has been received
        if (!run.get()) {
            Logger.d(this, "Manual test interrupted by the user.");
            break;
        }
        com.samknows.measurement.test.TestResult tr = new com.samknows.measurement.test.TestResult();
        ObservableExecutor oe = new ObservableExecutor(te, td, tr);
        Thread t = new Thread(oe);
        t.start();
        while (true) {
            try {
                t.join(100);
                if (!t.isAlive())
                    break;
            } catch (InterruptedException ie) {
                Logger.e(this, ie.getMessage());
            }
            for (JSONObject pm : progressMessage(td, te)) {
                msg = new Message();
                msg.obj = pm;
                mHandler.sendMessage(msg);
            }

        }
        testsBytes += te.getLastTestByte();

        List<JSONObject> currResults = new ArrayList<JSONObject>();
        for (String out : tr.results) {
            currResults.addAll(TestResult.testOutput(out));
        }
        for (JSONObject cr : currResults) {
            // publish results
            msg = new Message();
            msg.obj = cr;
            mHandler.sendMessage(msg);
        }
        testsResults.addAll(currResults);
    }
    Logger.d(this, "bytes used by the tests: " + testsBytes);
    AppSettings.getInstance().appendUsedBytes(testsBytes);
    // stops collectors
    te.stop();

    te.save(JSON_MANUAL_TEST);

    // Gather data from collectors
    for (BaseDataCollector collector : tc.config.dataCollectors) {
        if (collector.isEnabled) {
            for (JSONObject o : collector.getPassiveMetric()) {
                // update interface
                msg = new Message();
                msg.obj = PassiveMetric.passiveMetricToCurrentTest(o);
                mHandler.sendMessage(msg);
                // save metric
                passiveMetrics.add(o);
            }
        }
    }
    // insert batch in the database
    try {
        batch.put(TestBatch.JSON_DTIME, startTime);
        batch.put(TestBatch.JSON_RUNMANUALLY, "1");
    } catch (JSONException je) {
        Logger.e(this, "Error in creating test batch object: " + je.getMessage());
    }

    // insert the results in the database only if we didn't receive a stop
    // command
    if (run.get()) {
        DBHelper db = new DBHelper(ctx);

        db.insertTestBatch(batch, testsResults, passiveMetrics);

    }
    // Send completed message to the interface
    msg = new Message();
    JSONObject jtc = new JSONObject();
    try {
        Thread.sleep(1000);
        jtc.put(TestResult.JSON_TYPE_ID, "completed");
        msg.obj = jtc;

    } catch (JSONException je) {
        Logger.e(this, "Error in creating json object: " + je.getMessage());
    } catch (InterruptedException e) {
        Logger.e(this, "Sleep interrupted in the manual test view: " + e.getMessage());
    }
    mHandler.sendMessage(msg);

    try {
        // Submitting test results
        if (AppSettings.getInstance().anonymous) {
            new SubmitTestResultsAnonymousAction(ctx).execute();
        } else {
            new SubmitTestResultsAction(ctx).execute();
        }
    } catch (Throwable t) {
        Logger.e(this, "Submit result. ", t);
    }

    Logger.d(this, "Exiting manual test");

    isExecuting = false;
}

From source file:com.mirth.connect.connectors.tcp.TcpDispatcher.java

private void disposeThread(String socketKey) throws InterruptedException {
    Thread thread = timeoutThreads.get(socketKey);

    if (thread != null && thread.isAlive()) {
        logger.trace("Interrupting thread (" + connectorProperties.getName() + " \"" + getDestinationName()
                + "\" on channel " + getChannelId() + ").");
        thread.interrupt();/*from w  ww  .j  a v a 2  s. c o  m*/

        logger.trace("Joining thread (" + connectorProperties.getName() + " \"" + getDestinationName()
                + "\" on channel " + getChannelId() + ").");
        try {
            thread.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw e;
        }
    }
}

From source file:com.sworddance.taskcontrol.TestTaskControl.java

private void startTaskControl(TaskControl taskControl, TaskGroup<?> taskGroup) throws InterruptedException {
    // additional test that addTaskGroup after TaskControl start will work.
    taskControl.addTaskGroup(taskGroup);
    Thread t = new Thread(taskControl);
    taskControl.setStayActive(false);//ww  w .j  a v  a2s  .  co  m
    t.setName("TaskControl");
    t.start();
    t.join();
    assertFalse(t.isAlive());
}

From source file:org.castor.cpa.test.test02.TestConcurrent.java

/**
 * This method is called by the tests and preform the actual
 * concurrent modification test.//  w  ww. j  a v  a  2s. com
 *
 * @param accessMode the access mode that is used in the concurrent
 *        modification tests
 */
private void runDirtyChecked(final AccessMode accessMode) throws Exception {
    JDOManager jdo = getJDOManager(DBNAME, MAPPING);

    OQLQuery oql;
    Sample object;
    QueryResults enumeration;

    // Open transaction in order to perform JDO operations
    _db.begin();

    // Determine if test object exists, if not create it.
    // If it exists, set the name to some predefined value
    // that this test will later override.
    oql = _db.getOQLQuery("SELECT object FROM " + Sample.class.getName() + " object WHERE id = $1");
    oql.bind(Sample.DEFAULT_ID);

    enumeration = oql.execute();
    if (enumeration.hasMore()) {
        object = (Sample) enumeration.next();
        LOG.debug("Retrieved object: " + object);
        object.setValue1(Sample.DEFAULT_VALUE_1);
        object.setValue2(Sample.DEFAULT_VALUE_2);
    } else {
        object = new Sample();
        LOG.debug("Creating new object: " + object);
        _db.create(object);
    }

    _db.commit();

    // Open a new transaction in order to conduct test
    _db.begin();

    oql.bind(new Integer(Sample.DEFAULT_ID));
    object = (Sample) oql.execute(accessMode).nextElement();
    object.setValue1(JDO_VALUE);

    // Perform direct JDBC access and override the value of that table
    if (accessMode != Database.DBLOCKED) {
        Connection conn = jdo.getConnectionFactory().createConnection();
        Statement stmt = conn.createStatement();
        stmt.execute("UPDATE test02_sample SET value1='" + JDBC_VALUE + "' " + "WHERE id=" + Sample.DEFAULT_ID);
        stmt.close();
        conn.close();
        LOG.debug("OK: Updated object from JDBC");
    } else {
        Thread th = new ConcurrentUpdateThread(jdo);
        th.start();
        synchronized (this) {
            try {
                wait(WAIT_FOR_CONCURRENT_UPDATE);
                if (th.isAlive()) {
                    th.interrupt();
                    LOG.debug("OK: Cannot update object from JDBC");
                } else {
                    LOG.error("Error: Updated object from JDBC");
                    fail("Updated test object from JDBC");
                }
            } catch (InterruptedException ex) {
            }
        }
    }

    // Commit JDO transaction, this should report object modified exception
    LOG.debug("Committing JDO update: dirty checking field modified");
    if (accessMode != Database.DBLOCKED) {
        try {
            _db.commit();
            LOG.error("Error: ObjectModifiedException not thrown");
            fail("ObjectModifiedException not thrown");
        } catch (ObjectModifiedException ex) {
            LOG.debug("OK: ObjectModifiedException thrown");
        }
    } else {
        try {
            _db.commit();
            LOG.debug("OK: ObjectModifiedException not thrown");
            // After _db.commit the concurrent update will be performed.
            // and we need to undo it.
            Connection conn = jdo.getConnectionFactory().createConnection();
            Statement stmt = conn.createStatement();
            stmt.execute(
                    "UPDATE test02_sample SET value1='" + JDO_VALUE + "' " + "WHERE id=" + Sample.DEFAULT_ID);
            stmt.close();
            conn.close();
        } catch (ObjectModifiedException ex) {
            _db.rollback();
            LOG.error("Error: ObjectModifiedException thrown");
            fail("ObjectModifiedException not thrown");
        }
    }
}

From source file:org.sonar.application.SchedulerImplTest.java

@Test
public void awaitTermination_blocks_until_all_processes_are_stopped() throws Exception {
    Scheduler underTest = startAll();/* w  w  w  . java2  s  .  c  om*/

    Thread awaitingTermination = new Thread(() -> underTest.awaitTermination());
    awaitingTermination.start();
    assertThat(awaitingTermination.isAlive()).isTrue();

    underTest.terminate();
    // the thread is being stopped
    awaitingTermination.join();
    assertThat(awaitingTermination.isAlive()).isFalse();
}

From source file:org.echocat.jemoni.carbon.jmx.Jmx2CarbonBridge.java

protected void stopThread(@Nullable Thread thread) {
    if (thread != null) {
        thread.interrupt();/*from  ww w  . j a  v a 2  s .c  o  m*/
        try {
            long tries = 0;
            while (thread.isAlive()) {
                tries++;
                thread.join(50);
                thread.interrupt();
                if (thread.isAlive() && tries % 200 == 0) {
                    LOG.info("Still wait for termination of '" + thread + "'...");
                }
            }
        } catch (InterruptedException ignored) {
            currentThread().interrupt();
            LOG.debug("Could not wait for termination of '" + thread + "' - but this thread was interrupted.");
        }
    }
}