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.github.horrorho.inflatabledonkey.util.ProcessManager.java

Optional<byte[]> pipe(Process process, InputStream in) throws IOException, InterruptedException {
    try (InputStream decoderIn = process.getInputStream();
            OutputStream decoderOut = process.getOutputStream()) {

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        Thread write = new Thread(() -> copy(in, decoderOut));
        Thread read = new Thread(() -> copy(decoderIn, out));
        write.start();//  w  w w. j a v  a  2s  .  c o m
        read.start();

        if (!process.waitFor(timeoutMS, TimeUnit.MILLISECONDS)) {
            logger.warn("-- pipe() - timed out");
            // copy threads will shortly exit on exceptions as their streams are closed.
            return Optional.empty();
        }
        read.join(timeoutMS);

        return Optional.of(out.toByteArray());

    } finally {
        if (logger.isWarnEnabled()) {
            error(process);
        }
    }
}

From source file:br.com.uol.runas.classloader.ClassLoaderGC.java

@SuppressWarnings({ "unchecked", "deprecation" })
private void releaseFromShutdownHooks(WeakReference<ClassLoader> classLoader) {
    final Map<Thread, Thread> hooks = (Map<Thread, Thread>) Reflections
            .getStaticFieldValue("java.lang.ApplicationShutdownHooks", "hooks");

    if (hooks != null) {
        final List<Thread> shutdownHooks = new ArrayList<>(hooks.keySet());

        for (Thread shutdownHook : shutdownHooks) {
            if (Objects.equals(classLoader.get(), shutdownHook.getContextClassLoader())) {
                Runtime.getRuntime().removeShutdownHook(shutdownHook);
                shutdownHook.start();//from  w  ww  . j a  v a 2 s .  c om
                try {
                    shutdownHook.join(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    shutdownHook.stop();
                }
                shutdownHook.setContextClassLoader(null);
            }
        }
    }
}

From source file:fr.lirmm.graphik.graal.bench.homomorphism.InfHomomorphismBench.java

private DefaultUnionOfConjunctiveQueries rewrite(ConjunctiveQuery q) {

    Rewriter r = new Rewriter(q, onto, rc);
    Thread thread = new Thread(r);
    thread.start();/*www  . j  av  a2s.  c  o  m*/
    try {
        thread.join(3600000); // 60min
    } catch (InterruptedException e1) {

    }
    if (thread.isAlive()) {
        thread.stop();
        return null;
    } else {
        return r.getUCQ();
    }

}

From source file:com.shopzilla.hadoop.testing.hdfs.DFSCluster.java

@PreDestroy
public void stop() {
    try {//w  ww.  j  av  a  2  s .c  om
        final Thread shutdownThread = new Thread(new Runnable() {

            @Override
            public void run() {
                if (miniDFSCluster != null) {
                    miniDFSCluster.shutdown();
                    miniDFSCluster = null;
                }
            }
        });
        shutdownThread.start();
        shutdownThread.join(10000);
        FileUtils.deleteQuietly(buildDirectory);
        FileUtils.deleteQuietly(new File(projectDirectory, "logs"));
    } catch (final InterruptedException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.cloudera.branchreduce.impl.thrift.LordMain.java

@Override
public int run(String[] args) throws Exception {
    LOG.info("Initializing lord...");
    initialize(args);/* w ww . j a va2s.  co m*/
    LOG.info("Lord initialized.");

    String hostname = InetAddress.getLocalHost().getHostName();
    ServerSocket socket = new ServerSocket(0);
    ApplicationMasterParameters appMasterParams = new LuaApplicationMasterParameters(getConf(),
            ImmutableMap.<String, Object>of("MASTER_HOSTNAME", hostname, "MASTER_PORT", socket.getLocalPort()));
    appMasterParams.setTrackingUrl(String.format("%s:%d", hostname, socket.getLocalPort()));
    ApplicationMasterService appMasterService = new ApplicationMasterServiceImpl(appMasterParams, getConf());
    LOG.info("Starting application master service");
    appMasterService.startAndWait();

    TaskMaster taskMaster = new TaskMaster(numVassals, initialTasks, globalState);
    LordHandler lordHandler = new LordHandler(taskMaster);
    TServerSocket serverTransport = new TServerSocket(socket);
    Lord.Processor lordProc = new Lord.Processor(lordHandler);
    final TServer thriftServer = new TThreadPoolServer(
            new TThreadPoolServer.Args(serverTransport).processor(lordProc));

    LOG.info("Starting lord thrift server");
    Thread thriftServerThread = new Thread("Lord Thrift Server") {
        @Override
        public void run() {
            thriftServer.serve();
        };
    };
    thriftServerThread.start();

    do {
        Thread.sleep(1000);
    } while (appMasterService.hasRunningContainers());

    // Send final notifications
    lordHandler.signalJobFinished();
    while (!lordHandler.finishedNotificationSent()) {
        Thread.sleep(1000);
    }
    thriftServerThread.join(1000);

    LOG.info("Stopping application master service");
    appMasterService.stopAndWait();
    return 0;
}

From source file:com.alibaba.napoli.metamorphosis.client.consumer.SimpleFetchManager.java

@Override
public void stopFetchRunner() throws InterruptedException {
    topicPartitionRegInfos = null;//from   w w w  . j  a  va 2s .  c o m
    this.shutdown = true;
    // 
    if (this.fetchRunners != null) {
        for (final Thread thread : this.fetchRunners) {
            if (thread != null) {
                thread.interrupt();
                try {
                    thread.join(5000);
                } catch (final InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }

        }
    }
    // ?
    if (this.requestQueue != null) {
        while (this.requestQueue.size() != this.fetchRequestCount) {
            Thread.sleep(50);
        }
    }

}

From source file:es.curso.android.streamingVLC.VideoActivity.java

private void stopStreaming() {
    Thread th = new Thread(new Runnable() {

        @Override//from  w  w w .  j  a  v  a  2s  . c  o  m
        public void run() {

            doGetPetition("http://10.15.181.28:8000/streaming/stop/");

        }
    });

    th.start();

    try {
        th.join(3000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:de.csdev.ebus.core.connection.EBusSerialNRJavaSerialConnection.java

@Override
public boolean close() throws IOException {
    if (serialPort == null) {
        return true;
    }//from   ww  w.  j  a  v  a2s .com

    // run the serial.close in a new not-interrupted thread to
    // prevent an IllegalMonitorStateException error
    Thread shutdownThread = new Thread(new Runnable() {
        @Override
        public void run() {

            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);

            if (serialPort != null) {
                serialPort.close();
                serialPort = null;
            }
        }
    }, "eBUS serial shutdown thread");

    shutdownThread.start();

    try {
        // wait for shutdown
        shutdownThread.join(2000);
    } catch (InterruptedException e) {
    }

    return true;
}

From source file:com.samknows.measurement.test.TestExecutor.java

public void executeTest(TestDescription td, TestResult result) {
    try {/*  w  ww .  j  ava  2  s.co m*/
        List<Param> params = tc.paramsManager.prepareParams(td.params);

        executingTest = TestFactory.create(td.type, params);
        if (executingTest != null) {
            getPartialResult();
            Logger.d(TestExecutor.class, "start to execute test: " + td.displayName);
            showNotification(tc.getString(R.string.ntf_running_test) + td.displayName);

            //execute the test in a new thread and kill it it it doesn't terminate after
            //Constants.WAIT_TEST_BEFORE_ABORT
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    executingTest.execute();
                }
            });
            t.start();
            t.join(Constants.WAIT_TEST_BEFORE_ABORT);
            if (t.isAlive()) {
                Logger.e(this, "Test is still runnuing after " + Constants.WAIT_TEST_BEFORE_ABORT / 1000
                        + " seconds.");
                t.interrupt();
                t = null;
            } else {
                lastTestBytes = executingTest.getNetUsage();
                result.isSuccess = executingTest.isSuccessful();
                String out = executingTest.getOutputString();
                result.addTestString(out);
                rc.addTest(executingTest.getJSONResult());
                // HACK TO INCLUDE THE JUDPJITTER RESULTS
                if (td.type.equalsIgnoreCase("latency")) {
                    String[] judp = executingTest.getOutputFields();
                    DCSStringBuilder jjitter = new DCSStringBuilder();
                    String jitter = "" + (Integer.parseInt(judp[5]) - Integer.parseInt(judp[6]));
                    String sent = "" + (Integer.parseInt(judp[9]) + Integer.parseInt(judp[10]));
                    String received = "" + (Integer.parseInt(judp[9]) - Integer.parseInt(judp[10]));
                    jjitter.append("JUDPJITTER");
                    jjitter.append(judp[1]); // TIMESTAMP
                    jjitter.append(judp[2]); // STATUS
                    jjitter.append(judp[3]); // TARGET
                    jjitter.append(judp[4]); // TARGET IP ADDRESS
                    jjitter.append(128); // PACKETSIZE
                    jjitter.append(0); // BITRATE
                    jjitter.append(0); // DURATION
                    jjitter.append(sent); // PACKETS SENT UP
                    jjitter.append(sent); // PACKETS SENT DOWN
                    jjitter.append(received); // PACKETS RECEIVED UP
                    jjitter.append(received); // PACKETS RECEIVED DOWN
                    jjitter.append(jitter); // JITTER UP
                    jjitter.append(jitter); // JITTER DOWN
                    jjitter.append(judp[5]); // AVERAGE RTT
                    result.addTestString(jjitter.build());
                }

                if (result.isSuccess) {
                    tc.paramsManager.processOutParams(out, td.outParamsDescription);
                    if (executingTest.getHumanReadable() != null) {
                        HashMap<String, String> last_values = executingTest.getHumanReadable().getValues();
                        for (String key : last_values.keySet()) {
                            String value = last_values.get(key);
                            Logger.d(TestExecutor.class, "last_" + key + " " + value);
                            AppSettings.getInstance().saveString("last_" + key, value);
                        }
                    }
                }

                Logger.d(TAG, "finished execution test: " + td.type);
            }
        } else {
            Logger.e(TAG, "Can't find test for: " + td.type, new RuntimeException());
            result.isSuccess = false;
        }
    } catch (Throwable e) {
        Logger.e(this, "Error in executing the test. ", e);
        result.isSuccess = false;
    } finally {
        cancelNotification();
    }
}

From source file:com.cfets.door.yarn.jboss.JBossApplicationMaster.java

private void finish() {
    for (Thread launchThread : launchThreads) {
        try {/*from  w  w  w .j a  v  a2s  . c  o  m*/
            launchThread.join(10000);
        } catch (InterruptedException e) {
            LOG.info("Exception thrown in thread join: " + e.getMessage());
            e.printStackTrace();
        }
    }

    LOG.info("Application completed. Stopping running containers");
    nmClientAsync.stop();

    LOG.info("Application completed. Signalling finish to RM");

    FinalApplicationStatus appStatus;
    String appMessage = null;
    success = true;
    if (numFailedContainers.get() == 0 && numCompletedContainers.get() == numTotalContainers) {
        appStatus = FinalApplicationStatus.SUCCEEDED;
    } else {
        appStatus = FinalApplicationStatus.FAILED;
        appMessage = "Diagnostics." + ", total=" + numTotalContainers + ", completed="
                + numCompletedContainers.get() + ", allocated=" + numAllocatedContainers.get() + ", failed="
                + numFailedContainers.get();
        success = false;
    }
    try {
        resourceManager.unregisterApplicationMaster(appStatus, appMessage, null);
    } catch (YarnException ex) {
        LOG.log(Level.SEVERE, "Failed to unregister application", ex);
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Failed to unregister application", e);
    }

    done = true;
    resourceManager.stop();
}