Example usage for java.lang Thread join

List of usage examples for java.lang Thread join

Introduction

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

Prototype

public final synchronized void join(final long millis) throws InterruptedException 

Source Link

Document

Waits at most millis milliseconds for this thread to die.

Usage

From source file:com.thoughtworks.go.config.BackgroundMailSender.java

private ValidationBean execute(Runnable action) {
    Thread thread = new Thread(action);
    thread.start();/*from   w  ww .  j a v  a2 s.c o  m*/
    try {
        thread.join(timeout);
        if (thread.isAlive()) {
            thread.interrupt();
            return ValidationBean.notValid(ERROR_MESSAGE);
        }
        return validation;
    } catch (InterruptedException e) {
        LOGGER.error("Timed out when sending an email. Please check email configuration.");
        return ValidationBean.notValid(ERROR_MESSAGE);
    }
}

From source file:org.echocat.jomon.spring.ContextLoadThreadGroup.java

public boolean join(@Nonnull Duration duration) throws InterruptedException {
    boolean result = true;
    final Iterator<Thread> i = iterator();
    final StopWatch stopWatch = new StopWatch();
    while (result && i.hasNext()) {
        final Thread thread = i.next();
        if (thread.isAlive()) {
            thread.join(duration.minus(stopWatch.getCurrentDuration()).in(MILLISECONDS));
        }/* www  .  j  a va 2 s  .c  o m*/
        result = !thread.isAlive();
    }
    if (result) {
        throwRuntimeExceptionOn();
    }
    return result;
}

From source file:com.sonatype.nexus.perftest.ClientSwarm.java

public void stop() throws InterruptedException {
    for (Thread thread : threads) {
        for (int i = 0; i < 3 && thread.isAlive(); i++) {
            thread.interrupt();//from  w  ww  .  j  a  v  a  2  s  .c o m
            thread.join(1000L);
        }
        if (thread.isAlive()) {
            StringBuilder sb = new StringBuilder(
                    String.format("Thread %s ignored interrupt flag\n", thread.getName()));
            for (StackTraceElement f : thread.getStackTrace()) {
                sb.append("\t").append(f.toString()).append("\n");
            }
            System.err.println(sb.toString());
        }
    }
}

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   www  .ja  v  a2  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:com.photon.phresco.plugins.xcode.AppDeploy.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {//from w  w w.  j a va2s  . c om
        if (!deviceDeploy && !SdkVerifier.isAvailable(simVersion)) {
            throw new MojoExecutionException("Selected version " + simVersion + " is not available!");
        }
    } catch (IOException e2) {
        throw new MojoExecutionException("SDK verification failed!");
    } catch (InterruptedException e2) {
        throw new MojoExecutionException("SDK verification interrupted!");
    }
    //get the correct simhome if xCode 4.3 is installed simhome is in /Application/Xcode.app/Contents
    //Fix for artf462004
    File simHomeFile = new File(simHome);
    if (!simHomeFile.exists()) {
        simHome = "/Applications/Xcode.app/Contents" + simHome;
    }

    getLog().info("Simulator home" + simHome);

    if (!deviceDeploy) {
        //copy the files into simulation directory
        String home = System.getProperty("user.home");
        getLog().info("Application.path = " + appPath);
        appName = getAppFileName(appPath);
        getLog().info("Application name = " + appName);
        String deployHome = "";
        if (StringUtils.isNotBlank(appDeployHome)) {
            deployHome = appDeployHome;
        } else {
            deployHome = home + "/Library/Application Support/iPhone Simulator/" + simVersion + "/Applications";
        }
        simHomeAppLocation = new File(
                deployHome + File.separator + project.getName() + File.separator + appName);
        if (!simHomeAppLocation.exists()) {
            getLog().info("directory created");
            simHomeAppLocation.mkdirs();
        }
        getLog().info("Desired location " + simHomeAppLocation.getAbsolutePath());
        try {
            String alignedPath = alignedPath(appPath);
            getLog().info("path to copy source :" + alignedPath);
            XcodeUtil.copyFolder(new File(alignedPath), simHomeAppLocation);
            getLog().info("copy the application " + appPath + " to " + simHomeAppLocation);
        } catch (IOException e1) {
            getLog().error("couldn't copy the application " + appPath + " to " + simHomeAppLocation);
        }
    }
    Runnable runnable = new Runnable() {
        public void run() {

            ProcessBuilder pb;
            if (deviceDeploy) {
                pb = new ProcessBuilder("transporter_chief.rb");
                pb.command().add(appPath);
            } else {
                pb = new ProcessBuilder(simHome);
                // Include errors in output
                pb.redirectErrorStream(true);

                pb.command().add(action);
                pb.command()
                        .add(simHomeAppLocation + File.separator + appName.substring(0, appName.indexOf('.')));
            }
            //               pb.command().add(appName);
            getLog().info("List of commands" + pb.command());
            Process child;
            try {
                //               if(ProcessHelper.isProcessRunning()) {
                //                  ProcessHelper.killSimulatorProcess();
                //               }
                child = pb.start();
                // Consume subprocess output and write to stdout for debugging
                InputStream is = new BufferedInputStream(child.getInputStream());
                int singleByte = 0;
                while ((singleByte = is.read()) != -1) {
                    System.out.write(singleByte);
                }
            } catch (IOException e) {
                getLog().error("error occured in launching simulator ");
                getLog().error(e);
            }
        }
    };

    Thread t = new Thread(runnable, "iPhoneSimulator");
    t.start();
    try {
        t.join(5000);
    } catch (InterruptedException e1) {
        //Intentionally left blank.
    }

}

From source file:co.cask.tigon.test.SQLFlowTestBase.java

/**
 * This function is used to ingest data packets into multiple interfaces.
 * @param inputDataStreams {@link java.util.List} of {@link java.util.Map.Entry} that contains the name of the
 * interface as the key and the json encoded data packet as the value.
 *
 * Input Format :/*  w w  w. j av  a 2  s.  co m*/
 *            [ Map.Entry<InterfaceName, List<JsonEncodedDataPackets>>,
          Map.Entry<InterfaceName, List<JsonEncodedDataPackets>>,
          Map.Entry<InterfaceName, List<JsonEncodedDataPackets>>,
          .
          .
          Map.Entry<InterfaceName, List<JsonEncodedDataPackets>>]
 */
public static void ingestData(List<Map.Entry<String, List<String>>> inputDataStreams) {
    if (latch == null) {
        throw new RuntimeException("Expected output count not defined. Use setExpectedOutputCount()");
    } else if (service == null) {
        throw new RuntimeException("Flow not setup. Use setupFlow()");
    }
    final List<Map.Entry<String, List<String>>> finalInputDataStreams = inputDataStreams;
    Thread ingestData = new Thread(new Runnable() {
        @Override
        public void run() {
            HttpClient httpClient = new DefaultHttpClient();
            for (Map.Entry<String, List<String>> dataStreamEntry : finalInputDataStreams) {
                for (String dataPacket : dataStreamEntry.getValue()) {
                    try {
                        // TODO eliminate org.apache.http dependency TIGON-5
                        HttpPost httpPost = new HttpPost(
                                "http://localhost:" + httpPort + "/v1/tigon/" + dataStreamEntry.getKey());
                        httpPost.addHeader("Content-Type", "application/json");
                        httpPost.setEntity(new StringEntity(dataPacket, Charsets.UTF_8));
                        EntityUtils.consumeQuietly(httpClient.execute(httpPost).getEntity());
                    } catch (Exception e) {
                        Throwables.propagate(e);
                    }
                }
            }
        }
    });
    ingestionThreads.add(ingestData);
    ingestData.start();
    try {
        ingestData.join(60000);
    } catch (InterruptedException e) {
        Throwables.propagate(e);
    }
}

From source file:com.cisco.cta.taxii.adapter.httpclient.BasicAuthHttpRequestFactoryTest.java

@Test(expected = SocketTimeoutException.class)
public void timeoutConnection() throws Exception {
    BasicAuthHttpRequestFactory factoryImpl = (BasicAuthHttpRequestFactory) factory;
    factoryImpl.setReadTimeout(10);/*from  www  .  ja  va2 s  . c  o  m*/
    Thread server = null;
    try (ServerRunnable serverRunnable = new ServerRunnable()) {
        server = new Thread(serverRunnable);
        ClientHttpRequest req = factory.createRequest(connSettings.getPollEndpoint().toURI(), HttpMethod.POST);
        req.execute();
    } finally {
        server.join(10);
    }
}

From source file:com.nesscomputing.event.amqp.AmqpEventReceiver.java

@OnStage(LifecycleStage.STOP)
void stop() throws InterruptedException {
    final Thread consumerThread = consumerThreadHolder.getAndSet(null);
    if (consumerThread != null) {
        final ExchangeConsumer exchangeConsumer = exchangeConsumerHolder.getAndSet(null);
        if (exchangeConsumer != null) {
            exchangeConsumer.shutdown();

            consumerThread.interrupt();/*ww w.  ja  v a 2  s  .c om*/
            consumerThread.join(500L);
        }
    } else {
        LOG.debug("Never started, ignoring stop()");
    }
}

From source file:com.nesscomputing.event.jms.JmsEventReceiver.java

@OnStage(LifecycleStage.STOP)
public void stop() {
    final Thread consumerThread = consumerThreadHolder.getAndSet(null);
    if (consumerThread != null) {
        try {//from w  ww. j a  va  2s .  co m
            final AbstractConsumer consumer = consumerHolder.getAndSet(null);
            if (consumer != null) {
                consumer.shutdown();

                consumerThread.interrupt();
                consumerThread.join(500L);
            }
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt(); // Someone else needs to handle that.
        }
    } else {
        LOG.debug("Never started, ignoring stop()");
    }
}

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

@Override
public void run() {
    isExecuting = true;// w  w w  .ja va2s  . c o m
    // 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;
}