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.buaa.cfs.utils.ShutdownThreadsHelper.java

/**
 * @param thread {@link Thread to be shutdown}
 * @param timeoutInMilliSeconds time to wait for thread to join after being
 *                              interrupted
 * @return <tt>true</tt> if the thread is successfully interrupted,
 * <tt>false</tt> otherwise//  w  ww  .  j a  v a 2s .  com
 * @throws InterruptedException
 */
public static boolean shutdownThread(Thread thread, long timeoutInMilliSeconds) {
    if (thread == null) {
        return true;
    }

    try {
        thread.interrupt();
        thread.join(timeoutInMilliSeconds);
        return true;
    } catch (InterruptedException ie) {
        LOG.warn("Interrupted while shutting down thread - " + thread.getName());
        return false;
    }
}

From source file:Main.java

public static void awaitForTermination(List<Thread> threads, long timeout, TimeUnit timeUnit) {
    try {/* w w  w  .  j  a v  a2 s .  c  om*/
        long finishTime = System.currentTimeMillis() + timeUnit.toMillis(timeout);
        for (Thread t : threads) {
            long now = System.currentTimeMillis();
            if (now > finishTime) {
                throw new IllegalStateException("failed to stop all threads");
            } else {
                t.join(finishTime - now);
                if (t.isAlive()) {
                    throw new IllegalStateException("failed to stop all threads");
                }
            }
        }
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.googlecode.icegem.cacheutils.common.Utils.java

/**
 * Executes the thread with specified timeout.
 * /*from   w ww. ja v  a  2s .co  m*/
 * @param thread
 *            - the thread to execute.
 * @param timeout
 *            - the timeout.
 */
public static void execute(Thread thread, long timeout) {
    thread.start();

    try {
        thread.join(timeout);
    } catch (InterruptedException e) {
        // Should not be interrupted normally.
    }

    if (thread.isAlive()) {
        thread.interrupt();
    }
}

From source file:com.ery.estorm.util.Threads.java

/**
 * Shutdown passed thread using isAlive and join.
 * //  w  w  w .j av a 2 s .c om
 * @param joinwait
 *            Pass 0 if we're to wait forever.
 * @param t
 *            Thread to shutdown
 */
public static void shutdown(final Thread t, final long joinwait) {
    if (t == null)
        return;
    while (t.isAlive()) {
        try {
            t.join(joinwait);
        } catch (InterruptedException e) {
            LOG.warn(t.getName() + "; joinwait=" + joinwait, e);
        }
    }
}

From source file:com.ery.estorm.util.Threads.java

/**
 * @param t/*ww  w  . j  a  v a2s . c o  m*/
 *            Waits on the passed thread to die dumping a threaddump every minute while its up.
 * @throws InterruptedException
 */
public static void threadDumpingIsAlive(final Thread t) throws InterruptedException {
    if (t == null) {
        return;
    }

    while (t.isAlive()) {
        t.join(60 * 1000);
        if (t.isAlive()) {
            ReflectionUtils.printThreadInfo(new PrintWriter(System.out),
                    "Automatic Stack Trace every 60 seconds waiting on " + t.getName());
        }
    }
}

From source file:mServer.upload.MserverFtp.java

public static boolean uploadFtp(String srcPathFile_, String destFileName_, MserverDatenUpload datenUpload_) {
    try {//from  w  ww  .  j  a  v a 2s  . c o  m
        srcPathFile = srcPathFile_;
        destFileName = destFileName_;
        datenUpload = datenUpload_;
        server = datenUpload.arr[MserverDatenUpload.UPLOAD_SERVER_NR];
        strPort = datenUpload.arr[MserverDatenUpload.UPLOAD_PORT_NR];
        username = datenUpload.arr[MserverDatenUpload.UPLOAD_USER_NR];
        password = datenUpload.arr[MserverDatenUpload.UPLOAD_PWD_NR];
        MserverLog.systemMeldung("");
        MserverLog.systemMeldung("----------------------");
        MserverLog.systemMeldung("Upload start");
        MserverLog.systemMeldung("Server: " + server);
        Thread t = new Thread(new Ftp());
        t.start();

        int warten = MserverKonstanten.MAX_WARTEN_FTP_UPLOAD /*Minuten*/;
        MserverLog.systemMeldung("Max Laufzeit FTP[Min]: " + warten);
        MserverLog.systemMeldung("-----------------------------------");
        warten = 1000 * 60 * warten;
        t.join(warten);

        if (t != null) {
            if (t.isAlive()) {
                MserverLog.fehlerMeldung(396958702, MserverFtp.class.getName(),
                        "Der letzte FtpUpload luft noch");
                MserverLog.systemMeldung("und wird gekillt");
                t.stop();
                retFtp = false;
            }
        }
    } catch (Exception ex) {
        MserverLog.fehlerMeldung(739861047, MserverFtp.class.getName(), "uploadFtp", ex);
    }
    return retFtp;
}

From source file:es.darkhogg.hazelnutt.Hazelnutt.java

/**
 * Terminates the application in at most <i>time</i> milliseconds for
 * every alive thread. /* w ww .  j  a va 2 s . c om*/
 * 
 * @param time Number of milliseconds to wait for each thread to terminate
 */
public static void terminate(long time) {
    Logger logger = getLogger();
    logger.info("Terminating application...");

    try {
        getFrame().dispose();

        // Get the root thread group
        ThreadGroup rootThreadGroup = Thread.currentThread().getThreadGroup();
        while (rootThreadGroup.getParent() != null) {
            rootThreadGroup = rootThreadGroup.getParent();
        }

        // Declare some collections
        Queue<ThreadGroup> threadGroups = new LinkedList<ThreadGroup>();
        Queue<Thread> threads = new LinkedList<Thread>();

        // Get ALL groups
        threadGroups.add(rootThreadGroup);
        while (!threadGroups.isEmpty()) {
            ThreadGroup group = threadGroups.remove();

            Thread[] subThreads = new Thread[group.activeCount() * 2];
            //group.enumerate( subThreads );
            for (Thread subThread : subThreads) {
                if (subThread != null) {
                    threads.add(subThread);
                }
            }

            ThreadGroup[] subThreadGroups = new ThreadGroup[group.activeGroupCount() * 2];
            for (ThreadGroup subThreadGroup : subThreadGroups) {
                if (subThreadGroup != null) {
                    threadGroups.add(subThreadGroup);
                }
            }
        }

        // Join a maximum of time milliseconds for all non-daemon threads
        while (!threads.isEmpty()) {
            Thread thread = threads.remove();
            LOGGER.trace(thread);

            if (!thread.isDaemon() && thread != Thread.currentThread()) {
                logger.trace("Waiting for thread '" + thread.getName() + "'");
                thread.join(time);
                if (thread.isAlive()) {
                    logger.trace("Interrupting thread '" + thread.getName() + "'");
                    thread.interrupt();
                }
            }
        }

    } catch (Throwable e) {
        LOGGER.warn("Interrupted while terminating application", e);

    } finally {
        // Exit the program
        System.exit(0);
    }
}

From source file:net.sf.sahi.util.Utils.java

public static String executeCommand(final String command, boolean isSync, long timeout) throws Exception {
    final RunnableWithResult runnable = new RunnableWithResult(command);
    final Thread thread = new Thread(runnable);
    thread.start();/*ww w .  ja  v a  2s. c o m*/
    if (isSync)
        thread.join(timeout);
    return runnable.getResult();
}

From source file:net.sf.taverna.t2.servicedescriptions.impl.ServiceDescriptionRegistryImpl.java

private static void joinThreads(Collection<? extends Thread> threads, long descriptionThreadTimeoutMs) {
    long finishJoinBy = currentTimeMillis() + descriptionThreadTimeoutMs;
    for (Thread thread : threads) {
        // No shorter timeout than 1 ms (thread.join(0) waits forever!)
        long timeout = Math.max(1, finishJoinBy - currentTimeMillis());
        try {/*from   w w  w.j a va  2  s .c  o  m*/
            thread.join(timeout);
        } catch (InterruptedException e) {
            currentThread().interrupt();
            return;
        }
        if (thread.isAlive())
            logger.debug("Thread did not finish " + thread);
    }
}

From source file:com.discursive.jccook.collections.lazy.StockQuoteTransformer.java

public Object transform(Object symbol) {
    QuoteRetriever retriever = new QuoteRetriever((String) symbol);

    try {/*from  w ww . java 2  s  .  com*/
        Thread retrieveThread = new Thread(retriever);
        retrieveThread.start();
        retrieveThread.join(timeout);
    } catch (InterruptedException ie) {
        System.out.println("Quote request timed out.");
    }

    return retriever.getResult();
}