List of usage examples for java.lang Thread join
public final void join() throws InterruptedException
From source file:com.android.ide.common.process.MtlProcessExecutor.java
private static ListenableFuture<Integer> grabProcessOutput(@NonNull final Process process, @NonNull final ProcessOutput output) { final SettableFuture<Integer> result = SettableFuture.create(); final AtomicReference<Exception> exceptionHolder = new AtomicReference<Exception>(); /*// w w w . ja v a 2 s . c om * It looks like on windows process#waitFor() can return before the thread have filled the * arrays, so we wait for both threads and the process itself. * * To make sure everything is complete before setting the future, the thread handling * "out" will wait for all its input to be read, will wait for the "err" thread to finish * and will wait for the process to finish. Only after all three are done will it set * the future and terminate. * * This means that the future will be set while the "out" thread is still running, but * no output is pending and the process has already finished. */ final Thread threadErr = new Thread("stderr") { @Override public void run() { InputStream stderr = process.getErrorStream(); OutputStream stream = output.getErrorOutput(); try { ByteStreams.copy(stderr, stream); stream.flush(); } catch (IOException e) { exceptionHolder.compareAndSet(null, e); } } }; Thread threadOut = new Thread("stdout") { @Override public void run() { InputStream stdout = process.getInputStream(); OutputStream stream = output.getStandardOutput(); try { ByteStreams.copy(stdout, stream); stream.flush(); } catch (Exception e) { exceptionHolder.compareAndSet(null, e); } try { threadErr.join(); int processResult = process.waitFor(); if (exceptionHolder.get() != null) { result.setException(exceptionHolder.get()); } result.set(processResult); output.close(); } catch (Exception e) { result.setException(e); } } }; threadErr.start(); threadOut.start(); return result; }
From source file:org.apacheextras.camel.component.neo4j.RestNeo4jProducerCreateNodeIntegrationTest.java
@Test public void testCreateNodes() throws InterruptedException { final int messageCount = 100; end.expectedMessageCount(messageCount); Thread t = new Thread(new Runnable() { @Override/* w w w . j a v a2 s . co m*/ public void run() { for (int k = 0; k < messageCount; k++) { template.sendBodyAndHeader(null, Neo4jEndpoint.HEADER_OPERATION, Neo4jOperation.CREATE_NODE); } } }); t.start(); t.join(); end.assertIsSatisfied(); }
From source file:com.tc.process.Exec.java
@SuppressWarnings("resource") public static Result execute(final Process process, String cmd[], String outputLog, byte[] input, File workingDir, final long timeout) throws Exception { final AtomicBoolean processFinished = new AtomicBoolean(); if (timeout > 0) { Thread timeoutThread = new Thread() { @Override//from w w w. j a v a2s . c o m public void run() { ThreadUtil.reallySleep(timeout); if (!processFinished.get()) { process.destroy(); } } }; timeoutThread.start(); } Thread inputThread = new InputPumper(input == null ? new byte[] {} : input, process.getOutputStream()); StreamCollector stderr = null; StreamCollector stdout = null; FileOutputStream fileOutput = null; StreamAppender outputLogger = null; String errString = null; String outString = null; try { if (outputLog != null) { errString = "stderr output redirected to file " + outputLog; outString = "stdout output redirected to file " + outputLog; fileOutput = new FileOutputStream(outputLog); outputLogger = new StreamAppender(fileOutput); outputLogger.writeInput(process.getErrorStream(), process.getInputStream()); } else { stderr = new StreamCollector(process.getErrorStream()); stdout = new StreamCollector(process.getInputStream()); stderr.start(); stdout.start(); } inputThread.start(); final int exitCode = process.waitFor(); processFinished.set(true); inputThread.join(); if (outputLogger != null) { outputLogger.finish(); } if (stderr != null) { stderr.join(); errString = stderr.toString(); } if (stdout != null) { stdout.join(); outString = stdout.toString(); } return new Result(cmd, outString, errString, exitCode); } finally { closeQuietly(fileOutput); } }
From source file:com.healthmarketscience.rmiio.RemoteStreamServerTest.java
@SuppressWarnings("unchecked") public static List<List<File>> mainTest(String[] args, final List<Throwable> clientExceptions, final List<AccumulateRemoteStreamMonitor<?>> monitors) throws Exception { final String testFile = args[0]; final boolean doAbort = ((args.length > 1) ? Boolean.parseBoolean(args[1]) : false); final boolean reverse = ((args.length > 2) ? Boolean.parseBoolean(args[2]) : false); final boolean doSkip = ((args.length > 3) ? Boolean.parseBoolean(args[3]) : false); final boolean doFastTests = ((args.length > 4) ? Boolean.parseBoolean(args[4]) : false); final List<List<File>> tempFiles = Arrays.asList(Collections.synchronizedList(new LinkedList<File>()), Collections.synchronizedList(new LinkedList<File>())); FileServer server = new FileServer(testFile, tempFiles, monitors); final RemoteFileServer stub = (RemoteFileServer) simulateRemote( UnicastRemoteObject.exportObject(server, 0)); LOG.debug("Server ready"); LOG.debug("Sleeping 3000 ms..."); Thread.sleep(3000);/*from w ww . j a v a 2s . c om*/ LOG.debug("Running 'reliable' tests"); Thread clientThread = new Thread(new Runnable() { public void run() { clientExceptions.addAll(FileClient.main(stub, testFile, tempFiles, doAbort, reverse, doSkip, false, doFastTests, monitors)); } }); clientThread.start(); clientThread.join(); if (!doFastTests) { server.setUnreliable(true); LOG.debug("Running 'unreliable' tests"); clientThread = new Thread(new Runnable() { public void run() { clientExceptions.addAll(FileClient.main(stub, testFile, tempFiles, doAbort, reverse, doSkip, true, doFastTests, monitors)); } }); clientThread.start(); clientThread.join(); } LOG.debug("Unexporting server"); UnicastRemoteObject.unexportObject(server, true); return tempFiles; }
From source file:org.openxdata.server.util.LoadTest.java
@Test @Ignore("this test runs a lot of threads performing random service operations - i.e. takes a long time") public void testSimultaneousRandomConnections() throws Exception { long start = System.currentTimeMillis(); System.out.println("Start time: " + new Date()); // find the last test form created (it contains all the test data) List<FormDef> forms = studyManagerService.getForms(); if (forms != null) { for (FormDef form : forms) { FormDefVersion version = form.getDefaultVersion(); if (version != null && version.getName() != null && version.getName().startsWith("dagmar-testformversion-")) { if (this.form == null || this.form.getFormDefVersionId() < version.getFormDefVersionId()) { // first time around, or this version was created later this.form = version; }/*from w w w. java2 s.c om*/ } } if (form == null) { // we didn't find a match in the loop above ... // (perhaps the "testLotsOfData" test was never run) form = forms.get(forms.size() - 1).getDefaultVersion(); } System.out.println("Selected form " + form.getName()); } else { Assert.fail(); // can't continue the test further } // now try a lot of simultaneous random connections System.out.println("Creating the threads"); List<RandomExecutionThread> threads = new ArrayList<RandomExecutionThread>(); for (int i = 0; i < 125; i++) { threads.add(new RandomExecutionThread(i + 1)); } for (Thread thread : threads) { // ensures that the test only stops once the last thread is finished thread.join(); } long end = System.currentTimeMillis(); System.out.println("Time to run test: " + (end - start) + "ms"); int successfulCount = 0; int failedCount = 0; for (RandomExecutionThread thread : threads) { if (thread.isSuccessful()) { successfulCount++; } else { failedCount++; } } System.out.println("Successful calls: " + successfulCount + " Unsuccessful calls: " + failedCount); }
From source file:org.openlmis.performancetesting.ReferenceData.java
public void setupProducts() throws InterruptedException { int createdProductCounter = 0; List<Thread> threads = new ArrayList<>(); for (final Program program : programProductCountMap.keySet()) { final int fullSupplyProductCount = programProductCountMap.get(program).get(0); final int nonFullSupplyProductCount = programProductCountMap.get(program).get(1); createdProductCounter += (fullSupplyProductCount + nonFullSupplyProductCount); Thread thread1 = new Thread() { public void run() { insertProductAndItsMappings(fullSupplyProductCount, program, true); insertProductAndItsMappings(nonFullSupplyProductCount, program, false); }/*from ww w . j a v a 2 s . c om*/ }; threads.add(thread1); thread1.start(); Thread thread2 = new Thread() { public void run() { insertProductAndItsMappings(nonFullSupplyProductCount, program, false); } }; threads.add(thread2); thread2.start(); } for (; createdProductCounter < TOTAL_NO_OF_PRODUCTS; createdProductCounter++) { ProductForm productForm = productForms.get(valueOf(randomNumeric(3)) % productForms.size()); DosageUnit dosageUnit = dosageUnits.get(valueOf(randomNumeric(3)) % dosageUnits.size()); ProductCategory category = productCategories.get(valueOf(randomNumeric(3)) % productCategories.size()); productData.insertProduct(productForm, dosageUnit, category, nextBoolean()); } for (Thread thread : threads) { thread.join(); } }
From source file:eu.stratosphere.client.minicluster.NepheleMiniCluster.java
public void start() throws Exception { synchronized (startStopLock) { // set up the global configuration if (this.configDir != null) { GlobalConfiguration.loadConfiguration(configDir); } else {//ww w . j av a2 s . c o m Configuration conf = getMiniclusterDefaultConfig(jobManagerRpcPort, taskManagerRpcPort, taskManagerDataPort, memorySize, hdfsConfigFile, lazyMemoryAllocation, defaultOverwriteFiles, defaultAlwaysCreateDirectory, numTaskManager); GlobalConfiguration.includeConfiguration(conf); } // force the input/output format classes to load the default values from the configuration. // we need to do this here, because the format classes may have been initialized before the mini cluster was started initializeIOFormatClasses(); // before we start the JobManager, we need to make sure that there are no lingering IPC threads from before // check that all threads are done before we return Thread[] allThreads = new Thread[Thread.activeCount()]; int numThreads = Thread.enumerate(allThreads); for (int i = 0; i < numThreads; i++) { Thread t = allThreads[i]; String name = t.getName(); if (name.startsWith("IPC")) { t.join(); } } // start the job manager jobManager = new JobManager(ExecutionMode.LOCAL); waitForJobManagerToBecomeReady(numTaskManager); } }
From source file:Pool146.java
public void testBlockedKeyDoesNotBlockPoolImproved() throws Exception { SimpleFactory factory = new SimpleFactory(); GenericKeyedObjectPool pool = new GenericKeyedObjectPool(factory); pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK); pool.setMaxActive(1);/*from w ww . j a v a2s . c om*/ pool.setMaxTotal(-1); // Borrow with one key Object obj = pool.borrowObject("one"); // Borrow again with same key, should be blocked Runnable simple = new SimpleTestThread(pool, "one"); Thread borrowThread = new Thread(simple); borrowThread.start(); pool.borrowObject("two"); assert (pool.getNumActive("one") == 1); assert (pool.getNumActive("two") == 1); // Unblock and join the thread pool.returnObject("one", obj); borrowThread.join(); assert (pool.getNumActive("one") == 0); assert (pool.getNumActive("two") == 1); }
From source file:com.thoughtworks.go.util.pool.DigestObjectPoolsTest.java
@Test public void shouldCreateDigestOnlyIfItIsNotAlreadyInitializedOnThreads() throws NoSuchAlgorithmException, InterruptedException { DigestObjectPools.CreateDigest creator = mock(DigestObjectPools.CreateDigest.class); when(creator.create(DigestObjectPools.SHA_256)) .thenReturn(MessageDigest.getInstance(DigestObjectPools.SHA_256)); final DigestObjectPools pools = new DigestObjectPools(creator); try {//from w w w . j av a2 s .c o m final DigestObjectPools.DigestOperation operation = mock(DigestObjectPools.DigestOperation.class); pools.computeDigest(DigestObjectPools.SHA_256, operation); pools.computeDigest(DigestObjectPools.SHA_256, operation); Thread thread = new Thread(new Runnable() { public void run() { pools.computeDigest(DigestObjectPools.SHA_256, operation); pools.computeDigest(DigestObjectPools.SHA_256, operation); } }); thread.start(); thread.join(); verify(creator, times(2)).create(DigestObjectPools.SHA_256); verifyNoMoreInteractions(creator); } finally { pools.clearThreadLocals(); } }
From source file:org.eclipse.mylyn.commons.repositories.http.tests.CommonHttpClientTest.java
@Test public void testHttpContextPerThread() throws Exception { RepositoryLocation location = new RepositoryLocation("http://mylyn.org/"); final CommonHttpClient client = new CommonHttpClient(location); final AtomicReference<HttpContext> otherThreadContext = new AtomicReference<HttpContext>(); Thread t = new Thread() { @Override/*from ww w. jav a 2 s. c o m*/ public void run() { otherThreadContext.set(client.getContext()); }; }; t.start(); t.join(); assertNotNull(otherThreadContext.get()); assertNotNull(client.getContext()); assertFalse(otherThreadContext.get() == client.getContext()); }