List of usage examples for java.lang Thread join
public final void join() throws InterruptedException
From source file:org.apacheextras.camel.component.neo4j.RestNeo4jProducerCreateRelationshipIntegrationTest.java
@Test public void testCreateNodes() throws InterruptedException { final int messageCount = 100; end.expectedMessageCount(messageCount); Thread t = new Thread(new Runnable() { @Override// w ww . j a va 2 s . com public void run() { for (int k = 0; k < messageCount; k++) { Node start = neo.createNode(); Node end = neo.createNode(); BasicRelationship r = new BasicRelationship(start, end, "tickles"); template.sendBodyAndHeader(r, Neo4jEndpoint.HEADER_OPERATION, Neo4jOperation.CREATE_RELATIONSHIP); } } }); t.start(); t.join(); end.assertIsSatisfied(); }
From source file:com.espertech.esper.regression.nwtable.TestTableMTGroupedAccessReadIntoTableWriteAggColConsistency.java
private void tryMT(int numGroups, int numSeconds) throws Exception { String eplCreateVariable = "create table vartotal (key string primary key, " + CollectionUtil.toString(getDeclareCols()) + ")"; epService.getEPAdministrator().createEPL(eplCreateVariable); String eplInto = "into table vartotal select " + CollectionUtil.toString(getIntoCols()) + " from Local10ColEvent group by groupKey"; epService.getEPAdministrator().createEPL(eplInto); // initialize groups String[] groups = new String[numGroups]; for (int i = 0; i < numGroups; i++) { groups[i] = "G" + i; epService.getEPRuntime().sendEvent(new Local10ColEvent(groups[i], 0)); }// w ww . j ava2 s . com WriteRunnable writeRunnable = new WriteRunnable(epService, groups); ReadRunnable readRunnable = new ReadRunnable(epService, groups); // 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:aiai.ai.core.ExecProcessService.java
public Result execCommand(List<String> cmd, File execDir, File consoleLogFile) throws IOException, InterruptedException { ProcessBuilder pb = new ProcessBuilder(); pb.command(cmd);/*from w w w .ja v a 2 s . c o m*/ pb.directory(execDir); pb.redirectErrorStream(true); final Process process = pb.start(); final StreamHolder streamHolder = new StreamHolder(); int exitCode; try (final FileOutputStream fos = new FileOutputStream(consoleLogFile); BufferedOutputStream bos = new BufferedOutputStream(fos)) { final Thread reader = new Thread(() -> { try { streamHolder.is = process.getInputStream(); int c; while ((c = streamHolder.is.read()) != -1) { bos.write(c); } } catch (IOException e) { log.error("Error collect data from output stream", e); } }); reader.start(); exitCode = process.waitFor(); reader.join(); } finally { try { if (streamHolder.is != null) { streamHolder.is.close(); } } catch (Throwable th) { log.warn("Error with closing InputStream", th); } } log.info("Any errors of execution? {}", (exitCode == 0 ? "No" : "Yes")); log.debug("'\tcmd: {}", cmd); log.debug("'\texecDir: {}", execDir.getPath()); String console = readLastLines(500, consoleLogFile); log.debug("'\tconsole output:\n{}", console); return new Result(exitCode == 0, exitCode, console); }
From source file:com.mmnaseri.dragonfly.runtime.analysis.ApplicationDesignAdvisor.java
@Override public List<DesignIssue> analyze() { final List<DesignIssue> issues = new CopyOnWriteArrayList<DesignIssue>(); final StopWatch stopWatch = new StopWatch(); stopWatch.start();/* w ww.j a v a 2s .c o m*/ log.info("Starting design advisor on " + applicationContext.getDisplayName()); final TaskManager taskManager = new ThreadPoolTaskManager(Runtime.getRuntime().availableProcessors(), true); final Thread analyzerThread = new Thread(taskManager); final SessionPreparator sessionPreparator = applicationContext.getBean(SessionPreparator.class); with(getAnalyzers(sessionPreparator)).each(new Processor<ApplicationDesignAnalyzer>() { @Override public void process(ApplicationDesignAnalyzer applicationDesignAnalyzer) { taskManager.schedule(new AnalyzerTask(applicationDesignAnalyzer, issues)); } }); try { analyzerThread.start(); analyzerThread.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } stopWatch.stop(); log.info("Finished analysis of " + applicationContext.getDisplayName() + " in " + stopWatch.getLastTaskTimeMillis() + "ms"); return issues; }
From source file:com.heisenberg.test.load.LoadTest.java
@Test public void test() { String processDefinitionId = deployProcessDefinition(); long processExecutionsPerThread = 200; long processExecutions = 4 * processExecutionsPerThread; for (int i = 0; i < 20; i++) { runProcessInstance(processDefinitionId); }//w w w. j ava 2 s . com long testStartMillis = System.currentTimeMillis(); long start = System.currentTimeMillis(); Thread t1 = new ProcessInstanceRunner(processDefinitionId, processExecutionsPerThread); Thread t2 = new ProcessInstanceRunner(processDefinitionId, processExecutionsPerThread); Thread t3 = new ProcessInstanceRunner(processDefinitionId, processExecutionsPerThread); Thread t4 = new ProcessInstanceRunner(processDefinitionId, processExecutionsPerThread); t1.start(); t2.start(); t3.start(); t4.start(); try { t1.join(); t2.join(); t3.join(); t4.join(); } catch (InterruptedException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); log.info(processExecutions + " process executions in " + ((end - start) / 1000f) + " seconds"); log.info(processExecutions + " process executions at " + ((processExecutions * 1000f) / (float) (end - start)) + " per second"); workflowEngine.logReport(1000, testStartMillis); }
From source file:com.vmware.photon.controller.cloudstore.xenon.entity.SchedulingConstantGeneratorTest.java
/** * Test distribution of scheduling constants, creating hosts on multiple Xenon * hosts, one thread per Xenon host./* w w w. j a v a2 s . c o m*/ */ @Test(dataProvider = "MultiHostHostCounts") public void testSchedulingConstantVariationMultiHost(int xenonHostCount, int hostCount) throws Throwable { List<Long> schedulingConstants = Collections.synchronizedList(new ArrayList<>()); TestEnvironment env = TestEnvironment.create(xenonHostCount); List<Thread> threads = new ArrayList<>(); ServiceHost[] xenonHosts = env.getHosts(); IntStream.range(0, xenonHostCount).forEach((xenonHostId) -> { Thread t = new Thread(() -> { List<Long> thisThreadSchedulingConstants = createHosts(xenonHosts[xenonHostId], hostCount); schedulingConstants.addAll(thisThreadSchedulingConstants); }); t.start(); threads.add(t); }); for (Thread t : threads) { t.join(); } env.stop(); assertThat(schedulingConstants.size(), equalTo(hostCount * xenonHostCount)); Collections.sort(schedulingConstants); double cv = schedulingConstantGapCV(schedulingConstants); logger.info("Scheduling constant gap coefficient of variation: {}", cv); assertThat(cv, lessThan(MAX_VARIATION)); }
From source file:eu.stratosphere.pact.runtime.task.MapTaskTest.java
@Test public void testCancelMapTask() { addInput(new InfiniteInputIterator()); setOutput(new DiscardingOutputCollector<Record>()); final CollectorMapDriver<Record, Record> testTask = new CollectorMapDriver<Record, Record>(); final AtomicBoolean success = new AtomicBoolean(false); final Thread taskRunner = new Thread() { @Override/*from ww w .ja va 2s . c o m*/ public void run() { try { testDriver(testTask, MockMapStub.class); success.set(true); } catch (Exception ie) { ie.printStackTrace(); } } }; taskRunner.start(); TaskCancelThread tct = new TaskCancelThread(1, taskRunner, this); tct.start(); try { tct.join(); taskRunner.join(); } catch (InterruptedException ie) { Assert.fail("Joining threads failed"); } Assert.assertTrue("Test threw an exception even though it was properly canceled.", success.get()); }
From source file:eu.stratosphere.pact.runtime.task.TempTaskTest.java
@Test public void testCancelTempTask() { super.initEnvironment(1024 * 1024 * 1); super.addInput(new DelayingInfinitiveInputIterator(100), 1); super.addOutput(new NirvanaOutputList()); final TempTask<PactRecord> testTask = new TempTask<PactRecord>(); super.getTaskConfig().setMemorySize(1 * 1024 * 1024); super.registerTask(testTask, PrevStub.class); Thread taskRunner = new Thread() { @Override/*from ww w. jav a 2s . c om*/ public void run() { try { testTask.invoke(); } catch (Exception ie) { ie.printStackTrace(); Assert.fail("Task threw exception although it was properly canceled"); } } }; taskRunner.start(); TaskCancelThread tct = new TaskCancelThread(1, taskRunner, testTask); tct.start(); try { tct.join(); taskRunner.join(); } catch (InterruptedException ie) { Assert.fail("Joining threads failed"); } }
From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
@Test(timeOut = 15000) public void testTunnelToEchoServerThatRespondsFirstAcrossMultipleDrainReadsWithMultipleClients() throws IOException, InterruptedException { MockServer proxyServer = startConnectProxyServer(true, true); Tunnel tunnel = Tunnel.build("localhost", talkFirstEchoServer.getServerSocketPort(), "localhost", proxyServer.getServerSocketPort()); try {// ww w. java2s. c om final int tunnelPort = tunnel.getPort(); List<EasyThread> threads = new ArrayList<EasyThread>(); for (int i = 0; i < 5; i++) { threads.add(new EasyThread() { @Override void runQuietly() throws Exception { try { runClientToTalkFirstServer(tunnelPort); } catch (IOException e) { e.printStackTrace(); } } }.startThread()); } for (Thread t : threads) { t.join(); } assertEquals(proxyServer.getNumConnects(), 5); } finally { proxyServer.stopServer(); tunnel.close(); assertFalse(tunnel.isTunnelThreadAlive()); } }