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:edu.harvard.hul.ois.fits.Fits.java

public FitsOutput examine(File input) throws FitsException {
    if (!input.exists()) {
        throw new FitsConfigurationException(input + " does not exist or is not readable");
    }/*w  w  w  .  jav a2  s. c om*/

    List<ToolOutput> toolResults = new ArrayList<ToolOutput>();

    //run file through each tool, catching exceptions thrown by tools
    List<Exception> caughtExceptions = new ArrayList<Exception>();
    String path = input.getPath().toLowerCase();
    String ext = path.substring(path.lastIndexOf(".") + 1);

    ArrayList<Thread> threads = new ArrayList<Thread>();
    for (Tool t : toolbelt.getTools()) {
        if (t.isEnabled()) {
            if (!t.hasExcludedExtension(ext)) {
                //spin up new threads
                t.setInputFile(input);
                Thread thread = new Thread(t);
                threads.add(thread);
                thread.start();
            }
        }
    }

    //wait for them all to finish
    for (Thread thread : threads) {
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //get all output from the tools
    for (Tool t : toolbelt.getTools()) {
        toolResults.add(t.getOutput());
    }

    // consolidate the results into a single DOM
    FitsOutput result = consolidator.processResults(toolResults);
    result.setCaughtExceptions(caughtExceptions);

    for (Tool t : toolbelt.getTools()) {
        t.resetOutput();
    }

    return result;
}

From source file:com.amalto.core.save.AutoIncrementTest.java

public void testConcurrentHazelcastAutoIncrement() throws Exception {
    cleanAutoIncrement();//  w  ww. java2  s . co m
    cleanTestAIData();

    HazelcastAutoIncrementGenerator generator1 = initHazelcastAutoIncrementGenerator();
    final MockHazelcastAutoIncrementGenerator generator2 = new MockHazelcastAutoIncrementGenerator();

    createData("TestAI", "<A></A>", true); // create a record to initialize auto-increment
    Thread thread1 = new ClusterCreateThread();
    Thread thread2 = new ClusterCreateThread();
    Thread thread3 = new Thread() {

        public void run() {
            generator2.generateId("TestAI", "A", "Id");
        }
    };

    thread1.start();
    thread3.start();
    thread2.start();
    thread1.join();
    thread3.join();
    thread2.join();

    validateAutoIncrement(22L);
    // Node1's nextId
    assertEquals(generator1.generateId("TestAI", "A", "Id"), "23");
    // Node2 will get right nextId
    assertEquals(generator2.generateId("TestAI", "A", "Id"), "24");
}

From source file:au.com.ish.derbydump.derbydump.main.DumpTest.java

@Test
public void theDumpTest() throws Exception {
    // Create table
    StringBuilder createTableBuffer = new StringBuilder();
    createTableBuffer.append("CREATE TABLE ");
    createTableBuffer.append(Configuration.getConfiguration().getSchemaName());
    createTableBuffer.append(".");
    createTableBuffer.append(tableName);
    createTableBuffer.append(" (");

    StringBuilder insertBuffer = new StringBuilder();
    insertBuffer.append("INSERT INTO ");
    insertBuffer.append(RESOURCE_SCHEMA_NAME);
    insertBuffer.append(".");
    insertBuffer.append(tableName);//from   w  w w .  j av  a2 s .c  om
    insertBuffer.append(" VALUES (");

    for (String col : columns) {
        createTableBuffer.append(col.toUpperCase());
        //String[] c = col.split(" ");
        //insertBuffer.append(c[0].toUpperCase().trim());
        insertBuffer.append("?");
        if (!columns[columns.length - 1].equals(col)) {
            createTableBuffer.append(", ");
            insertBuffer.append(",");
        }
    }

    createTableBuffer.append(")");
    insertBuffer.append(")");

    config.setTableRewriteProperty("testSkip", "--exclude--");
    config.setTableRewriteProperty("testRename", "testRenameNew");
    config.setTruncateTables(truncate);

    File f = new File("./build/outputs/" + tableName + ".sql");
    if (f.exists()) {
        f.delete();
    }
    f.mkdirs();

    config.setOutputFilePath(f.getCanonicalPath());

    Connection connection = db.createNewConnection();
    Statement statement = connection.createStatement();
    PreparedStatement ps = null;

    try {
        statement.execute(createTableBuffer.toString());
        connection.commit();
        //config.setTableRewriteProperty("TABLE2", "--exclude--");

        for (Object o : valuesToInsert) {
            Object[] vals = (Object[]) o;
            if (vals.length > 0) {
                ps = db.getConnection().prepareStatement(insertBuffer.toString());
                for (int i = 0; i < vals.length; i++) {
                    if (vals[i] instanceof InputStream) {
                        ps.setBinaryStream(i + 1, (InputStream) vals[i]);
                    } else {
                        ps.setObject(i + 1, vals[i]);
                    }
                }
                ps.execute();
                connection.commit();
            }
        }

        OutputThread output = new OutputThread();
        Thread writer = new Thread(output, "File_Writer");
        writer.start();

        new DatabaseReader(output);
        // Let the writer know that no more data is coming
        writer.interrupt();
        writer.join();

        // Now let's read the output and see what is in it
        List<String> lines = FileUtils.readLines(f);

        assertEquals("Missing foreign key operations", "SET FOREIGN_KEY_CHECKS = 0;", lines.get(0));
        assertEquals("Missing foreign key operations", "SET FOREIGN_KEY_CHECKS = 1;",
                lines.get(lines.size() - 1));

        if (!skipped) {
            assertTrue("LOCK missing", lines.contains("LOCK TABLES `" + outputTableName + "` WRITE;"));
            assertTrue("UNLOCK missing", lines.contains("UNLOCK TABLES;"));

            int index = lines.indexOf("LOCK TABLES `" + outputTableName + "` WRITE;");

            if (truncate) {
                assertTrue("TRUNCATE missing", lines.contains("TRUNCATE TABLE " + outputTableName + ";"));
                assertTrue("INSERT missing, got " + lines.get(index + 2),
                        lines.get(index + 2).startsWith("INSERT INTO " + outputTableName));
            } else {
                assertTrue("INSERT missing, got " + lines.get(index + 1),
                        lines.get(index + 1).startsWith("INSERT INTO " + outputTableName));
            }

            for (String s : validOutputs) {
                assertTrue("VALUES missing :" + s, lines.contains(s));
            }
        } else {
            assertTrue("LOCK missing", !lines.contains("LOCK TABLES `" + outputTableName + "` WRITE;"));
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail("failed to create test data" + e.getMessage());
    } finally {
        if (ps != null) {
            ps.close();
        }
        statement.close();
        connection.close();
    }
}

From source file:org.apache.tomcat.maven.it.AbstractWarProjectIT.java

/**
 * Executes mvn verify and retrieves the response from the web application.
 *
 * @return the response given//  w w w.j  a  v a 2  s  .c om
 * @throws VerificationException if the verifier failed to execute the goal
 * @throws InterruptedException  if the execution got interrupted in some way
 */
protected final String executeVerifyWithGet() throws VerificationException, InterruptedException, IOException {
    final String[] responseBodies = new String[] { null };

    final Thread thread = new Thread("webapp-response-retriever") {
        @Override
        public void run() {
            responseBodies[0] = getResponseBody(getTimeout());
        }
    };

    thread.start();

    logger.info("Executing verify on " + webappHome.getAbsolutePath());

    verifier.setCliOptions(getCliOptions());

    verifier.setLogFileName("foo.log");

    verifier.executeGoal(getGoal());

    verifier.displayStreamBuffers();

    thread.join();

    return responseBodies[0];
}

From source file:com.netflix.curator.framework.recipes.queue.TestSimpleDistributedQueue.java

@Test
public void testTakeWait1() throws Exception {
    CuratorFramework clients[] = null;/*from www . j a  va  2 s.c o  m*/
    try {
        String dir = "/testTakeWait1";
        final String testString = "Hello World";
        final int num_clients = 1;
        clients = new CuratorFramework[num_clients];
        final SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients];
        for (int i = 0; i < clients.length; i++) {
            clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
            clients[i].start();
            queueHandles[i] = new SimpleDistributedQueue(clients[i], dir);
        }

        final byte[] takeResult[] = new byte[1][];
        Thread takeThread = new Thread() {
            public void run() {
                try {
                    takeResult[0] = queueHandles[0].take();
                } catch (Exception e) {
                    // ignore
                }
            }
        };
        takeThread.start();

        Thread.sleep(1000);
        Thread offerThread = new Thread() {
            public void run() {
                try {
                    queueHandles[0].offer(testString.getBytes());
                } catch (Exception e) {
                    // ignore
                }
            }
        };
        offerThread.start();
        offerThread.join();

        takeThread.join();

        assertTrue(takeResult[0] != null);
        assertEquals(new String(takeResult[0]), testString);
    } finally {
        closeAll(clients);
    }
}

From source file:com.netflix.curator.framework.recipes.queue.TestSimpleDistributedQueue.java

@Test
public void testTakeWait2() throws Exception {
    String dir = "/testTakeWait2";
    final String testString = "Hello World";
    final int num_clients = 1;
    final CuratorFramework clients[] = new CuratorFramework[num_clients];
    final SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients];
    for (int i = 0; i < clients.length; i++) {
        clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        clients[i].start();// ww  w .jav  a2s .  c o  m
        queueHandles[i] = new SimpleDistributedQueue(clients[i], dir);
    }
    int num_attempts = 2;
    for (int i = 0; i < num_attempts; i++) {
        final byte[] takeResult[] = new byte[1][];
        final String threadTestString = testString + i;
        Thread takeThread = new Thread() {
            public void run() {
                try {
                    takeResult[0] = queueHandles[0].take();
                } catch (Exception e) {
                    // ignore
                }
            }
        };
        takeThread.start();

        Thread.sleep(1000);
        Thread offerThread = new Thread() {
            public void run() {
                try {
                    queueHandles[0].offer(threadTestString.getBytes());
                } catch (Exception e) {
                    // ignore
                }
            }
        };
        offerThread.start();
        offerThread.join();

        takeThread.join();

        assertTrue(takeResult[0] != null);
        assertEquals(new String(takeResult[0]), threadTestString);
    }
}

From source file:uk.org.thegatekeeper.dw.booking.BookingServiceIT.java

@Test
public void testConcurrentBooking() throws Exception {
    JdiGateController controller = new JdiGateController(debugger);
    Gate gate = controller.stopFirstThread().inClass(PaymentService.class).beforeMethod("pay").build();

    final List<Throwable> exceptions = new ArrayList<Throwable>();
    Thread booking = new Thread(new Runnable() {
        public void run() {
            try {
                Request.Post("http://localhost:8080/booking/book/3/34").execute().returnContent().asString();
            } catch (Throwable t) {
                exceptions.add(t);/* w w w . j av  a2  s  .c  o m*/
            }
        }
    });

    booking.start();
    gate.waitFor(5, TimeUnit.SECONDS);

    String status = Request.Post("http://localhost:8080/booking/book/3/34").execute().returnContent()
            .asString();
    assertThat(status, containsString("\"success\":true"));

    gate.open();
    booking.join();

    assertEquals(1, exceptions.size());
}

From source file:org.openmrs.module.auditlog.AuditLogBehaviorTest.java

@Test
@NotTransactional//from w w  w.  j a v  a 2 s  .c  o m
public void shouldHandleInsertsOrUpdatesOrDeletesInEachTransactionIndependently() throws InterruptedException {
    final int N = 50;
    final Set<Thread> threads = new LinkedHashSet<Thread>();

    for (int i = 0; i < N; i++) {
        threads.add(new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Context.openSession();
                    Context.authenticate("admin", "test");
                    Integer index = new Integer(Thread.currentThread().getName());
                    EncounterService es = Context.getEncounterService();
                    if (index == 0) {
                        //Let's have a delete
                        EncounterType existingEncounterType = es.getEncounterType(6);
                        assertNotNull(existingEncounterType);
                        es.purgeEncounterType(existingEncounterType);
                    } else {
                        EncounterType encounterType;
                        if (index % 2 == 0) {
                            //And some updates
                            encounterType = es.getEncounterType(2);
                            encounterType.setDescription("New Description-" + index);
                        } else {
                            //And some new rows inserted
                            encounterType = new EncounterType("Encounter Type-" + index,
                                    "Description-" + index);
                        }
                        es.saveEncounterType(encounterType);
                    }
                } finally {
                    Context.closeSession();
                }
            }
        }, Integer.toString(i)));
    }

    for (Thread thread : threads) {
        thread.start();
    }

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

    assertEquals(N, getAllLogs().size());

    List<Action> actions = new ArrayList<Action>();
    actions.add(CREATED);//should match expected count of created log entries
    assertEquals(25, auditLogService.getAuditLogs(null, actions, null, null, false, null, null).size());

    actions.clear();
    actions.add(UPDATED);//should match expected count of updated log entries
    assertEquals(24, auditLogService.getAuditLogs(null, actions, null, null, false, null, null).size());

    actions.clear();
    actions.add(DELETED);//should match expected count of deleted log entries
    assertEquals(1, auditLogService.getAuditLogs(null, actions, null, null, false, null, null).size());
}

From source file:com.meltmedia.dropwizard.etcd.json.EtcdWatchServiceIT.java

@Test
public void shouldJoinExistingWatchWithLotsOfEvents() throws InterruptedException {
    int eventsCount = 1000;
    // add a directory watch.
    WatchService service = serviceRule.getService();

    @SuppressWarnings("unchecked")
    EtcdEventHandler<NodeData> handler = mock(EtcdEventHandler.class);

    Thread events = startNodeDataThread(jobsDao, eventsCount);

    try {//from  w w  w.  j  a v a  2 s .  c  o m
        service.registerDirectoryWatch("/jobs", new TypeReference<NodeData>() {
        }, handler);

        verifySequentialNodeData(handler, eventsCount);
    } finally {
        events.join();
    }
}