List of usage examples for java.lang Thread join
public final void join() throws InterruptedException
From source file:com.thoughtworks.go.domain.BuildComposerTest.java
@Test public void shouldRunCancelTaskWhenBuildIsCanceled() throws Exception { final Exception[] err = { null }; Thread buildThread = new Thread(new Runnable() { @Override/*from ww w .j a v a 2 s .c o m*/ public void run() { try { build(SystemUtil.isWindows() ? SLEEP_TEN_SECONDS_ON_WINDOWS : SLEEP_TEN_SECONDS_ON_UNIX, PIPELINE_NAME, true, false); } catch (Exception e) { err[0] = e; } } }); buildThread.start(); console.waitForContain("before sleep", Timeout.FIVE_SECONDS); assertTrue(buildSession.cancel(30, TimeUnit.SECONDS)); assertThat(statusReporter.status(), is(Arrays.asList(Preparing, Building, Completed))); assertThat(statusReporter.results(), is(Collections.singletonList(Cancelled))); assertThat(console.output(), printedJobCompletedInfo(JOB_IDENTIFIER.buildLocatorForDisplay())); assertThat(console.output(), printedJobCanceledInfo(JOB_IDENTIFIER.buildLocatorForDisplay())); assertThat(console.output(), containsString("executing on cancel task")); buildThread.join(); if (err[0] != null) { throw err[0]; } }
From source file:com.symbian.driver.core.environment.TDConfigTest.java
public void testGetSetBuildNumber() { try {/*from w w w.jav a 2 s. c o m*/ String lBuildNumber = CONFIG.getPreference(TDConfig.BUILD_NUMBER); System.out.println("First Build Number: " + lBuildNumber); String lTest = "Test123"; CONFIG.setPreference(TDConfig.BUILD_NUMBER, lTest); lBuildNumber = CONFIG.getPreference(TDConfig.BUILD_NUMBER); System.out.println("Second Build Number: " + lBuildNumber); if (!lBuildNumber.equals(lTest)) { fail(); } lBuildNumber = CONFIG.getPreference(TDConfig.BUILD_NUMBER); System.out.println("Third Build Number: " + lBuildNumber); if (!lBuildNumber.equals(lTest)) { fail(); } int lCount = 0; while (lCount < 10) { lCount++; final String lTest2 = Integer.toString(lCount); CONFIG.setPreference(TDConfig.BUILD_NUMBER, lTest2); Thread lThread = new Thread() { public void run() { try { String lBuildNumber = CONFIG.getPreference(TDConfig.BUILD_NUMBER); System.out.println("Forth Build Number: " + lBuildNumber); if (!lBuildNumber.equals(lTest2)) { fail(); } } catch (ParseException e) { e.printStackTrace(); fail(); } } }; lThread.start(); lThread.join(); } } catch (ParseException e) { e.printStackTrace(); fail(); } catch (InterruptedException e) { e.printStackTrace(); fail(); } }
From source file:edu.illinois.imunit.examples.apache.collections.TestBlockingBuffer.java
/** * Tests {@link BlockingBuffer#remove()} in combination with {@link BlockingBuffer#addAll(java.util.Collection)} * using multiple read threads./* w w w . ja v a 2 s.c o m*/ * <p/> * Two read threads should block on an empty buffer until a collection with two distinct objects is added then both * threads should complete. Each thread should have read a different object. * @throws InterruptedException */ @Test @Schedules({ @Schedule(name = "BlockedRemoveWithAddAll2", value = "[beforeNullRemove: afterNullRemove]@readThread1->beforeAddAll@main," + "[beforeNullRemove: afterNullRemove]@readThread2->beforeAddAll@main," + "afterNullRemove@readThread1->afterAddAll@main," + "afterNullRemove@readThread2->afterAddAll@main") }) public void testBlockedRemoveWithAddAll2() throws InterruptedException { Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer()); Object obj1 = new Object(); Object obj2 = new Object(); Set objs = Collections.synchronizedSet(new HashSet()); objs.add(obj1); objs.add(obj2); // run methods will remove and compare -- must wait for addAll Thread thread1 = new ReadThread(blockingBuffer, objs, "remove", "BlockedRemoveWithAddAll2", "readThread1"); Thread thread2 = new ReadThread(blockingBuffer, objs, "remove", "BlockedRemoveWithAddAll2", "readThread2"); thread1.start(); thread2.start(); // give hungry read threads ample time to hang try { // Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } fireEvent("beforeAddAll"); blockingBuffer.addAll(objs); // allow notified threads to complete try { // Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } fireEvent("afterAddAll"); assertEquals("BlockedRemoveWithAddAll2", 0, objs.size()); // There should not be any threads waiting. thread1.join(); thread2.join(); //assertFalse( "BlockedRemoveWithAddAll1", thread1.isAlive() || thread2.isAlive() ); //if( thread1.isAlive() || thread2.isAlive() ) { //fail( "Live thread(s) when both should be dead." ); //} }
From source file:com.twitter.distributedlog.lock.TestDistributedLock.java
@Test(timeout = 60000) public void testCheckWriteLockFailureWhenLockIsAcquiredByOthers() throws Exception { String lockPath = "/test-check-write-lock-failure-when-lock-is-acquired-by-others-" + System.currentTimeMillis(); String clientId = "test-check-write-lock-failure"; createLockPath(zkc.get(), lockPath); SessionLockFactory lockFactory0 = createLockFactory(clientId, zkc0); ZKDistributedLock lock0 = new ZKDistributedLock(lockStateExecutor, lockFactory0, lockPath, Long.MAX_VALUE, NullStatsLogger.INSTANCE);//from w w w . j a va2s .c om FutureUtils.result(lock0.asyncAcquire()); Pair<String, Long> lockId0_1 = ((ZKSessionLock) lock0.getInternalLock()).getLockId(); List<String> children = getLockWaiters(zkc, lockPath); assertEquals(1, children.size()); assertTrue(lock0.haveLock()); assertEquals(lockId0_1, Await.result(asyncParseClientID(zkc0.get(), lockPath, children.get(0)))); // expire the session ZooKeeperClientUtils.expireSession(zkc0, zkServers, sessionTimeoutMs); // reacquire the lock and wait reacquire completed checkLockAndReacquire(lock0, true); Pair<String, Long> lockId0_2 = ((ZKSessionLock) lock0.getInternalLock()).getLockId(); assertFalse("New lock should be created under different session", lockId0_1.equals(lockId0_2)); children = getLockWaiters(zkc, lockPath); assertEquals(1, children.size()); assertTrue(lock0.haveLock()); assertEquals(lockId0_2, Await.result(asyncParseClientID(zkc0.get(), lockPath, children.get(0)))); SessionLockFactory lockFactory = createLockFactory(clientId, zkc); final ZKDistributedLock lock1 = new ZKDistributedLock(lockStateExecutor, lockFactory, lockPath, Long.MAX_VALUE, NullStatsLogger.INSTANCE); final CountDownLatch lockLatch = new CountDownLatch(1); Thread lockThread = new Thread(new Runnable() { @Override public void run() { try { FutureUtils.result(lock1.asyncAcquire()); lockLatch.countDown(); } catch (IOException e) { logger.error("Failed on locking lock1 : ", e); } } }, "lock-thread"); lockThread.start(); // ensure lock1 is waiting for lock0 do { Thread.sleep(1); children = getLockWaiters(zkc, lockPath); } while (children.size() < 2); // expire the session ZooKeeperClientUtils.expireSession(zkc0, zkServers, sessionTimeoutMs); lockLatch.await(); lockThread.join(); try { checkLockAndReacquire(lock0, true); fail("Should fail on checking write lock since lock is acquired by lock1"); } catch (LockingException le) { // expected } try { checkLockAndReacquire(lock0, false); fail("Should fail on checking write lock since lock is acquired by lock1"); } catch (LockingException le) { // expected } }
From source file:com.ficeto.esp.EspExceptionDecoder.java
private int listenOnProcess(String[] arguments) { try {/* w w w .ja v a 2 s. c om*/ final Process p = ProcessUtils.exec(arguments); Thread thread = new Thread() { public void run() { try { InputStreamReader reader = new InputStreamReader(p.getInputStream()); int c; String line = ""; while ((c = reader.read()) != -1) { if ((char) c == '\r') continue; if ((char) c == '\n') { printLine(line); line = ""; } else { line += (char) c; } } printLine(line); reader.close(); reader = new InputStreamReader(p.getErrorStream()); while ((c = reader.read()) != -1) System.err.print((char) c); reader.close(); } catch (Exception e) { } } }; thread.start(); int res = p.waitFor(); thread.join(); return res; } catch (Exception e) { } return -1; }
From source file:com.facebook.notifications.NotificationsManager.java
/** * Present a {@link Notification} to be presented from a GCM push bundle. * <p/>//from w ww . j ava 2 s . c om * This does not present a notification immediately, instead it caches the assets from the * notification bundle, and then presents a notification to the user. This allows for a smoother * interaction without loading indicators for the user. * <p/> * Note that only one notification can be created for a specific push bundle, should you attempt * to present a new notification with the same payload bundle as an existing notification, it will * replace and update the old notification. * * @param context The context to send the notification from * @param notificationBundle The content of the push notification * @param launcherIntent The launcher intent that contains your Application's activity. * This will be modified with the FLAG_ACTIVITY_CLEAR_TOP and * FLAG_ACTIVITY_SINGLE_TOP flags, in order to properly show the * notification in an already running application. * <p/> * Should you not want this behavior, you may use the notificationExtender * parameter to customize the contentIntent of the notification before * presenting it. * @param notificationExtender A nullable argument that allows you to customize the notification * before displaying it. Use this to configure Icons, text, sounds, * etc. before we pass the notification off to the OS. */ public static boolean presentNotification(@NonNull final Context context, @NonNull final Bundle notificationBundle, @NonNull final Intent launcherIntent, @Nullable final NotificationExtender notificationExtender) { final JSONObject alert; final int payloadHash; try { String payload = notificationBundle.getString(CARD_PAYLOAD_KEY); if (payload == null) { return false; } payloadHash = payload.hashCode(); JSONObject payloadObject = new JSONObject(payload); alert = payloadObject.optJSONObject("alert") != null ? payloadObject.optJSONObject("alert") : new JSONObject(); } catch (JSONException ex) { Log.e(LOG_TAG, "Error while parsing notification bundle JSON", ex); return false; } final boolean[] success = new boolean[1]; final Thread backgroundThread = new Thread(new Runnable() { @Override public void run() { Looper.prepare(); prepareCard(context, notificationBundle, new PrepareCallback() { @Override public void onPrepared(@NonNull Intent presentationIntent) { Intent contentIntent = new Intent(launcherIntent); contentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); contentIntent.putExtra(EXTRA_PAYLOAD_INTENT, presentationIntent); NotificationManager manager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); Notification.Builder builder = new Notification.Builder(context) .setSmallIcon(android.R.drawable.ic_dialog_alert) .setContentTitle(alert.optString("title")).setContentText(alert.optString("body")) .setAutoCancel(true) .setContentIntent(PendingIntent.getActivity(context.getApplicationContext(), payloadHash, contentIntent, PendingIntent.FLAG_ONE_SHOT)); if (notificationExtender != null) { builder = notificationExtender.extendNotification(builder); } manager.notify(NOTIFICATION_TAG, payloadHash, builder.getNotification()); success[0] = true; Looper.myLooper().quit(); } @Override public void onError(@NonNull Exception exception) { Log.e(LOG_TAG, "Error while preparing card", exception); Looper.myLooper().quit(); } }); Looper.loop(); } }); backgroundThread.start(); try { backgroundThread.join(); } catch (InterruptedException ex) { Log.e(LOG_TAG, "Failed to wait for background thread", ex); return false; } return success[0]; }
From source file:edu.illinois.enforcemop.examples.apache.collections.TestBlockingBuffer.java
/** * Tests {@link BlockingBuffer#remove()} in combination with {@link BlockingBuffer#addAll(java.util.Collection)} * using multiple read threads.//from w w w . java 2 s . com * <p/> * Two read threads should block on an empty buffer until a collection with two distinct objects is added then both * threads should complete. Each thread should have read a different object. * @throws InterruptedException */ @Test // @Schedules({ // @Schedule(name = "BlockedRemoveWithAddAll2", sequence = "[beforeNullRemove: afterNullRemove]@readThread1->beforeAddAll@main," + // "[beforeNullRemove: afterNullRemove]@readThread2->beforeAddAll@main," + // "afterNullRemove@readThread1->afterAddAll@main," + "afterNullRemove@readThread2->afterAddAll@main") }) public void testBlockedRemoveWithAddAll2() throws InterruptedException { Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer()); Object obj1 = new Object(); Object obj2 = new Object(); Set objs = Collections.synchronizedSet(new HashSet()); objs.add(obj1); objs.add(obj2); // run methods will remove and compare -- must wait for addAll Thread thread1 = new ReadThread(blockingBuffer, objs, "remove", "BlockedRemoveWithAddAll2", "readThread1"); Thread thread2 = new ReadThread(blockingBuffer, objs, "remove", "BlockedRemoveWithAddAll2", "readThread2"); thread1.start(); thread2.start(); // give hungry read threads ample time to hang try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } /* @Event("beforeAddAll")*/ blockingBuffer.addAll(objs); // allow notified threads to complete try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } /* @Event("afterAddAll")*/ assertEquals("BlockedRemoveWithAddAll2", 0, objs.size()); // There should not be any threads waiting. thread1.join(); thread2.join(); //assertFalse( "BlockedRemoveWithAddAll1", thread1.isAlive() || thread2.isAlive() ); //if( thread1.isAlive() || thread2.isAlive() ) { //fail( "Live thread(s) when both should be dead." ); //} }
From source file:TestFuseDFS.java
/** * Test concurrent creation and access of the mount *///from www.ja v a 2 s. c o m @Test public void testMultipleThreads() throws IOException { ArrayList<Thread> threads = new ArrayList<Thread>(); final AtomicReference<String> errorMessage = new AtomicReference<String>(); for (int i = 0; i < 10; i++) { Thread t = new Thread() { public void run() { try { File d = new File(mountPoint, "dir" + getId()); execWaitRet("mkdir " + d.getAbsolutePath()); for (int j = 0; j < 10; j++) { File f = new File(d, "file" + j); final String contents = "thread " + getId() + " " + j; createFile(f, contents); } for (int j = 0; j < 10; j++) { File f = new File(d, "file" + j); execWaitRet("cat " + f.getAbsolutePath()); execWaitRet("rm " + f.getAbsolutePath()); } execWaitRet("rmdir " + d.getAbsolutePath()); } catch (IOException ie) { errorMessage.set(String.format("Exception %s", StringUtils.stringifyException(ie))); } } }; t.start(); threads.add(t); } for (Thread t : threads) { try { t.join(); } catch (InterruptedException ie) { fail("Thread interrupted: " + ie.getMessage()); } } assertNull(errorMessage.get(), errorMessage.get()); }
From source file:org.terasoluna.gfw.common.exception.ResultMessagesLoggingInterceptorTest.java
/** * [invoke] Case of occur BusinessException on one thread in a multit-hreaded environment. * <p>//from w w w. j a va 2 s. co m * [Expected Result] * <ol> * <li>throws BusinessException on one thread.</li> * <li>BusinessException log is output & not duplicate on one thread.</li> * <li>unnecessary log is not output.</li> * </ol> * </p> */ @Test public void testInvoke_multi_thread_occur_businessexception_one_thread() throws Throwable { // do setup for test case. final TestFacade facade = getApplicationContext().getBean(TestFacade.class); final TestService service = getApplicationContext().getBean(TestService.class); final Map<Thread, BusinessException> actualBusinessException = new HashMap<Thread, BusinessException>(); // setup for thread1. Thread thread1 = new Thread(new Runnable() { @Override public void run() { facade.setSleepTime(Long.valueOf(2)); try { facade.getMessage(); } catch (BusinessException e) { actualBusinessException.put(Thread.currentThread(), e); } } }); // setup for thread2. final BusinessException occurExceptionForThread2 = new BusinessException( ResultMessages.error().add("e.cm.thread2")); Thread thread2 = new Thread(new Runnable() { @Override public void run() { service.setResultMessagesNotificationException(occurExceptionForThread2); facade.setSleepTime(Long.valueOf(0)); try { facade.getMessage(); } catch (BusinessException e) { actualBusinessException.put(Thread.currentThread(), e); } } }); // do test. thread1.start(); TimeUnit.SECONDS.sleep(1); thread2.start(); // wait thread finish. thread1.join(); thread2.join(); // do assert assertFalse(actualBusinessException.containsKey(thread1)); assertThat(actualBusinessException.get(thread2), is(occurExceptionForThread2)); verify(mockExceptionLogger, times(1)).warn(occurExceptionForThread2); verify(mockExceptionLogger, times(1)).warn((Exception) anyObject()); }
From source file:com.gochinatv.datasync.util.Shell.java
/** * Run a command//from www .j ava2 s.co m */ private void runCommand() throws IOException { ProcessBuilder builder = new ProcessBuilder(getExecString()); Timer timeOutTimer = null; ShellTimeoutTimerTask timeoutTimerTask; timedOut = new AtomicBoolean(false); completed = new AtomicBoolean(false); if (environment != null) { builder.environment().putAll(this.environment); } if (dir != null) { builder.directory(this.dir); } process = builder.start(); if (timeOutInterval > 0) { timeOutTimer = new Timer(); timeoutTimerTask = new ShellTimeoutTimerTask(this); //One time scheduling. timeOutTimer.schedule(timeoutTimerTask, timeOutInterval); } final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream())); final StringBuffer errMsg = new StringBuffer(); // read error and input streams as this would free up the buffers // free the error stream buffer Thread errThread = new Thread() { @Override public void run() { try { String line = errReader.readLine(); while ((line != null) && !isInterrupted()) { errMsg.append(line); errMsg.append(System.getProperty("line.separator")); line = errReader.readLine(); } } catch (IOException ioe) { LOG.warn("Error reading the error stream", ioe); } } }; try { errThread.start(); } catch (IllegalStateException ignored) { } try { parseExecResult(inReader); // parse the output // clear the input stream buffer String line = inReader.readLine(); while (line != null) { line = inReader.readLine(); } // wait for the process to finish and check the exit code exitCode = process.waitFor(); try { // make sure that the error thread exits errThread.join(); } catch (InterruptedException ie) { LOG.warn("Interrupted while reading the error stream", ie); } completed.set(true); //the timeout thread handling //taken care in finally block if (exitCode != 0) { throw new ExitCodeException(exitCode, errMsg.toString()); } } catch (InterruptedException ie) { throw new IOException(ie.toString()); } finally { if ((timeOutTimer != null) && !timedOut.get()) { timeOutTimer.cancel(); } // close the input stream try { inReader.close(); } catch (IOException ioe) { LOG.warn("Error while closing the input stream", ioe); } if (!completed.get()) { errThread.interrupt(); } try { errReader.close(); } catch (IOException ioe) { LOG.warn("Error while closing the error stream", ioe); } process.destroy(); lastTime = System.currentTimeMillis(); } }