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:no.difi.sdp.client.asice.signature.CreateSignatureTest.java

@Test
public void multithreaded_signing() throws Exception {
    List<Thread> threads = new ArrayList<Thread>();
    final AtomicInteger fails = new AtomicInteger(0);
    for (int i = 0; i < 50; i++) {
        Thread t = new Thread() {
            @Override//from   w ww  .j  a  v a2 s.co  m
            public void run() {
                for (int j = 0; j < 20; j++) {
                    Signature signature = sut.createSignature(noekkelpar, files);
                    if (!verify_signature(signature)) {
                        fails.incrementAndGet();
                    }
                    if (fails.get() > 0) {
                        break;
                    }
                }
            }
        };
        threads.add(t);
        t.start();
    }
    for (Thread t : threads) {
        t.join();
    }
    if (fails.get() > 0) {
        fail("Signature validation failed");
    }
}

From source file:com.fujitsu.dc.test.jersey.concurrent.ConcurrentODataRequestTest.java

() throws InterruptedException {
    // ????// ww w  .j  ava2s  .c o  m
    this.createRoleRequest(NEW_ROLE_NAME, BOX_NAME).returns();
    // 
    final Counters counters = new Counters();
    // ??
    List<Thread> listThread = new ArrayList<Thread>();
    for (int i = 0; i < NUM_CONCURRENCY; i++) {
        final Http theReq = this.updateRoleRequest(NEW_ROLE_NAME, BOX_NAME, NEW_ROLE_NAME_2);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                // 
                TResponse resp = theReq.returns();
                log.debug("Status Code = " + resp.getStatusCode());
                // ?
                if (HttpStatus.SC_NO_CONTENT == resp.getStatusCode()) {
                    counters.incSuccess();
                } else if (HttpStatus.SC_SERVICE_UNAVAILABLE == resp.getStatusCode()) {
                    counters.incOverflow();
                } else {
                    counters.incFailure();
                }
            }
        };
        Thread t = new Thread(runnable);
        listThread.add(t);
    }
    // ??
    try {
        // ???
        for (Thread t : listThread) {
            t.start();
        }
        // ?
        for (Thread t : listThread) {
            t.join();
        }
        // ??
        counters.debugPrint();
        // ????????
        counters.assertTotalCount(NUM_CONCURRENCY);
        // ???????????
        counters.assertSuccessCount(1);
    } finally {
        // ?
        this.deleteRoleRequest(NEW_ROLE_NAME_2, BOX_NAME).returns().statusCode(HttpStatus.SC_NO_CONTENT);
        // ???204???
    }
}

From source file:com.persinity.ndt.datamutator.DataMutator.java

/**
 * Will block calling thread until all loaders are done.
 *///ww  w .  ja  v a2s.c o m
public void waitToFinish() {
    log.info("Waiting to finish {} threads...", threads.size());

    view.start();
    startStatusDumpTask();

    while (true) {
        Thread aliveTh = null;
        synchronized (lock) {
            for (Thread th : threads) {
                if (th.isAlive()) {
                    aliveTh = th;
                    break;
                }
            }
        }

        if (aliveTh == null) {
            break;
        }

        try {
            aliveTh.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    scheduler.shutdown();
    entityFactory.close();

    log.info("All threads DONE.");
    view.logMsg("Load done");
}

From source file:eu.stratosphere.nephele.taskmanager.runtime.EnvelopeConsumptionLog.java

void finish() {

    synchronized (this) {

        if (this.announcedEnvelopesAsIntBuffer.position() == 0) {
            return;
        }/*  ww w . ja  v  a  2  s . c om*/
    }

    final EnvelopeConsumptionLog lock = this;

    // Run this in a separate thread, so we will be distributed by the thread trying to interrupt this
    // thread. However, wait for the thread to finish.

    final Thread finisherThread = new Thread("Log finisher for " + this.environment.getTaskNameWithIndex()) {

        /**
         * {@inheritDoc}
         */
        @Override
        public void run() {

            synchronized (lock) {
                writeAnnouncedEnvelopesBufferToDisk();
            }
        }
    };

    finisherThread.start();

    boolean regularExit = false;
    while (!regularExit) {
        try {
            finisherThread.join();
            regularExit = true;
        } catch (InterruptedException ie) {
        }
    }
}

From source file:org.apache.camel.component.mongodb.MongoDbTailableCursorConsumerTest.java

@Test
public void testCustomTailTrackLocation() throws Exception {
    assertEquals(0, cappedTestCollection.count());
    final MockEndpoint mock = getMockEndpoint("mock:test");

    // get the custom tracking collection and drop it (tailTrackDb=einstein&tailTrackCollection=curie&tailTrackField=newton)
    DBCollection trackingCol = mongo.getDB("einstein").getCollection("curie");
    trackingCol.drop();/*from   ww  w  .  j a v a2  s .co  m*/
    trackingCol = mongo.getDB("einstein").getCollection("curie");

    // create a capped collection with max = 1000
    cappedTestCollection = db.createCollection(cappedTestCollectionName,
            BasicDBObjectBuilder.start().add("capped", true).add("size", 1000000000).add("max", 1000).get());

    addTestRoutes();
    context.startRoute("tailableCursorConsumer3");

    mock.expectedMessageCount(300);
    // pump 300 records
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 1; i <= 300; i++) {
                cappedTestCollection.insert(
                        BasicDBObjectBuilder.start("increasing", i).add("string", "value" + i).get(),
                        WriteConcern.SAFE);
            }
        }
    });

    // start the data pumping
    t.start();
    // before we continue wait for the data pump to end
    t.join();
    mock.assertIsSatisfied();
    mock.reset();

    // stop the route to ensure that our lastVal is persisted, and check it
    context.stopRoute("tailableCursorConsumer3");
    // ensure that the persisted lastVal is 300, newton is the name of the trackingField we are using
    assertEquals(300, trackingCol.findOne(new BasicDBObject("persistentId", "darwin")).get("newton"));
    context.startRoute("tailableCursorConsumer3");

    // expect 300 messages and not 600
    mock.expectedMessageCount(300);
    // pump 300 records
    t = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 301; i <= 600; i++) {
                cappedTestCollection.insert(
                        BasicDBObjectBuilder.start("increasing", i).add("string", "value" + i).get(),
                        WriteConcern.SAFE);
            }
        }
    });
    // start the data pumping
    t.start();
    // before we continue wait for the data pump to end
    t.join();
    mock.assertIsSatisfied();
    // check that the first received body contains increasing=301 and not increasing=1, i.e. it's not starting from the top
    Object firstBody = mock.getExchanges().get(0).getIn().getBody();
    assertTrue(firstBody instanceof DBObject);
    assertEquals(301, ((DBObject) firstBody).get("increasing"));
    // check that the persisted lastVal after stopping the route is 600, newton is the name of the trackingField we are using
    context.stopRoute("tailableCursorConsumer3");
    assertEquals(600, trackingCol.findOne(new BasicDBObject("persistentId", "darwin")).get("newton"));

}

From source file:org.apache.camel.component.mongodb.MongoDbTailableCursorConsumerTest.java

@Test
public void testPersistentTailTrack() throws Exception {
    assertEquals(0, cappedTestCollection.count());
    final MockEndpoint mock = getMockEndpoint("mock:test");

    // drop the tracking collection
    db.getCollection(MongoDbTailTrackingConfig.DEFAULT_COLLECTION).drop();
    // create a capped collection with max = 1000
    cappedTestCollection = db.createCollection(cappedTestCollectionName,
            BasicDBObjectBuilder.start().add("capped", true).add("size", 1000000000).add("max", 1000).get());
    cappedTestCollection.ensureIndex("increasing");

    addTestRoutes();/*from w  ww .ja va  2  s. co m*/
    context.startRoute("tailableCursorConsumer2");

    mock.expectedMessageCount(300);
    // pump 300 records
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 1; i <= 300; i++) {
                cappedTestCollection.insert(
                        BasicDBObjectBuilder.start("increasing", i).add("string", "value" + i).get(),
                        WriteConcern.SAFE);
            }
        }
    });

    // start the data pumping
    t.start();
    // before we continue wait for the data pump to end
    t.join();
    mock.assertIsSatisfied();
    mock.reset();
    context.stopRoute("tailableCursorConsumer2");
    while (context.getRouteStatus("tailableCursorConsumer2") != ServiceStatus.Stopped) {
    }
    context.startRoute("tailableCursorConsumer2");

    // expect 300 messages and not 600
    mock.expectedMessageCount(300);
    // pump 300 records
    t = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 301; i <= 600; i++) {
                cappedTestCollection.insert(
                        BasicDBObjectBuilder.start("increasing", i).add("string", "value" + i).get(),
                        WriteConcern.SAFE);
            }
        }
    });
    // start the data pumping
    t.start();
    // before we continue wait for the data pump to end
    t.join();
    mock.assertIsSatisfied();

    // check that the first message received in this second batch corresponds to increasing=301
    Object firstBody = mock.getExchanges().get(0).getIn().getBody();
    assertTrue(firstBody instanceof DBObject);
    assertEquals(301, ((DBObject) firstBody).get("increasing"));

    // check that the lastVal is persisted at the right time: check before and after stopping the route
    assertEquals(300, db.getCollection(MongoDbTailTrackingConfig.DEFAULT_COLLECTION)
            .findOne(new BasicDBObject("persistentId", "darwin")).get("lastTrackingValue"));
    // stop the route and verify the last value has been updated
    context.stopRoute("tailableCursorConsumer2");
    while (context.getRouteStatus("tailableCursorConsumer2") != ServiceStatus.Stopped) {
    }
    assertEquals(600, db.getCollection(MongoDbTailTrackingConfig.DEFAULT_COLLECTION)
            .findOne(new BasicDBObject("persistentId", "darwin")).get("lastTrackingValue"));

}

From source file:ezbake.security.service.processor.EzSecurityClientThreadSafetyIT.java

@Test
@Ignore//from ww  w.  j a  v  a2 s.  c o  m
public void threadedAppInfo() throws InterruptedException {
    List<Thread> threads = new ArrayList<Thread>();
    for (int i = 0; i < 100; ++i) {
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    ProxyPrincipal dn = getSignedPrincipal(DN);
                    EzSecurityToken info = ezbakeSecurityClient.fetchTokenForProxiedUser(dn, null);
                } catch (PKeyCryptoException e) {
                    e.printStackTrace();
                } catch (EzSecurityTokenException e) {
                    e.printStackTrace();
                } catch (TException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
        t.start();
        threads.add(t);
    }

    for (Thread t : threads) {
        t.join();
    }

    threads.clear();

    for (int i = 0; i < 100; ++i) {
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    ProxyPrincipal dn = getSignedPrincipal(DN);
                    EzSecurityToken info = ezbakeSecurityClient.fetchTokenForProxiedUser(dn, null);
                } catch (PKeyCryptoException e) {
                    e.printStackTrace();
                } catch (EzSecurityTokenException e) {
                    e.printStackTrace();
                } catch (TException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
        threads.add(t);
    }

    for (Thread t : threads) {
        t.join();
    }

}

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 w  w  .  j  a v a2  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.zavakid.mushroom.impl.TestSinkQueue.java

/**
 * Test blocking when queue is empty/*  w  ww .  j  a va  2 s  . com*/
 * 
 * @throws Exception
 */
@Test
public void testEmptyBlocking() throws Exception {
    final SinkQueue<Integer> q = new SinkQueue<Integer>(2);
    final Runnable trigger = mock(Runnable.class);
    // try consuming emtpy equeue and blocking
    Thread t = new Thread() {

        @Override
        public void run() {
            try {
                assertEquals("element", 1, (int) q.dequeue());
                q.consume(new Consumer<Integer>() {

                    public void consume(Integer e) {
                        assertEquals("element", 2, (int) e);
                        trigger.run();
                    }
                });
            } catch (InterruptedException e) {
                LOG.warn("Interrupted", e);
            }
        }
    };
    t.start();
    Thread.yield(); // Let the other block
    q.enqueue(1);
    q.enqueue(2);
    t.join();
    verify(trigger).run();
}

From source file:com.thoughtworks.cruise.util.command.CommandLine.java

public boolean runScript(Script script, long timeout, StreamConsumer buildOutputConsumer,
        EnvironmentVariableContext environmentVariableContext) throws CheckedCommandLineException {
    LOG.info("Running command: " + toStringForDisplay());

    StreamConsumer consumerForError = new SafeStreamConsumer(
            new CompositeConsumer(StreamLogger.getWarnLogger(LOG), buildOutputConsumer), getArguments());
    StreamConsumer consumerForOut = new SafeStreamConsumer(
            new CompositeConsumer(StreamLogger.getInfoLogger(LOG), buildOutputConsumer), getArguments());
    //TODO: The build output buffer doesn't take into account Cruise running in multi-threaded mode.

    Process p;/*from   www  .  j  av a 2 s . com*/
    int exitCode = -1;

    try {
        ConsoleOutputStreamConsumer outputStreamConsumer = new ConsoleOutputStreamConsumer(buildOutputConsumer,
                buildOutputConsumer);
        p = startProcess(environmentVariableContext, outputStreamConsumer);
    } catch (CommandLineException e) {
        String msg = "Error happend while attempting to execute '" + toStringForDisplay()
                + "'. \nPlease make sure [" + getExecutable() + "] can be executed on this agent.\n";
        consumerForError.consumeLine(msg);
        throw new CheckedCommandLineException(msg, e);
    } catch (IOException e) {
        String msg = "Encountered an IO exception while attempting to execute '" + toStringForDisplay()
                + "'. Cruise cannot continue.\n";
        consumerForError.consumeLine(msg);
        throw new CheckedCommandLineException(msg, e);
    }

    StreamPumper errorPumper = new StreamPumper(p.getErrorStream(), consumerForError, "", encoding);
    StreamPumper outPumper = new StreamPumper(p.getInputStream(), consumerForOut, "", encoding);

    Thread stderr = new Thread(errorPumper);
    stderr.start();
    Thread stdout = new Thread(outPumper);
    stdout.start();
    AsyncKiller killer = new AsyncKiller(p, timeout);
    if (timeout > 0) {
        killer.start();
    }

    try {
        exitCode = p.waitFor();
        killer.interrupt();
        stderr.join();
        stdout.join();
    } catch (InterruptedException e) {
        LOG.info("Was interrupted while waiting for script to finish."
                + " Cruise will continue, assuming that it completed");
    } finally {
        IO.close(p);
    }

    script.setExitCode(exitCode);

    return !killer.processKilled();

}