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:org.berlin.crawl.bom.StartURLSeedReader.java

public void launch() {
    final ApplicationContext ctx = new ClassPathXmlApplicationContext(
            "/org/berlin/batch/batch-databot-context.xml");
    final BotCrawlerDAO dao = new BotCrawlerDAO();
    final SessionFactory sf = (SessionFactory) ctx.getBean("sessionFactory");
    final Session session = sf.openSession();
    final List<BotSeed> seeds = dao.findSeedRequests(session);
    int numberOfSeeds = 0;

    // Randomize the seed list //      
    Collections.shuffle(seeds);//from  w  w  w .  ja  v a2s .  c o m
    for (final BotSeed seed : seeds) {
        if ("Y".equalsIgnoreCase(seed.getEnabled())) {
            numberOfSeeds++;
            if (this.activeThreads.size() < maxActiveThreads) {
                logger.info("At Start URL Seeder, seeding / num=" + numberOfSeeds + " / " + seed.getId()
                        + " sz=" + this.activeThreads.size());
                // Only launch so many threads               
                final BotTrueCrawler crawl = new BotTrueCrawler(this, ctx, seed.toLink());
                crawl.launch();
                // Slight delay after producing the links for processing //
                try {
                    Thread.sleep(BotTrueCrawler.DELAY_FROM_PRODUCER + (4 * 1000));
                } catch (final InterruptedException e) {
                    e.printStackTrace();
                } /// End of try catch //
            } else {
                // Wait for the threads to finish, using join
                for (final Thread wt : this.activeThreads) {
                    try {
                        logger.info("At Start URL Seeder, waiting on seeds to complete");
                        wt.join();
                    } catch (final InterruptedException e) {
                        e.printStackTrace();
                    }
                } // End of the for //
                  // If we reached this point, remove all the threads , they finished processing
                if (this.activeThreads.size() > 0) {
                    this.activeThreads.clear();
                }
            } // End of the if - else //            
            logger.info("!/=! At END OF seed launching, seeding / num=" + numberOfSeeds + " / " + seed.getId());
        } // End of the if //
    } // End of the for //

    // Wait for the threads to finish, using join
    for (final Thread wt : this.activeThreads) {
        try {
            logger.info("At Start URL Seeder, waiting on seeds to complete [f66x0");
            wt.join();
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
    } // End of the for //

    logger.info("!/=! At END OF seed seeding, launch complete");
    if (session != null) {
        // May not need to close the session
        session.close();
    } // End of the if //
}

From source file:com.netxforge.oss2.core.utils.ProcessExec.java

/**
 * <p>exec</p>//from  w ww .j  ava  2s . com
 *
 * @param cmd an array of {@link java.lang.String} objects.
 * @return a int.
 * @throws java.io.IOException if any.
 * @throws java.lang.InterruptedException if any.
 */
public int exec(String[] cmd) throws IOException, InterruptedException {
    Process p = Runtime.getRuntime().exec(cmd);

    p.getOutputStream().close();
    PrintInputStream out = new PrintInputStream(p.getInputStream(), m_out);
    PrintInputStream err = new PrintInputStream(p.getErrorStream(), m_err);

    Thread t1 = new Thread(out, this.getClass().getSimpleName() + "-stdout");
    Thread t2 = new Thread(err, this.getClass().getSimpleName() + "-stderr");
    t1.start();
    t2.start();

    int exitVal = p.waitFor();

    t1.join();
    t2.join();

    return exitVal;
}

From source file:com.continuuity.weave.kafka.client.KafkaTest.java

@Test(timeout = 10000)
public void testOffset() throws Exception {
    String topic = "testOffset";

    // Initial earliest offset should be 0.
    long[] offsets = kafkaClient.getOffset(topic, 0, -2, 10).get();
    Assert.assertArrayEquals(new long[] { 0L }, offsets);

    // Publish some messages
    Thread publishThread = createPublishThread(kafkaClient, topic, Compression.NONE, "Testing", 2000);
    publishThread.start();//from   w w w. j  a  v  a2  s . com
    publishThread.join();

    // Fetch earliest offset, should still be 0.
    offsets = kafkaClient.getOffset(topic, 0, -2, 10).get();
    Assert.assertArrayEquals(new long[] { 0L }, offsets);

    // Fetch latest offset
    offsets = kafkaClient.getOffset(topic, 0, -1, 10).get();
    Iterator<FetchedMessage> consumer = kafkaClient.consume(topic, 0, offsets[0], 1048576);

    // Publish one more message, the consumer should see the new message being published.
    publishThread = createPublishThread(kafkaClient, topic, Compression.NONE, "Testing", 1, 3000);
    publishThread.start();
    publishThread.join();

    // Should see the last message being published.
    Assert.assertTrue(consumer.hasNext());
    Assert.assertEquals("3000 Testing", Charsets.UTF_8.decode(consumer.next().getBuffer()).toString());
}

From source file:ch.sourcepond.io.checksum.impl.DefaultChecksumTest.java

/**
 * @throws Exception// www.j a va2s  .  c  om
 */
@Test
public void verifyPropagateInterruptedException() throws Exception {
    final InterruptTest r = new InterruptTest();
    final Thread th = new Thread(r);
    th.start();
    th.join();

    assertFalse("Exception expected", r.fail);
    assertEquals(InterruptedException.class, r.exception.getCause().getClass());
}

From source file:com.microsoft.speech.tts.Authentication.java

public Authentication(String apiKey) {
    this.apiKey = apiKey;

    Thread th = new Thread(new Runnable() {
        @Override/* ww  w.  j  a va2  s.  c  om*/
        public void run() {
            RenewAccessToken();
        }
    });

    try {
        th.start();
        th.join();
    } catch (Exception e) {
        e.printStackTrace();
    }

    // renew the accessToken every specified minutes
    accessTokenRenewer = new Timer();
    nineMinitesTask = new TimerTask() {
        public void run() {
            RenewAccessToken();
        }
    };

    accessTokenRenewer.schedule(nineMinitesTask, RefreshTokenDuration, RefreshTokenDuration);
}

From source file:com.espertech.esper.dataflow.core.EPDataFlowInstanceImpl.java

public void join() throws InterruptedException {
    if (state == EPDataFlowState.INSTANTIATED) {
        throw new IllegalStateException("Data flow '" + dataFlowName
                + "' instance has not been executed, please use join after start or run");
    }/*from w ww . j av a2  s.com*/
    if (state == EPDataFlowState.CANCELLED) {
        throw new IllegalStateException(
                "Data flow '" + dataFlowName + "' instance has been cancelled and cannot be joined");
    }

    // latch used for non-blocking start
    if (threads != null) {
        for (Thread thread : threads) {
            thread.join();
        }
    } else {
        CountDownLatch latch = new CountDownLatch(1);
        synchronized (this) {
            if (joinedThreadLatches == null) {
                joinedThreadLatches = new ArrayList<CountDownLatch>();
            }
            joinedThreadLatches.add(latch);
        }
        if (state != EPDataFlowState.COMPLETE) {
            latch.await();
        }
    }
}

From source file:com.hortonworks.registries.storage.filestorage.DbFileStorageTest.java

@Test(expected = StorageException.class)
public void testConcurrentUpload() throws Throwable {
    try {/*from  w  w w. j a  va2s .  c  o m*/
        transactionManager.beginTransaction(TransactionIsolation.SERIALIZABLE);
        String input = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(FILE_NAME),
                "UTF-8");
        String updated = input + " new text";
        dbFileStorage.upload(IOUtils.toInputStream(input, "UTF-8"), FILE_NAME);
        InputStream slowStream = new InputStream() {
            byte[] bytes = updated.getBytes("UTF-8");
            int i = 0;

            @Override
            public int read() throws IOException {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException ex) {
                }
                return (i < bytes.length) ? (bytes[i++] & 0xff) : -1;
            }
        };
        FutureTask<String> ft1 = new FutureTask<>(() -> {
            try {
                transactionManager.beginTransaction(TransactionIsolation.SERIALIZABLE);
                String name = dbFileStorage.upload(slowStream, FILE_NAME);
                transactionManager.commitTransaction();
                return name;
            } catch (Exception e) {
                transactionManager.rollbackTransaction();
                throw e;
            }
        });
        FutureTask<String> ft2 = new FutureTask<>(() -> {
            try {
                transactionManager.beginTransaction(TransactionIsolation.SERIALIZABLE);
                String name = dbFileStorage.upload(IOUtils.toInputStream(updated, "UTF-8"), FILE_NAME);
                transactionManager.commitTransaction();
                return name;
            } catch (Exception e) {
                transactionManager.rollbackTransaction();
                throw e;
            }
        });
        Thread t1 = new Thread(ft1);
        Thread t2 = new Thread(ft2);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        try {
            ft1.get();
        } catch (ExecutionException ex) {
            throw ex.getCause();
        }
        transactionManager.commitTransaction();
    } catch (Exception e) {
        transactionManager.rollbackTransaction();
        throw e;
    }
}

From source file:fitnesse.FitNesseExpediterTest.java

@Test
public void testCompleteRequest() throws Exception {
    final FitNesseExpediter sender = preparePipedFitNesseExpediter();

    Thread senderThread = makeSendingThread(sender);
    senderThread.start();/*from  w  ww  .jav a  2s. c  o  m*/
    Thread parseResponseThread = makeParsingThread();
    parseResponseThread.start();

    clientOutput.write("GET /root HTTP/1.1\r\n\r\n".getBytes());
    clientOutput.flush();

    parseResponseThread.join();

    assertEquals(200, response.getStatus());
}

From source file:azkaban.execapp.event.LocalFlowWatcherTest.java

@Ignore
@Test//from w w w.j  a v  a2 s.  c o  m
public void testBasicLocalFlowWatcher() throws Exception {
    MockExecutorLoader loader = new MockExecutorLoader();

    EventCollectorListener eventCollector = new EventCollectorListener();

    File workingDir1 = setupDirectory();
    FlowRunner runner1 = createFlowRunner(workingDir1, loader, eventCollector, "exec1", 1, null, null);
    Thread runner1Thread = new Thread(runner1);

    File workingDir2 = setupDirectory();
    LocalFlowWatcher watcher = new LocalFlowWatcher(runner1);
    FlowRunner runner2 = createFlowRunner(workingDir2, loader, eventCollector, "exec1", 2, watcher, 2);
    Thread runner2Thread = new Thread(runner2);

    runner1Thread.start();
    runner2Thread.start();
    runner2Thread.join();

    FileUtils.deleteDirectory(workingDir1);
    FileUtils.deleteDirectory(workingDir2);

    testPipelineLevel2(runner1.getExecutableFlow(), runner2.getExecutableFlow());
}

From source file:azkaban.execapp.event.LocalFlowWatcherTest.java

@Ignore
@Test/*from  w w w .j  av a 2s.  c om*/
public void testLevel1LocalFlowWatcher() throws Exception {
    MockExecutorLoader loader = new MockExecutorLoader();

    EventCollectorListener eventCollector = new EventCollectorListener();

    File workingDir1 = setupDirectory();
    FlowRunner runner1 = createFlowRunner(workingDir1, loader, eventCollector, "exec1", 1, null, null);
    Thread runner1Thread = new Thread(runner1);

    File workingDir2 = setupDirectory();
    LocalFlowWatcher watcher = new LocalFlowWatcher(runner1);
    FlowRunner runner2 = createFlowRunner(workingDir2, loader, eventCollector, "exec1", 2, watcher, 1);
    Thread runner2Thread = new Thread(runner2);

    runner1Thread.start();
    runner2Thread.start();
    runner2Thread.join();

    FileUtils.deleteDirectory(workingDir1);
    FileUtils.deleteDirectory(workingDir2);

    testPipelineLevel1(runner1.getExecutableFlow(), runner2.getExecutableFlow());
}