List of usage examples for java.lang Thread join
public final void join() throws InterruptedException
From source file:org.killbill.queue.TestDBBackedQueue.java
@Test(groups = "slow") public void testWithOneReaderOneWriter() throws InterruptedException { final PersistentBusConfig config = createConfig(7, 100, false, true); queue = new DBBackedQueue<BusEventModelDao>(clock, sqlDao, config, "oneReaderOneWriter-bus_event", metricRegistry, databaseTransactionNotificationApi); queue.initialize();/*from w ww.j a v a 2s.c o m*/ Thread writer = new Thread(new WriterRunnable(0, 1000, queue)); final AtomicLong consumed = new AtomicLong(0); final ReaderRunnable readerRunnable = new ReaderRunnable(0, consumed, 1000, queue); final Thread reader = new Thread(readerRunnable); writer.start(); while (queue.isQueueOpenForWrite()) { try { Thread.sleep(10); } catch (InterruptedException e) { } } reader.start(); try { writer.join(); reader.join(); } catch (InterruptedException e) { Assert.fail("InterruptedException ", e); } final List<BusEventModelDao> ready = sqlDao.getReadyEntries(clock.getUTCNow().toDate(), 1000, OWNER, "bus_events"); assertEquals(ready.size(), 0); log.info("Got inflightProcessed = " + queue.getTotalInflightFetched() + "/1000, inflightWritten = " + queue.getTotalInflightInsert() + "/1000"); assertEquals(queue.getTotalInsert(), 1000L); // Verify ordering long expected = 999; for (Long cur : readerRunnable.getSearch1()) { assertEquals(cur.longValue(), expected); expected--; } }
From source file:com.tikal.tallerWeb.control.imp.StartupControllerImp.java
private void phaseCatalogos() { try {// w w w .j a va 2s . c o m Thread warmupCustomer = new Thread(new Runnable() { @Override public void run() { // TaskStatusView taskViewClientes = new TaskStatusView("Cargando cat\u00E1logo de clientes"); // appStartView.addTask(taskViewClientes); // app.warmupCustomer(); // taskViewClientes.setCompleted(true); // appStartView.recalculateMsg(); } }); warmupCustomer.start(); Thread warmupAuto = new Thread(new Runnable() { @Override public void run() { // TaskStatusView taskViewAutos = new TaskStatusView("Cargando cat\u00E1logo de autos"); // appStartView.addTask(taskViewAutos); // app.warmupAutoIndex(); // taskViewAutos.setCompleted(true); // appStartView.recalculateMsg(); } }); warmupAuto.start(); warmupCustomer.join(); warmupAuto.join(); // TaskStatusView taskViewServicios = new TaskStatusView("Cargando cat\u00E1logo de servicios"); // appStartView.addTask(taskViewServicios); // app.warmupServicioIndex(); // taskViewServicios.setCompleted(true); // appStartView.recalculateMsg(); } catch (InterruptedException ex) { Logger.getLogger(StartupControllerImp.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.cloudbees.hudson.plugins.folder.computed.EventOutputStreamsTest.java
public void test(final boolean aFlush, final boolean bFlush) throws Exception { final File file = work.newFile(); final EventOutputStreams instance = new EventOutputStreams(new EventOutputStreams.OutputFile() { @NonNull// w w w . jav a 2 s .c om @Override public File get() { return file; } }, 250, TimeUnit.MILLISECONDS, 8192, false, Long.MAX_VALUE, 0); Thread t1 = new Thread() { public void run() { OutputStream os = instance.get(); try { PrintWriter pw = new PrintWriter(os, aFlush); for (int i = 0; i < 10000; i += 1) { pw.println(String.format("%1$05dA", i)); } pw.flush(); } catch (Throwable e) { e.printStackTrace(System.err); } finally { IOUtils.closeQuietly(os); } } }; Thread t2 = new Thread() { public void run() { OutputStream os = instance.get(); try { PrintWriter pw = new PrintWriter(os, bFlush); for (int i = 0; i < 10000; i += 1) { pw.println(String.format("%1$05dB", i)); } pw.flush(); } catch (Throwable e) { e.printStackTrace(System.err); } finally { IOUtils.closeQuietly(os); } } }; t1.start(); t2.start(); t1.join(); t2.join(); List<String> as = new ArrayList<String>(); List<String> bs = new ArrayList<String>(); for (String line : FileUtils.readLines(file)) { assertThat("Line does not have both thread output: '" + StringEscapeUtils.escapeJava(line) + "'", line.matches("^\\d+[AB](\\d+[AB])+$"), is(false)); assertThat("Line does not contain a null character: '" + StringEscapeUtils.escapeJava(line) + "'", line.indexOf(0), is(-1)); if (line.endsWith("A")) { as.add(line); } else if (line.endsWith("B")) { bs.add(line); } else { fail("unexpected line: '" + StringEscapeUtils.escapeJava(line) + "'"); } } List<String> sorted = new ArrayList<String>(as); Collections.sort(sorted); assertThat(as, is(sorted)); sorted = new ArrayList<String>(bs); Collections.sort(sorted); assertThat(bs, is(sorted)); }
From source file:org.apache.camel.component.mongodb.MongoDbTailableCursorConsumerTest.java
@Test public void testHundredThousandRecords() throws Exception { assertEquals(0, cappedTestCollection.count()); final MockEndpoint mock = getMockEndpoint("mock:test"); mock.expectedMessageCount(1000);// ww w . j av a2s .com // create a capped collection with max = 1000 cappedTestCollection = db.createCollection(cappedTestCollectionName, BasicDBObjectBuilder.start().add("capped", true).add("size", 1000000000).add("max", 1000).get()); addTestRoutes(); context.startRoute("tailableCursorConsumer1"); // continuous pump of 100000 records, asserting incrementally to reduce overhead on the mock endpoint Thread t = new Thread(new Runnable() { @Override public void run() { for (int i = 1; i <= 100000; i++) { cappedTestCollection.insert( BasicDBObjectBuilder.start("increasing", i).add("string", "value" + i).get(), WriteConcern.SAFE); // incrementally assert, as the mock endpoint stores all messages and otherwise the test would be sluggish if (i % 1000 == 0) { try { MongoDbTailableCursorConsumerTest.this.assertAndResetMockEndpoint(mock); } catch (Exception e) { return; } } } } }); // start the data pumping t.start(); // before we stop the route, wait for the data pumping to end t.join(); context.stopRoute("tailableCursorConsumer1"); }
From source file:org.ulyssis.ipp.control.CommandDispatcher.java
public void run() { Thread statusThread = new Thread(() -> { try {/*ww w.java 2 s .c o m*/ while (!Thread.currentThread().isInterrupted()) { try { JedisHelper.get(redisUri).subscribe(createResultListener(), statusChannel); } catch (JedisConnectionException e) { // TODO: After a while, deregister the processor? LOG.error("Connection with Redis was broken! Trying again in 0.5s.", e); Thread.sleep(500L); } } } catch (InterruptedException ignored) { } }); statusThread.start(); while (!Thread.interrupted()) { try { Command command = commandsToSend.take(); LOG.debug("Sending command {}", command.getCommandId()); jedis.publish(controlChannel, Serialization.getJsonMapper().writeValueAsBytes(command)); } catch (InterruptedException ignored) { } catch (JsonProcessingException e) { LOG.error("Error writing command as JSON object", e); } } statusThread.interrupt(); try { statusThread.join(); } catch (InterruptedException ignored) { } }
From source file:io.openvidu.server.recording.service.RecordingManager.java
public void initializeRecordingManager() throws OpenViduException { RecordingManager.IMAGE_TAG = openviduConfig.getOpenViduRecordingVersion(); this.dockerManager = new DockerManager(); this.composedRecordingService = new ComposedRecordingService(this, openviduConfig); this.singleStreamRecordingService = new SingleStreamRecordingService(this, openviduConfig); log.info("Recording module required: Downloading openvidu/openvidu-recording:" + openviduConfig.getOpenViduRecordingVersion() + " Docker image (350MB aprox)"); this.checkRecordingRequirements(this.openviduConfig.getOpenViduRecordingPath(), this.openviduConfig.getOpenviduRecordingCustomLayout()); if (dockerManager.dockerImageExistsLocally(IMAGE_NAME + ":" + IMAGE_TAG)) { log.info("Docker image already exists locally"); } else {//w w w . j a v a 2s . co m Thread t = new Thread(() -> { boolean keep = true; log.info("Downloading "); while (keep) { System.out.print("."); try { Thread.sleep(1000); } catch (InterruptedException e) { keep = false; log.info("\nDownload complete"); } } }); t.start(); try { dockerManager.downloadDockerImage(IMAGE_NAME + ":" + IMAGE_TAG, 600); } catch (Exception e) { log.error("Error downloading docker image {}:{}", IMAGE_NAME, IMAGE_TAG); } t.interrupt(); try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } log.info("Docker image available"); } // Clean any stranded openvidu/openvidu-recording container on startup dockerManager.cleanStrandedContainers(RecordingManager.IMAGE_NAME); }
From source file:com.thoughtworks.go.server.service.BuildAssignmentServiceIntegrationTest.java
@Test public void shouldNotReloadScheduledJobPlansWhenAgentWorkAssignmentIsInProgress() throws Exception { fixture.createPipelineWithFirstStageScheduled(); Pipeline pipeline = pipelineDao.mostRecentPipeline(fixture.pipelineName); JobInstance job = pipeline.getFirstStage().getJobInstances().first(); final JobInstanceService mockJobInstanceService = mock(JobInstanceService.class); final Pipeline pipeline1 = pipeline; final Semaphore sem = new Semaphore(1); sem.acquire();//from ww w. jav a 2 s . co m when(mockJobInstanceService.orderedScheduledBuilds()) .thenReturn(jobInstanceService.orderedScheduledBuilds()); when(mockJobInstanceService.buildByIdWithTransitions(job.getId())) .thenReturn(jobInstanceService.buildByIdWithTransitions(job.getId())); ScheduledPipelineLoader scheduledPipelineLoader = new ScheduledPipelineLoader(null, null, null, null, null, null, null, null) { @Override public Pipeline pipelineWithPasswordAwareBuildCauseByBuildId(long buildId) { sem.release(); sleepQuietly(1000); verify(mockJobInstanceService, times(1)).orderedScheduledBuilds(); return pipeline1; } }; final BuildAssignmentService buildAssignmentServiceUnderTest = new BuildAssignmentService(goConfigService, mockJobInstanceService, scheduleService, agentService, environmentConfigService, transactionTemplate, scheduledPipelineLoader, pipelineService, builderFactory, maintenanceModeService, elasticAgentPluginService, systemEnvironment, secretParamResolver, jobStatusTopic, consoleService); final Throwable[] fromThread = new Throwable[1]; buildAssignmentServiceUnderTest.onTimer(); Thread assigner = new Thread(() -> { try { final AgentConfig agentConfig = AgentMother.localAgentWithResources("some-other-resource"); buildAssignmentServiceUnderTest.assignWorkToAgent(agent(agentConfig)); } catch (Throwable e) { e.printStackTrace(); fromThread[0] = e; } finally { } }, "assignmentThread"); assigner.start(); sem.acquire(); buildAssignmentServiceUnderTest.onTimer(); assigner.join(); assertThat(fromThread[0], is(nullValue())); }
From source file:mitm.common.util.ProcessRunner.java
public int run(List<String> cmd) throws IOException { if (cmd == null || cmd.size() == 0) { throw new IllegalArgumentException("cmd is invalid."); }/*from w ww .j av a 2 s. c o m*/ /* * Used to show which command was executed */ String cmdLine = logArguments ? StringUtils.join(cmd, ",") : cmd.get(0); logger.debug("Starting application. cmdLine: " + cmdLine); /* * Watchdog that will be used to destroy the process on a timeout */ TaskScheduler watchdog = new TaskScheduler(ProcessRunner.class.getCanonicalName() + "#" + cmdLine); try { ProcessBuilder processBuilder = new ProcessBuilder(cmd); Process process = processBuilder.start(); if (timeout > 0) { /* * Task that will destroy the process on a timeout */ Task processWatchdogTask = new DestroyProcessTimeoutTask(process, watchdog.getName()); watchdog.addTask(processWatchdogTask, timeout); /* * Task that will interrupt the current thread on a timeout */ Task threadInterruptTimeoutTask = new ThreadInterruptTimeoutTask(Thread.currentThread(), watchdog.getName()); watchdog.addTask(threadInterruptTimeoutTask, timeout); } Thread inputThread = null; Thread outputThread = null; Thread errorThread = null; if (input != null) { inputThread = new StreamCopier(input, process.getOutputStream(), "input", false, true); inputThread.start(); } if (output != null) { outputThread = new StreamCopier(process.getInputStream(), output, "output", true, false); outputThread.start(); } if (error != null) { errorThread = new StreamCopier(process.getErrorStream(), error, "error", true, false); errorThread.start(); } try { exitCode = process.waitFor(); /* * We need to wait for the threads to finish because otherwise there is * a chance we will start using the output before all the output has been * written/read. */ if (inputThread != null) { inputThread.join(); } if (outputThread != null) { outputThread.join(); } if (errorThread != null) { errorThread.join(); } /* * We MUST close the standard streams otherwise some "FIFO pipes" won't be closed until * the garbage collector is run. If there are too many open "FIFO pipes", the following * exception might occur: * * java.io.IOException: error=24, Too many open files * * Closing the standard streams makes sure that the pipes are closed. * * Note: The Javadoc for Process does not mention that you should close the standard streams * even if not used. Perhaps they rely on the GC? * * Note2: The number of FIFI pipes can be counted with: * * lsof | grep java | grep pipe | wc -l */ IOUtils.closeQuietly(process.getInputStream()); IOUtils.closeQuietly(process.getOutputStream()); IOUtils.closeQuietly(process.getErrorStream()); } catch (InterruptedException e) { throw new IOException("Error running [" + cmdLine + "]", e); } if (exitCode != successExitCode) { throw new ProcessException("Error running [" + cmdLine + "]. exit value: " + exitCode, exitCode); } } finally { logger.debug("Application finished. cmdLine: " + cmdLine); /* * Need to cancel any pending watchdog tasks */ watchdog.cancel(); } return exitCode; }
From source file:com.feedhenry.sdk.tests.api.FHSDKTest.java
private void runAsyncRequest(final FHAct pRequest, final FHActCallback pCallback) throws Exception { // The AsyncHttpClient uses Looper & Handlers to implement async http calls. // It requires the calling thread to have a looper attached to it. // When requests are made from the main UI thread, it will work find as the // main UI thread contains a main Looper. // However, if the app creates another Thread which will be used to invoke // the call, it should use the sync mode or attach the looper to the thread // as demoed below. // The main thread that runs the tests doesn't work with Handlers either. Thread testThread = new Thread() { @Override/*from ww w . java2 s .c o m*/ public void run() { try { Looper.prepare(); pRequest.executeAsync(new FHActCallback() { @Override public void success(FHResponse pResponse) { System.out.println("Got response " + pResponse.getRawResponse()); pCallback.success(pResponse); Looper.myLooper().quit(); } @Override public void fail(FHResponse pResponse) { System.out.println("Got error response : " + pResponse.getRawResponse()); pCallback.fail(pResponse); Looper.myLooper().quit(); } }); Looper.loop(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; testThread.start(); testThread.join(); }
From source file:com.thoughtworks.go.config.GoConfigDataSourceTest.java
@Test public void shouldBeAbleToConcurrentAccess() throws Exception { GoConfigFileHelper helper = new GoConfigFileHelper( loadAndMigrate(ConfigFileFixture.CONFIG_WITH_NANT_AND_EXEC_BUILDER)); final String xml = FileUtil.readContentFromFile(helper.getConfigFile()); final List<Exception> errors = new Vector<Exception>(); Thread thread1 = new Thread(new Runnable() { public void run() { for (int i = 0; i < 5; i++) { try { goConfigFileDao.updateMailHost(new MailHost("hostname", 9999, "user", "password", false, false, "from@local", "admin@local")); } catch (Exception e) { e.printStackTrace(); errors.add(e);/* w w w. ja v a 2 s . c o m*/ } } } }, "Update-license"); Thread thread2 = new Thread(new Runnable() { public void run() { for (int i = 0; i < 5; i++) { try { dataSource.write(xml, false); } catch (Exception e) { e.printStackTrace(); errors.add(e); } } } }, "Modify-config"); thread1.start(); thread2.start(); thread1.join(); thread2.join(); assertThat(errors.size(), is(0)); }