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:net.sf.ehcache.constructs.blocking.SelfPopulatingCacheTest.java

/**
 * Creating 11 Threads which attempt to get a non-null entry will result in 1
 * call to the CacheEntryFactory/*from  w w w.j  a  va 2s.com*/
 * @throws InterruptedException
 */
public void testSelfPopulatingBlocksWithoutTimeoutSetNonNull() throws InterruptedException {
    selfPopulatingCache = new SelfPopulatingCache(new Cache("TestCache", 50, false, false, 0, 0),
            new NonNullCachePopulator());
    //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(2000);
    Thread lateThread = new CacheAccessorThread(selfPopulatingCache, "key1");
    lateThread.start();
    lateThread.join();

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

From source file:at.ac.tuwien.dsg.quelle.elasticityQuantification.engines.CloudServiceUnitAnalysisEngine.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  ava2s . co m
        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(CloudServiceUnitAnalysisEngine.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return analysisResults;
}

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

private void tryMT(int numSeconds) throws Exception {
    String eplCreateVariable = "create table vartotal (total sum(int))";
    epService.getEPAdministrator().createEPL(eplCreateVariable);

    String eplInto = "into table vartotal select sum(intPrimitive) as total from SupportBean";
    epService.getEPAdministrator().createEPL(eplInto);

    SupportUpdateListener listenerZero = new SupportUpdateListener();
    epService.getEPAdministrator().createEPL("select * from SupportBean_S0(1 = vartotal.total)")
            .addListener(listenerZero);/*from   ww w. j av a  2 s  . c  o m*/

    SupportUpdateListener listenerOne = new SupportUpdateListener();
    epService.getEPAdministrator().createEPL("select * from SupportBean_S0(0 = vartotal.total)")
            .addListener(listenerOne);

    WriteRunnable writeRunnable = new WriteRunnable(epService);
    ReadRunnable readRunnable = new ReadRunnable(epService, listenerZero, listenerOne);

    // start
    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:com.espertech.esper.regression.nwtable.TestTableMTUngroupedSubqueryReadMergeWriteColumnUpd.java

private void tryMT(int numSeconds) throws Exception {
    String epl = "create table MyTable (p0 string, p1 string, p2 string, p3 string, p4 string);\n"
            + "on SupportBean merge MyTable "
            + "  when not matched then insert select '1' as p0, '1' as p1, '1' as p2, '1' as p3, '1' as p4;\n"
            + "on SupportBean_S0 merge MyTable "
            + "  when matched then update set p0=p00, p1=p00, p2=p00, p3=p00, p4=p00;\n"
            + "@name('out') select " + "(select p0 from MyTable where "
            + "  (p0='1' and p1='1' and p2='1' and p3='1' and p4='1') "
            + "  or (p0='2' and p1='2' and p2='2' and p3='2' and p4='2')) as c0 " + "from SupportBean_S1;\n";
    epService.getEPAdministrator().getDeploymentAdmin().parseDeploy(epl);

    // preload/*from w w w  .  j  a v a2  s. co m*/
    epService.getEPRuntime().sendEvent(new SupportBean());

    TestTableMTUngroupedJoinColumnConsistency.Update_1_2_WriteRunnable writeRunnable = new TestTableMTUngroupedJoinColumnConsistency.Update_1_2_WriteRunnable(
            epService);
    ReadRunnable readRunnable = new ReadRunnable(epService);

    // start
    Thread threadWrite = new Thread(writeRunnable);
    Thread threadRead = new Thread(readRunnable);
    threadWrite.start();
    threadRead.start();

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

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

    // join
    log.info("Waiting for completion");
    threadWrite.join();
    threadRead.join();

    assertNull(writeRunnable.getException());
    assertNull(readRunnable.getException());
    System.out.println("Write loops " + writeRunnable.getNumLoops() + " and performed "
            + readRunnable.numQueries + " reads");
    assertTrue(writeRunnable.getNumLoops() > 1);
    assertTrue(readRunnable.numQueries > 100);
}

From source file:com.sworddance.taskcontrol.TestTaskControl.java

private void startTaskControl(TaskControl taskControl, TaskGroup<?> taskGroup) throws InterruptedException {
    // additional test that addTaskGroup after TaskControl start will work.
    taskControl.addTaskGroup(taskGroup);
    Thread t = new Thread(taskControl);
    taskControl.setStayActive(false);/*from  w ww  .jav  a 2  s.com*/
    t.setName("TaskControl");
    t.start();
    t.join();
    assertFalse(t.isAlive());
}

From source file:com.amazon.aws.samplecode.travellog.web.TravelLogController.java

private void preloadJournal() {
    Configuration config = Configuration.getInstance();
    String bucket = config.getProperty("bundleBucket");
    String path = config.getProperty("bundlePath");
    DataLoader loader = new DataLoader(bucket, path, dao);
    Thread thread = new Thread(loader);
    thread.start();/* w w  w .  java 2 s .co  m*/
    try {
        thread.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        logger.log(Level.WARNING, e.getMessage(), e);
    }
}

From source file:com.photon.phresco.plugins.xcode.Instrumentation.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    getLog().info("Instrumentation command" + command);

    try {//  w w w.  j  a v  a 2  s  . co m
        outputFolder = project.getBasedir().getAbsolutePath();
        File f = new File(outputFolder);
        File files[] = f.listFiles();
        for (File file : files) {
            if (file.getName().startsWith("Run 1") || file.getName().endsWith(".trace")) {
                FileUtils.deleteDirectory(file);
            }
        }
    } catch (IOException e) {
        getLog().error(e);
    }

    Runnable runnable = new Runnable() {
        public void run() {
            ProcessBuilder pb = new ProcessBuilder(command);
            //device takes the highest priority
            if (StringUtils.isNotBlank(deviceid)) {
                pb.command().add("-w");
                pb.command().add(deviceid);
            }
            pb.command().add("-t");
            pb.command().add(template);

            if (StringUtils.isNotBlank(appPath)) {
                pb.command().add(appPath);
            } else {
                getLog().error("Application should not be empty");
            }
            if (StringUtils.isNotBlank(script)) {
                pb.command().add("-e");
                pb.command().add("UIASCRIPT");
                String scriptPath = project.getBasedir().getAbsolutePath() + File.separator + script;
                pb.command().add(scriptPath);
            } else {
                getLog().error("script is empty");
            }

            pb.command().add("-e");
            pb.command().add("UIARESULTSPATH");
            pb.command().add(outputFolder);

            // Include errors in output
            pb.redirectErrorStream(true);

            getLog().info("List of commands" + pb.command());
            Process child;
            try {
                child = pb.start();
                // Consume subprocess output and write to stdout for debugging
                InputStream is = new BufferedInputStream(child.getInputStream());
                int singleByte = 0;
                while ((singleByte = is.read()) != -1) {
                    System.out.write(singleByte);
                }
            } catch (IOException e) {
                getLog().error(e);
            }

        }

    };

    Thread t = new Thread(runnable, "iPhoneSimulator");
    t.start();
    getLog().info("Thread started");
    try {
        //Thread.sleep(5000);
        t.join();
        t.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    preparePlistResult();
    generateXMLReport(project.getBasedir().getAbsolutePath() + File.separator + plistResult);
}

From source file:com.linkedin.pinot.transport.perf.ScatterGatherPerfTester.java

public void run() throws Exception {

    List<ScatterGatherPerfServer> servers = null;

    // Run Servers when mode is RUN_SERVER or RUN_BOTH
    if (_mode != ExecutionMode.RUN_CLIENT) {
        servers = runServer();//from   w  w w.ja  v  a 2  s  .  co m
    }

    if (_mode != ExecutionMode.RUN_SERVER) {
        int port = _startPortNum;
        // Setup Routing config for clients
        RoutingTableConfig config = new RoutingTableConfig();
        Map<String, PerTableRoutingConfig> cfg = config.getPerTableRoutingCfg();
        PerTableRoutingConfig c = new PerTableRoutingConfig(null);
        Map<Integer, List<ServerInstance>> instanceMap = c.getNodeToInstancesMap();
        port = _startPortNum;

        int numUniqueServers = _remoteServerHosts.size();

        for (int i = 0; i < _numServers; i++) {
            List<ServerInstance> instances = new ArrayList<ServerInstance>();
            String server = null;
            if (_mode == ExecutionMode.RUN_BOTH)
                server = "localhost";
            else
                server = _remoteServerHosts.get(i % numUniqueServers);
            ServerInstance instance = new ServerInstance(server, port++);
            instances.add(instance);
            instanceMap.put(i, instances);
        }
        String server = null;
        if (_mode == ExecutionMode.RUN_BOTH)
            server = "localhost";
        else
            server = _remoteServerHosts.get(0);
        c.getDefaultServers().add(new ServerInstance(server, port - 1));
        cfg.put(_resourceName, c);

        System.out.println("Routing Config is :" + cfg);

        // Build Clients
        List<Thread> clientThreads = new ArrayList<Thread>();
        List<ScatterGatherPerfClient> clients = new ArrayList<ScatterGatherPerfClient>();
        AggregatedHistogram<Histogram> latencyHistogram = new AggregatedHistogram<Histogram>();
        for (int i = 0; i < _numClients; i++) {
            ScatterGatherPerfClient c2 = new ScatterGatherPerfClient(config, _requestSize, _resourceName,
                    _asyncRequestDispatch, _numRequests, _maxActiveConnectionsPerClientServerPair,
                    _numResponseReaderThreads);
            Thread t = new Thread(c2);
            clients.add(c2);
            latencyHistogram.add(c2.getLatencyHistogram());
            clientThreads.add(t);
        }

        System.out.println("Starting the clients !!");
        long startTimeMs = 0;
        // Start Clients
        for (Thread t2 : clientThreads)
            t2.start();

        System.out.println("Waiting for clients to finish");

        // Wait for clients to finish
        for (Thread t2 : clientThreads)
            t2.join();

        Thread.sleep(3000);

        System.out.println("Client threads done !!");

        int totalRequestsMeasured = 0;
        long beginRequestTime = Long.MAX_VALUE;
        long endResponseTime = Long.MIN_VALUE;
        for (ScatterGatherPerfClient c3 : clients) {
            int numRequestsMeasured = c3.getNumRequestsMeasured();
            totalRequestsMeasured += numRequestsMeasured;
            beginRequestTime = Math.min(beginRequestTime, c3.getBeginFirstRequestTime());
            endResponseTime = Math.max(endResponseTime, c3.getEndLastResponseTime());
            //System.out.println("2 Num Requests :" + numRequestsMeasured);
            //System.out.println("2 time :" + timeTakenMs );
            //System.out.println("2 Throughput (Requests/Second) :" + ((numRequestsMeasured* 1.0 * 1000)/timeTakenMs));
        }
        long totalTimeTakenMs = endResponseTime - beginRequestTime;
        System.out.println("Overall Total Num Requests :" + totalRequestsMeasured);
        System.out.println("Overall Total time :" + totalTimeTakenMs);
        System.out.println("Overall Throughput (Requests/Second) :"
                + ((totalRequestsMeasured * 1.0 * 1000) / totalTimeTakenMs));
        latencyHistogram.refresh();
        System.out.println("Latency :" + new LatencyMetric<AggregatedHistogram<Histogram>>(latencyHistogram));
    }

    if (_mode == ExecutionMode.RUN_BOTH) {
        // Shutdown Servers
        for (ScatterGatherPerfServer s : servers) {
            s.shutdown();
        }
    }
}

From source file:com.alibaba.jstorm.daemon.worker.Worker.java

private List<TaskShutdownDameon> createTasks() throws Exception {
    List<TaskShutdownDameon> shutdowntasks = new ArrayList<TaskShutdownDameon>();

    Set<Integer> taskids = workerData.getTaskids();

    Set<Thread> threads = new HashSet<Thread>();
    List<Task> taskArrayList = new ArrayList<Task>();
    for (int taskid : taskids) {
        Task task = new Task(workerData, taskid);
        Thread thread = new Thread(task);
        threads.add(thread);/* w  w w.j av a  2s  .  co  m*/
        taskArrayList.add(task);
        thread.start();
    }
    for (Thread thread : threads) {
        thread.join();
    }
    for (Task t : taskArrayList) {
        shutdowntasks.add(t.getTaskShutdownDameon());
    }
    return shutdowntasks;
}