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:android.core.SSLSocketTest.java

/**
 * Implements the actual test case. Launches a server and a client, requires
 * client authentication and checks the certificates afterwards (not in the
 * usual sense, we just make sure that we got the expected certificates,
 * because our self-signed test certificates are not valid.)
 *//*ww w. j a  v  a  2  s  . c  o  m*/
public void testClientAuth() {
    try {
        TestServer server = new TestServer(8088, true, TestServer.CLIENT_AUTH_WANTED);
        TestClient client = new TestClient(8088, true);

        Thread serverThread = new Thread(server);
        Thread clientThread = new Thread(client);

        serverThread.start();
        clientThread.start();

        serverThread.join();
        clientThread.join();

        // The server must have completed without an exception.
        if (server.getException() != null) {
            throw new RuntimeException(server.getException());
        }

        // The client must have completed without an exception.
        if (client.getException() != null) {
            throw new RuntimeException(client.getException());
        }

        // Caution: The clientChain is the certificate chain from our
        // client object. It contains the server certificates, of course!
        X509Certificate[] clientChain = client.getChain();
        assertTrue("Client cert chain must not be null", clientChain != null);
        assertTrue("Client cert chain must not be empty", clientChain.length != 0);
        assertEquals("CN=Test Server, OU=Android, O=Google, L=MTV, ST=California, C=US",
                clientChain[0].getSubjectDN().toString());
        // Important part ------^

        // Caution: The serverChain is the certificate chain from our
        // server object. It contains the client certificates, of course!
        X509Certificate[] serverChain = server.getChain();
        assertTrue("Server cert chain must not be null", serverChain != null);
        assertTrue("Server cert chain must not be empty", serverChain.length != 0);
        assertEquals("CN=Test Client, OU=Android, O=Google, L=MTV, ST=California, C=US",
                serverChain[0].getSubjectDN().toString());
        // Important part ------^

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:tools.datasync.db2db.net.TCPConnection.java

public void initiate() {
    try {/*  w w  w. j  av a  2 s  .co m*/
        if (serverPort == 0) {
            serverPort = 9991;
            syncPeerIp = "127.0.0.1";
            syncPeerPort = 7771;
        }
        logger.info("Initializing with serverPort=[" + serverPort + "], syncPeerIp=[" + syncPeerIp
                + "], syncPeerPort=[" + syncPeerPort + "]");

        Thread connectionThread = null;
        if ("A".equalsIgnoreCase(peerName)) {
            logger.info("Starting TCP server listener thread... Peer: " + peerName);
            TCPServerListener server_ = new TCPServerListener(serverPort);
            connectionThread = new Thread(server_);
        } else {
            int temp = serverPort;
            serverPort = syncPeerPort;
            syncPeerPort = temp;

            logger.info("Starting TCP client listener thread...");
            TCPClientListener client_ = new TCPClientListener(syncPeerIp, syncPeerPort);
            connectionThread = new Thread(client_);
        }

        connectionThread.start();
        // Wait until connection is established...
        logger.info("Waiting until connection is established...");
        connectionThread.join();

        logger.info("Connection established... Starting the input reader thread...");
        TCPInputReader inputReader = new TCPInputReader(inStream);
        Thread inputReaderThread = new Thread(inputReader);
        inputReaderThread.start();
    } catch (Exception ex) {
        exceptionHandler.handle(ex, Level.SEVERE, "Exception occured while initializing");
    }
}

From source file:com.inmobi.grill.server.query.QueryExecutionServiceImpl.java

public synchronized void stop() {
    super.stop();
    querySubmitter.interrupt();/*from   www .j av  a 2 s  .  c om*/
    statusPoller.interrupt();
    queryPurger.interrupt();
    prepareQueryPurger.interrupt();

    for (Thread th : new Thread[] { querySubmitter, statusPoller, queryPurger, prepareQueryPurger }) {
        try {
            th.join();
        } catch (InterruptedException e) {
            LOG.error("Error waiting for thread: " + th.getName(), e);
        }
    }
    LOG.info("Query execution service stopped");
}

From source file:com.datatorrent.stram.engine.GenericNodeTest.java

@SuppressWarnings("SleepWhileInLoop")
private void testDoubleCheckpointHandling(ProcessingMode processingMode) throws Exception {
    WindowGenerator windowGenerator = new WindowGenerator(new ScheduledThreadPoolExecutor(1, "WindowGenerator"),
            1024);/* w ww. j  a va2  s  . com*/
    windowGenerator.setResetWindow(0L);
    windowGenerator.setFirstWindow(0L);
    windowGenerator.setWindowWidth(100);
    windowGenerator.setCheckpointCount(1, 0);

    GenericCheckpointOperator gco = new GenericCheckpointOperator();
    DefaultAttributeMap dam = new DefaultAttributeMap();
    dam.put(OperatorContext.APPLICATION_WINDOW_COUNT, 2);
    dam.put(OperatorContext.CHECKPOINT_WINDOW_COUNT, 2);
    dam.put(OperatorContext.PROCESSING_MODE, processingMode);

    final GenericNode in = new GenericNode(gco, new com.datatorrent.stram.engine.OperatorContext(0, dam, null));
    in.setId(1);

    TestSink testSink = new TestSink();

    in.connectInputPort("ip1", windowGenerator.acquireReservoir(String.valueOf(in.id), 1024));
    in.connectOutputPort("output", testSink);
    in.firstWindowMillis = 0;
    in.windowWidthMillis = 100;

    windowGenerator.activate(null);

    final AtomicBoolean ab = new AtomicBoolean(false);
    Thread t = new Thread() {
        @Override
        public void run() {
            ab.set(true);
            in.activate();
            in.run();
            in.deactivate();
        }
    };

    t.start();

    long startTime = System.currentTimeMillis();
    long endTime = 0;

    while (gco.numWindows < 3 && ((endTime = System.currentTimeMillis()) - startTime) < 5000) {
        Thread.sleep(50);
    }

    in.shutdown();
    t.join();

    windowGenerator.deactivate();

    Assert.assertFalse(gco.checkpointTwice);
    Assert.assertTrue("Timed out", (endTime - startTime) < 5000);
}

From source file:com.emc.ecs.sync.CasMigrationTest.java

private String pipeAndGetMd5(byte[] source) throws Exception {
    PipedInputStream pin = new PipedInputStream(BUFFER_SIZE);
    PipedOutputStream pout = new PipedOutputStream(pin);

    Producer producer = new Producer(source, pout);

    // produce in parallel
    Thread producerThread = new Thread(producer);
    producerThread.start();/*from ww w.ja va  2  s .c o  m*/

    // consume inside this thread
    byte[] dest = new byte[source.length];
    try {
        int read = 0;
        while (read < dest.length && read != -1) {
            read += pin.read(dest, read, dest.length - read);
        }
    } finally {
        try {
            pin.close();
        } catch (Throwable t) {
            // ignore
        }
    }

    // synchronize
    producerThread.join();

    return Hex.encodeHexString(MessageDigest.getInstance("MD5").digest(dest));
}

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

@Test
public void testMultipleBursts() throws Exception {
    assertEquals(0, cappedTestCollection.count());
    MockEndpoint mock = getMockEndpoint("mock:test");
    mock.expectedMessageCount(5000);/*from w w  w. j  av a2  s .  c  o m*/

    // 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("tailableCursorConsumer1");

    // pump 5 bursts of 1000 records each with 500ms pause between burst and burst
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 5000; i++) {
                if (i % 1000 == 0) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        return;
                    }
                }
                cappedTestCollection.insert(
                        BasicDBObjectBuilder.start("increasing", i).add("string", "value" + i).get(),
                        WriteConcern.SAFE);
            }

        }
    });

    // start the data pumping
    t.start();
    // before we assert, wait for the data pumping to end
    t.join();

    mock.assertIsSatisfied();
    context.stopRoute("tailableCursorConsumer1");

}

From source file:org.nuxeo.client.test.TestRepository.java

@Test
public void testMultiThread() throws InterruptedException {
    Thread t = new Thread(() -> {
        try {/*www  .j  a  v a  2  s . co  m*/
            RecordSet documents = nuxeoClient.automation().param("query", "SELECT * " + "FROM Document")
                    .execute("Repository.ResultSetQuery");
            assertTrue(documents.getUuids().size() != 0);
        } catch (Exception e) {
        }
    });
    Thread t2 = new Thread(() -> {
        try {
            RecordSet documents = nuxeoClient.automation().param("query", "SELECT * FROM Document")
                    .execute("Repository.ResultSetQuery");
            assertTrue(documents.getUuids().size() != 0);
        } catch (Exception e) {
        }
    });
    t.start();
    t2.start();
    t.join();
    t2.join();
}

From source file:com.datatorrent.stram.engine.GenericNodeTest.java

private void testCheckpointApplicationWindowCount(ProcessingMode processingMode) throws Exception {
    final long timeoutMillis = 10000L;
    final long sleepTime = 25L;

    WindowGenerator windowGenerator = new WindowGenerator(new ScheduledThreadPoolExecutor(1, "WindowGenerator"),
            1024);/* w ww. j ava2s. c  o m*/
    long resetWindow = 0L;
    long firstWindowMillis = 1448909287863L;
    int windowWidth = 100;

    windowGenerator.setResetWindow(resetWindow);
    windowGenerator.setFirstWindow(firstWindowMillis);
    windowGenerator.setWindowWidth(windowWidth);
    windowGenerator.setCheckpointCount(1, 0);

    GenericOperator go = new GenericOperator();

    DefaultAttributeMap dam = new DefaultAttributeMap();
    dam.put(OperatorContext.APPLICATION_WINDOW_COUNT, 5);
    dam.put(OperatorContext.CHECKPOINT_WINDOW_COUNT, 5);
    dam.put(OperatorContext.PROCESSING_MODE, processingMode);

    DelayAsyncFSStorageAgent storageAgent = new DelayAsyncFSStorageAgent(testMeta.getDir(),
            new Configuration());
    storageAgent.setDelayMS(200L);

    dam.put(OperatorContext.STORAGE_AGENT, storageAgent);

    TestStatsOperatorContext operatorContext = new TestStatsOperatorContext(0, dam, null);
    final GenericNode gn = new GenericNode(go, operatorContext);
    gn.setId(1);

    TestSink testSink = new TestSink();

    gn.connectInputPort("ip1", windowGenerator.acquireReservoir(String.valueOf(gn.id), 1024));
    gn.connectOutputPort("output", testSink);
    gn.firstWindowMillis = firstWindowMillis;
    gn.windowWidthMillis = windowWidth;

    windowGenerator.activate(null);

    Thread t = new Thread() {
        @Override
        public void run() {
            gn.activate();
            gn.run();
            gn.deactivate();
        }
    };

    t.start();

    long startTime = System.currentTimeMillis();
    long endTime = 0;

    while (operatorContext.checkpoints.size() < 8
            && ((endTime = System.currentTimeMillis()) - startTime) < timeoutMillis) {
        Thread.sleep(sleepTime);
    }

    gn.shutdown();
    t.join();

    windowGenerator.deactivate();

    Assert.assertTrue(!operatorContext.checkpoints.isEmpty());

    for (int index = 0; index < operatorContext.checkpoints.size(); index++) {
        if (operatorContext.checkpoints.get(index) == null) {
            continue;
        }

        Assert.assertEquals(0, operatorContext.checkpoints.get(index).applicationWindowCount);
        Assert.assertEquals(0, operatorContext.checkpoints.get(index).checkpointWindowCount);
    }
}