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 void join() throws InterruptedException 

Source Link

Document

Waits for this thread to die.

Usage

From source file:com.mirth.connect.donkey.server.channel.DestinationConnector.java

public void halt() throws ConnectorTaskException, InterruptedException {
    updateCurrentState(DeployedState.STOPPING);

    if (MapUtils.isNotEmpty(queueThreads)) {
        for (Thread thread : queueThreads.values()) {
            thread.interrupt();/*from   w  w w . j  av  a 2s.co m*/
        }
    }

    try {
        onHalt();
    } finally {
        if (MapUtils.isNotEmpty(queueThreads)) {
            try {
                for (Thread thread : queueThreads.values()) {
                    thread.join();
                }

                queueThreads.clear();
            } finally {
                // Invalidate the queue's buffer when the queue is stopped to prevent the buffer becoming 
                // unsynchronized with the data store.
                queue.invalidate(false, true);
            }
        }

        channel.getEventDispatcher().dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.IDLE));
        updateCurrentState(DeployedState.STOPPED);
    }
}

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

/**
 * Checks that the buffer will block when having no messages and continues when the first message arrives
 *
 * @throws InterruptedException/*from  w  w w  . j  a  v  a2  s.c  o  m*/
 */
@Test
public void testConsumerBlocking() throws InterruptedException {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            buffer.drain();
        }
    });
    thread.start();

    // draining the buffer should block since it is empty
    waitForThreadStateToBe(thread, Thread.State.WAITING);
    Assert.assertEquals("reading thread should be in a waiting state when inserting to full buffer",
            Thread.State.WAITING, thread.getState());

    // insert 2 new messages
    Message[] messages = new Message[] { new DummyMsg1(), new DummyMsg2() };
    buffer.put(messages);

    // thread should be released now
    waitForThreadStateToBe(thread, Thread.State.TERMINATED);
    Assert.assertEquals("reading thread should be in a terminated after a message was inserted to the buffer",
            Thread.State.TERMINATED, thread.getState());

    thread.join();
    verify(dispatcherService).dispatch(
            (List<? extends Serializable>) argThat(new MessagesSizeMatcher(Arrays.asList(messages))),
            anyString(), anyString(), anyString());
}

From source file:com.thoughtworks.go.server.service.BackupServiceIntegrationTest.java

@Test
public void shouldReturnBackupRunningSinceValue_inISO8601_format() throws InterruptedException {
    assertThat(backupService.backupRunningSinceISO8601(), is(Optional.empty()));

    final Semaphore waitForBackupToStart = new Semaphore(1);
    final Semaphore waitForAssertionToCompleteWhileBackupIsOn = new Semaphore(1);
    final BackupUpdateListener backupUpdateListener = new BackupUpdateListener() {
        private boolean backupStarted = false;

        @Override//  w  w  w .ja va  2 s. c om
        public void updateStep(BackupProgressStatus step) {
            if (!backupStarted) {
                backupStarted = true;
                waitForBackupToStart.release();
                try {
                    waitForAssertionToCompleteWhileBackupIsOn.acquire();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        @Override
        public void error(String message) {
        }

        @Override
        public void completed() {
        }
    };

    waitForAssertionToCompleteWhileBackupIsOn.acquire();
    waitForBackupToStart.acquire();
    Thread backupThd = new Thread(() -> backupService.startBackup(admin, backupUpdateListener));

    backupThd.start();
    waitForBackupToStart.acquire();
    String backupStartedTimeString = backupService.backupRunningSinceISO8601().get();
    DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTime();
    DateTime backupTime = dateTimeFormatter.parseDateTime(backupStartedTimeString);

    ServerBackup runningBackup = (ServerBackup) ReflectionUtil.getField(backupService, "runningBackup");
    assertThat(new DateTime(runningBackup.getTime()), is(backupTime));
    waitForAssertionToCompleteWhileBackupIsOn.release();
    backupThd.join();
}

From source file:org.apache.ignite.yardstick.cache.load.IgniteCacheRandomOperationBenchmark.java

/**
 * @throws Exception If fail.//  www .  j av a 2 s .com
 */
private void preLoading() throws Exception {
    if (args.preloadAmount() > args.range())
        throw new IllegalArgumentException("Preloading amount (\"-pa\", \"--preloadAmount\") "
                + "must by less then the range (\"-r\", \"--range\").");

    startPreloadLogging(args.preloadLogsInterval());

    Thread[] threads = new Thread[availableCaches.size()];

    for (int i = 0; i < availableCaches.size(); i++) {
        final String cacheName = availableCaches.get(i).getName();

        threads[i] = new Thread() {
            @Override
            public void run() {
                try (IgniteDataStreamer<Object, Object> dataLdr = ignite().dataStreamer(cacheName)) {
                    for (int i = 0; i < args.preloadAmount() && !isInterrupted(); i++)
                        dataLdr.addData(createRandomKey(i, cacheName), createRandomValue(i, cacheName));
                }
            }
        };

        threads[i].start();
    }

    for (Thread thread : threads)
        thread.join();

    stopPreloadLogging();
}

From source file:com.nridge.core.app.mgr.AppMgr.java

/**
 * Executes one or more application tasks based on the the run/test command
 * line argument./*from  ww w .j a v  a 2  s  .c  om*/
 * <p>
 * <b>Note:</b>If the word "all" is specified for the run/test argument
 * parameter, then all tasks defined for this application manager
 * will be executed in parallel.  Otherwise, only the task that matches
 * the run/test name will be executed.
 * </p>
 *
 * @throws NSException Could be thrown by the executing task.
 */
public void execute() throws NSException {
    Thread appThread;
    Logger appLogger = getLogger(this, "execute");

    appLogger.trace(LOGMSG_TRACE_ENTER);

    if (mTaskList == null)
        throw new NSException("The task list is undefined and cannot be executed.");

    if (mIsAbortHandlerEnabled) {
        Runtime osRuntime = Runtime.getRuntime();
        osRuntime.addShutdownHook(new TaskAbort(this, mTaskList));
    }

    // http://www.vogella.com/articles/JavaConcurrency/article.html

    if (mCmdLine.hasOption("run")) {
        String taskName = mCmdLine.getOptionValue("run");
        if (taskName.equals(CMDARG_RUNALL_TASKS)) {
            ArrayList<Thread> threadList = new ArrayList<Thread>();
            for (Task appTask : mTaskList) {
                appTask.init(this);
                appThread = new Thread(appTask);
                threadList.add(appThread);
                appThread.start();
            }

            // Next, we will wait for each task thread to complete.

            for (Thread thread : threadList) {
                try {
                    thread.join();
                } catch (InterruptedException e) {
                    appLogger.warn("Interrupted Thread: " + e.getMessage());
                }
            }
        } else {
            Task appTask = getTaskByRunName(taskName);
            if (appTask != null) {
                appTask.init(this);
                appTask.run();
            }
        }
    } else {
        if (mCmdLine.hasOption("test")) {
            String taskName = mCmdLine.getOptionValue("test");
            if (taskName.equals(CMDARG_TESTALL_TASKS)) {
                for (Task appTask : mTaskList) {
                    appTask.init(this);
                    appTask.test();
                }
            } else {
                Task appTask = getTaskByTestName(taskName);
                if (appTask != null) {
                    appTask.init(this);
                    appTask.test();
                }
            }
        }
    }

    appLogger.trace(LOGMSG_TRACE_DEPART);
}

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

/**
 * checks that when inserting messages to a full buffer,
 * the inserting thread will block until the buffer is emptied
 *
 * @throws InterruptedException//w  w  w .j av  a2 s. co m
 */
@Test
public void testProducerBlocking() throws InterruptedException {
    // buffer capacity is 10, put messages in it until it is full
    while (buffer.getWeight() < MAX_BUFFER_WEIGHT) {
        buffer.put(new DummyMsg1());
    }

    // the next insert to buffer will block because it's full, do it on a different thread
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                buffer.put(new DummyMsg1());
            } catch (InterruptedException e) {
                //ignore
            }
        }
    });
    thread.start();

    // wait for that thread to block
    waitForThreadStateToBe(thread, Thread.State.WAITING);
    Assert.assertEquals("inserting thread should be in a waiting state when inserting to full buffer",
            Thread.State.WAITING, thread.getState());

    // drain the buffer -> will send the first 10 messages and release the blocking thread
    buffer.drain();
    waitForThreadStateToBe(thread, Thread.State.TERMINATED);
    Assert.assertEquals("inserting thread should be in a terminated state after inserting to buffer",
            Thread.State.TERMINATED, thread.getState());
    thread.join();
}

From source file:com.facebook.LinkBench.LinkBenchDriverInj.java

void sendrequests() throws IOException, InterruptedException, Throwable {

    if (!doRequest) {
        logger.info("Skipping request phase per the cmdline arg");
        return;//  w w w  . j ava 2 s  . c  om
    }

    // config info for requests
    nrequesters = ConfigUtil.getInt(props, Config.NUM_REQUESTERS);
    if (nrequesters == 0) {
        logger.info("NO REQUEST PHASE CONFIGURED. ");
        return;
    }
    List<LinkBenchRequestInj> requesters = new LinkedList<LinkBenchRequestInj>();

    RequestProgress progress = LinkBenchRequestInj.createProgress(logger, props);

    Random masterRandom = createMasterRNG(props, Config.REQUEST_RANDOM_SEED);
    requestrate = ConfigUtil.getLong(props, Config.REQUEST_RATE, 0L);
    maxTime = ConfigUtil.getLong(props, Config.MAX_TIME);

    genQueue = new ArrayBlockingQueue<Long>(1000000); // 10000 should be in Config really. TODO

    statsQueue = new ArrayBlockingQueue<StatMessage>(1000000); // 1000000 should be in Config. TODO

    // create GlobalStats thread

    GlobalStats gs = new GlobalStats(statsQueue, props, csvStreamFile);
    Thread t = new Thread(gs, "Global Stats Thread");
    t.start();

    // create requesters
    for (int i = 0; i < nrequesters; i++) {
        Stores stores = initStores();
        LinkBenchRequestInj l = new LinkBenchRequestInj(stores.linkStore, stores.nodeStore, props,
                csvStreamFile, progress, new Random(masterRandom.nextLong()), i, nrequesters, genQueue,
                statsQueue);
        requesters.add(l);
    }
    progress.startTimer();
    // run requesters
    concurrentExec(requesters, true, new Random(masterRandom.nextLong()));

    // stop Thread with global statistics
    t.interrupt();
    t.join();
    gs.printQuantileStats();

    long finishTime = System.currentTimeMillis();
    // Calculate duration accounting for warmup time
    long benchmarkTime = finishTime - progress.getBenchmarkStartTime();

    long requestsdone = 0;
    int abortedRequesters = 0;
    // wait for requesters
    for (LinkBenchRequestInj requester : requesters) {
        requestsdone += requester.getRequestsDone();
        if (requester.didAbort()) {
            abortedRequesters++;
        }
    }

    logger.info("REQUEST PHASE COMPLETED. " + requestsdone + " requests done in " + (benchmarkTime / 1000)
            + " seconds." + " Requests/second = " + (1000 * requestsdone) / benchmarkTime);
    if (abortedRequesters > 0) {
        logger.error(String.format(
                "Benchmark did not complete cleanly: %d/%d "
                        + "request threads aborted.  See error log entries for details.",
                abortedRequesters, nrequesters));
    }
}

From source file:org.opencron.server.service.ExecuteService.java

/**
 * ??/*from   w w  w  . j a v a 2  s  .c  o m*/
 */
private boolean executeSameTimeJob(final long groupId, final Queue<JobVo> jobQueue) {
    final List<Boolean> result = new ArrayList<Boolean>(0);
    Thread jobThread = new Thread(new Runnable() {
        @Override
        public void run() {
            for (final JobVo jobVo : jobQueue) {
                //?(?,??)
                Thread thread = new Thread(new Runnable() {
                    public void run() {
                        result.add(doFlowJob(jobVo, groupId));
                    }
                });
                thread.start();
            }
        }
    });
    jobThread.start();
    //?,?...
    try {
        jobThread.join();
    } catch (InterruptedException e) {
        logger.error("[opencron] job rumModel with SAMETIME error:{}", e.getMessage());
    }
    return !result.contains(false);
}

From source file:com.barchart.netty.server.http.TestHttpServer.java

@Test
public void testShutdown() throws Exception {

    final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    final AtomicBoolean pass = new AtomicBoolean(false);

    final Thread t = new Thread(new Runnable() {

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

            try {
                Thread.sleep(1000);
                server.shutdown();
            } catch (final InterruptedException e1) {
                e1.printStackTrace();
            }

            try {
                client.execute(new HttpGet("http://localhost:" + port + "/basic"));
            } catch (final HttpHostConnectException hhce) {
                pass.set(true);
            } catch (final Exception e) {
                e.printStackTrace();
            }

        }

    });

    t.start();

    final HttpGet get = new HttpGet("http://localhost:" + port + "/client-disconnect");
    final HttpResponse response = client.execute(get);
    EntityUtils.consume(response.getEntity());
    assertEquals(200, response.getStatusLine().getStatusCode());

    t.join();

    assertTrue(pass.get());

}