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:lockstep.LockstepServer.java

/**
 * Frees all resources tied to the server, that is networking threads and
 * sockets.//from  ww w . j a  v a 2 s .  co m
 */
private void closeResources() {
    for (Thread transmitter : transmitters.values())
        transmitter.interrupt();

    try {
        for (Thread receiver : receivers.values()) {
            receiver.join();
        }

        for (Thread transmitter : transmitters.values()) {
            transmitter.join();
        }
    } catch (InterruptedException intEx) {
        //shouldn't be interrupted
        LOG.fatal("Interrupted during termination!!");
        LOG.fatal(intEx);
    }
}

From source file:jp.aegif.nemaki.tracker.CoreTracker.java

public void index(String trackingType, String repositoryId) {
    synchronized (LOCK) {
        ChangeEvents changeEvents = getCmisChangeLog(trackingType, repositoryId);
        if (changeEvents == null) {
            return;
        }/*w w  w.  j a va2s  .c o  m*/
        List<ChangeEvent> events = changeEvents.getChangeEvents();

        // After 2nd crawling, discard the first item
        // Because the specs say that it's included in the results
        String token = readLatestChangeToken(repositoryId);

        if (!StringUtils.isEmpty(token)) {
            if (!org.apache.commons.collections.CollectionUtils.isEmpty(events)) {
                events.remove(0);
            }
        }

        if (events.isEmpty())
            return;

        // Parse filtering configuration
        PropertyManager pm = new PropertyManagerImpl(StringPool.PROPERTIES_NAME);
        boolean fulltextEnabled = Boolean.TRUE.toString()
                .equalsIgnoreCase(pm.readValue(PropertyKey.SOLR_TRACKING_FULLTEXT_ENABLED));
        boolean mimeTypeFilterEnabled = false; // default
        List<String> allowedMimeTypeFilter = new ArrayList<String>(); // default
        if (fulltextEnabled) {
            String _filter = pm.readValue(PropertyKey.SOLR_TRACKING_MIMETYPE_FILTER_ENABLED);
            mimeTypeFilterEnabled = Boolean.TRUE.toString().equalsIgnoreCase(_filter);
            if (mimeTypeFilterEnabled) {
                allowedMimeTypeFilter = pm.readValues(PropertyKey.SOLR_TRACKING_MIMETYPE);
            }
        }

        // Extract only the last events of each objectId
        List<ChangeEvent> list = extractChangeEvent(events);

        PropertyManager propMgr = new PropertyManagerImpl(StringPool.PROPERTIES_NAME);
        int numberOfThread = Integer.valueOf(propMgr.readValue(PropertyKey.SOLR_TRACKING_NUMBER_OF_THREAD));
        int numberPerThread = list.size() / numberOfThread;
        if (list.size() < numberOfThread) {
            numberOfThread = list.size();
            numberPerThread = 1;
        }

        for (int i = 0; i <= numberOfThread; i++) {
            int toIndex = (numberPerThread * (i + 1) > list.size()) ? list.size() : numberPerThread * (i + 1);

            List<ChangeEvent> listPerThread = list.subList(numberPerThread * i, toIndex);
            Session cmisSession = CmisSessionFactory.getSession(repositoryId);
            Registration registration = new Registration(cmisSession, core, indexServer, listPerThread,
                    fulltextEnabled, mimeTypeFilterEnabled, allowedMimeTypeFilter);
            Thread t = new Thread(registration);
            t.start();
            try {
                t.join();
            } catch (InterruptedException e) {
                logger.error(e);
            }
        }

        // Save the latest token
        storeLatestChangeToken(changeEvents.getLatestChangeLogToken(), repositoryId);

        // In case of FUll mode, repeat until indexing all change logs
        if (Constant.MODE_FULL.equals(trackingType)) {
            index(Constant.MODE_FULL, repositoryId);
        }
    }
}

From source file:org.elasticsearch.backwards.IndexingIT.java

/**
 * Indexes a document in <code>index</code> with <code>docId</code> then concurrently updates the same document
 * <code>nUpdates</code> times
 *
 * @return the document version after updates
 *//*from   w w w.ja v  a  2s. c o m*/
private int indexDocWithConcurrentUpdates(String index, final int docId, int nUpdates)
        throws IOException, InterruptedException {
    indexDocs(index, docId, 1);
    Thread[] indexThreads = new Thread[nUpdates];
    for (int i = 0; i < nUpdates; i++) {
        indexThreads[i] = new Thread(() -> {
            try {
                indexDocs(index, docId, 1);
            } catch (IOException e) {
                throw new AssertionError("failed while indexing [" + e.getMessage() + "]");
            }
        });
        indexThreads[i].start();
    }
    for (Thread indexThread : indexThreads) {
        indexThread.join();
    }
    return nUpdates + 1;
}

From source file:com.arpnetworking.metrics.impl.TsdQueryLogSinkTest.java

@Test
public void testShutdownHookThread() throws InterruptedException {
    final LoggerContext context = Mockito.mock(LoggerContext.class);
    final Thread shutdownThread = new TsdQueryLogSink.ShutdownHookThread(context);
    shutdownThread.start();//  w w w  .  jav  a  2s  . c  o m
    shutdownThread.join();
    Mockito.verify(context).stop();
}

From source file:com.esri.geoevent.test.tools.RunTcpInBdsOutTest.java

private void runTest(long numberEvents, int rate, String server, int in_port, String data_file,
        String msLayerUrl, Boolean isSingle) {

    this.send_rate = -1.0;
    this.rcv_rate = -1.0;

    try {/*from   w w  w . ja  v a  2s .  c  om*/

        GetMapServiceCountRunnable reader = new GetMapServiceCountRunnable(numberEvents, msLayerUrl, isSingle);
        Thread readerThread = new Thread(reader);

        readerThread.start();

        // Give the consumer a couple of seconds to start
        Thread.sleep(2000);

        this.send(server, in_port, numberEvents, rate, data_file);

        readerThread.join();

        rcv_rate = reader.getAverage_read_per_second();

        if (reader.getNum_events_read() != numberEvents) {
            // Number of events read differs from send 
            throw new Exception("Number of Events received (" + Long.toString(reader.getNum_events_read())
                    + ") did not match what was sent (" + Long.toString(numberEvents) + ") !");
        }

    } catch (Exception e) {
        System.out.println(e.getMessage());
        rcv_rate = -1.0;
    } finally {
        this.rcv_rate = rcv_rate;
    }

}

From source file:org.ulyssis.ipp.publisher.HttpServerPublisher.java

@Override
public void run() {
    LOG.info("Starting Undertow!");
    Thread thread = new Thread(server::start);
    thread.start();//w  ww.ja v  a2  s.  co  m
    try {
        while (!Thread.currentThread().isInterrupted()) {
            Thread.sleep(10L);
        }
    } catch (InterruptedException ignored) {
    }
    server.stop();
    thread.interrupt();
    try {
        thread.join();
    } catch (InterruptedException ignored) {
    }
    cleanup();
}

From source file:at.ac.tuwien.dsg.quelle.elasticityQuantification.engines.CloudServiceElasticityAnalysisEngine.java

public List<AnalysisResult> analyzeElasticity(CloudProvider cloudProvider) {

    final List<AnalysisResult> analysisResults = Collections.synchronizedList(new ArrayList<AnalysisResult>());
    List<Thread> threads = new ArrayList<Thread>();

    for (final CloudOfferedService unit : cloudProvider.getCloudOfferedServices()) {
        if (!unit.getCategory().equals("IaaS")) {
            continue;
        }/*from   w  w  w .  j  av  a 2  s.com*/
        Thread t = new Thread() {
            @Override
            public void run() {
                analysisResults.add(analyzeElasticity(unit));
            }
        };
        threads.add(t);
        t.start();
    }

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

        } catch (InterruptedException ex) {
            Logger.getLogger(CloudServiceElasticityAnalysisEngine.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    Collections.sort(analysisResults, new Comparator<AnalysisResult>() {

        @Override
        public int compare(AnalysisResult o1, AnalysisResult o2) {
            return ((Double) o1.getValue(OVERALL_ELASTICITY))
                    .compareTo(((Double) o2.getValue(OVERALL_ELASTICITY)));
        }

    });
    return analysisResults;
}

From source file:com.espertech.esper.regression.nwtable.TestTableMTUngroupedAccessWithinRowFAFConsistency.java

private void tryMT(int numSeconds) throws Exception {
    String eplCreateVariable = "create table vartotal (cnt count(*), sumint sum(int), avgint avg(int))";
    epService.getEPAdministrator().createEPL(eplCreateVariable);

    String eplInto = "into table vartotal select count(*) as cnt, sum(intPrimitive) as sumint, avg(intPrimitive) as avgint from SupportBean";
    epService.getEPAdministrator().createEPL(eplInto);

    epService.getEPAdministrator().createEPL("create window MyWindow.std:lastevent() as SupportBean_S0");
    epService.getEPAdministrator().createEPL("insert into MyWindow select * from SupportBean_S0");
    epService.getEPRuntime().sendEvent(new SupportBean_S0(0));

    WriteRunnable writeRunnable = new WriteRunnable(epService);
    ReadRunnable readRunnable = new ReadRunnable(epService);

    // start/*from  w  w w .  j a va 2s  .com*/
    Thread t1 = new Thread(writeRunnable);
    Thread t2 = new Thread(readRunnable);
    t1.start();
    t2.start();

    // wait
    Thread.sleep(numSeconds * 1000);

    // shutdown
    writeRunnable.setShutdown(true);
    readRunnable.setShutdown(true);

    // join
    log.info("Waiting for completion");
    t1.join();
    t2.join();

    assertNull(writeRunnable.getException());
    assertNull(readRunnable.getException());
    assertTrue(writeRunnable.numEvents > 100);
    assertTrue(readRunnable.numQueries > 100);
    System.out.println(
            "Send " + writeRunnable.numEvents + " and performed " + readRunnable.numQueries + " reads");
}

From source file:net.sf.ehcache.constructs.blocking.SelfPopulatingCacheTest.java

/**
 * Expected: If multiple threads try to retrieve the same key from a
 * SelfPopulatingCache at the same time, and that key is not yet in the cache,
 * one thread obtains the lock for that key and uses the CacheEntryFactory to
 * generate the cache entry and all other threads wait on the lock.
 * Any and all threads which timeout while waiting for this lock should fail
 * to acquire the lock for that key and throw an exception.
 * <p/>//from   w  w  w .  ja va  2s.co  m
 * This thread tests for this by having several threads to a cache "get" for
 * the same key, allowing one to acquire the lock and the others to wait.  The
 * one that acquires the lock and attempts to generate the cache entry for the
 * key waits for a period of time long enough to allow all other threads to
 * timeout waiting for the lock.  Any thread that succeeds in acquiring the lock,
 * including the first to do so, increment a counter when they begin creating
 * the cache entry using the CacheEntryFactory.  It is expected that this
 * counter will only be "1" after all threads complete since all but the
 * first to acquire it should timeout and throw exceptions.
 * <p/>
 * We then test that a thread that comes along later increments the counter.
 */
public void testSelfPopulatingBlocksWithTimeoutSetNull() throws InterruptedException {
    selfPopulatingCache = new SelfPopulatingCache(new Cache("TestCache", 50, false, false, 0, 0),
            new NullCachePopulator());
    selfPopulatingCache.setTimeoutMillis(200);
    manager.addCache(selfPopulatingCache);

    CacheAccessorThread[] cacheAccessorThreads = new CacheAccessorThread[10];

    for (int i = 0; i < cacheAccessorThreads.length; i++) {
        cacheAccessorThreads[i] = new CacheAccessorThread(selfPopulatingCache, "key1");
        cacheAccessorThreads[i].start();
        // Do a slight delay here so that all the timeouts
        // don't happen simultaneously - this is key
        try {
            Thread.sleep(20);
        } catch (InterruptedException ignored) {
            //
        }
    }

    //All of the others should have timed out. The first thread will have returned null.
    // This thread should be able to have a go, thus setting the count to 2
    Thread.sleep(1000);
    Thread lateThread = new CacheAccessorThread(selfPopulatingCache, "key1");
    lateThread.start();
    lateThread.join();

    assertEquals("Too many cacheAccessorThreads tried to create selfPopulatingCache entry for key1", 2,
            cacheEntryFactoryRequests);
}

From source file:net.sf.ehcache.constructs.blocking.SelfPopulatingCacheTest.java

/**
 * Creating 11 Threads which attempt to get a null entry will result, eventually, in 11
 * calls to the CacheEntryFactory/*from www.  j a v a 2s. c  om*/
 * @throws InterruptedException
 */
public void testSelfPopulatingBlocksWithoutTimeoutSetNull() throws InterruptedException {
    selfPopulatingCache = new SelfPopulatingCache(new Cache("TestCache", 50, false, false, 0, 0),
            new NullCachePopulator());
    //selfPopulatingCache.setTimeoutMillis(200);
    manager.addCache(selfPopulatingCache);

    CacheAccessorThread[] cacheAccessorThreads = new CacheAccessorThread[10];

    for (int i = 0; i < cacheAccessorThreads.length; i++) {
        cacheAccessorThreads[i] = new CacheAccessorThread(selfPopulatingCache, "key1");
        cacheAccessorThreads[i].start();
        // Do a slight delay here so that all the timeouts
        // don't happen simultaneously - this is key
        try {
            Thread.sleep(20);
        } catch (InterruptedException ignored) {
            //
        }
    }

    //All of the others should have timed out. The first thread will have returned null.
    // This thread should be able to have a go, thus setting the count to 2
    Thread.sleep(12000);
    Thread lateThread = new CacheAccessorThread(selfPopulatingCache, "key1");
    lateThread.start();
    lateThread.join();

    assertEquals("The wrong number of cacheAccessorThreads tried to create selfPopulatingCache entry for key1",
            11, cacheEntryFactoryRequests);
}