Java Code Examples for java.util.concurrent.CountDownLatch

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project activemq-apollo, under directory /apollo-itests/src/test/java/org/apache/activemq/apollo/.

Source file: ProducerFlowControlTest.java

  18 
vote

public void test2ndPubisherWithStandardConnectionThatIsBlocked() throws Exception {
  ConnectionFactory factory=createConnectionFactory();
  connection=(ActiveMQConnection)factory.createConnection();
  connections.add(connection);
  connection.start();
  fillQueue(queueA);
  CountDownLatch pubishDoneToQeueuB=asyncSendTo(queueB,"Message 1");
  assertFalse(pubishDoneToQeueuB.await(2,TimeUnit.SECONDS));
}
 

Example 2

From project Agot-Java, under directory /src/main/java/got/logic/.

Source file: StartHandler.java

  18 
vote

private void event(MessageType type) throws Exception {
  logger.debug("Server: Send the command " + type.toString());
  CountDownLatch cdl=new CountDownLatch(countdownN);
  serverGameInfo.getCdl().put(type,cdl);
  node.send(type);
  cdl.await();
  logger.debug("Server: Receive all commands of type " + type.toString());
  syncGameStatus();
}
 

Example 3

From project ardverk-commons, under directory /src/test/java/org/ardverk/io/.

Source file: ProgressInputStreamTest.java

  18 
vote

@Test public void close() throws IOException, InterruptedException {
  final CountDownLatch latch=new CountDownLatch(1);
  ProgressCallback callback=new ProgressAdapter(){
    @Override public void closed(    InputStream in){
      latch.countDown();
    }
  }
;
  ProgressInputStream in=new ProgressInputStream(new ByteArrayInputStream(new byte[0]),callback);
  in.close();
  if (!latch.await(1,TimeUnit.SECONDS)) {
    TestCase.fail("Close failed!");
  }
}
 

Example 4

From project atlas, under directory /src/test/java/com/ning/atlas/.

Source file: TestGuavaNotificationBus.java

  18 
vote

@Test public void testFoo() throws Exception {
  AsyncEventBus bus=new AsyncEventBus(Executors.newCachedThreadPool(new ThreadFactoryBuilder().setDaemon(true).setNameFormat("event-bus-%d").build()));
  final CountDownLatch latch=new CountDownLatch(1);
  bus.register(new Object(){
    @SuppressWarnings("unused") @Subscribe public void on(    String msg){
      System.out.println(msg);
      latch.countDown();
    }
  }
);
  bus.post("hello world");
  assertThat(latch.await(1,TimeUnit.SECONDS),equalTo(true));
}
 

Example 5

From project bonecp, under directory /bonecp/src/test/java/com/jolbox/bonecp/.

Source file: CommonTestUtils.java

  18 
vote

/** 
 * Helper function.
 * @param threads
 * @param connections
 * @param cpds
 * @param workDelay
 * @param doPreparedStatement 
 * @return time taken
 * @throws InterruptedException
 */
public static long startThreadTest(int threads,long connections,DataSource cpds,int workDelay,boolean doPreparedStatement) throws InterruptedException {
  CountDownLatch startSignal=new CountDownLatch(1);
  CountDownLatch doneSignal=new CountDownLatch(threads);
  ExecutorService pool=Executors.newFixedThreadPool(threads);
  for (int i=0; i < threads; i++) {
    pool.execute(new ThreadTester(startSignal,doneSignal,cpds,connections,workDelay,doPreparedStatement));
  }
  long start=System.currentTimeMillis();
  startSignal.countDown();
  doneSignal.await();
  long end=(System.currentTimeMillis() - start);
  pool.shutdown();
  return end;
}
 

Example 6

From project cometd, under directory /cometd-java/cometd-java-client/src/test/java/org/cometd/client/.

Source file: BayeuxClientTest.java

  18 
vote

@Test public void testWaitForImpliedState() throws Exception {
  final BayeuxClient client=newBayeuxClient();
  final CountDownLatch latch=new CountDownLatch(1);
  client.getChannel(Channel.META_HANDSHAKE).addListener(new ClientSessionChannel.MessageListener(){
    public void onMessage(    ClientSessionChannel channel,    Message message){
      if (message.isSuccessful() && client.isHandshook())       latch.countDown();
    }
  }
);
  client.handshake();
  Assert.assertTrue(latch.await(5,TimeUnit.SECONDS));
  Assert.assertTrue(client.waitFor(5000,State.HANDSHAKING));
  disconnectBayeuxClient(client);
}
 

Example 7

From project cow, under directory /libs/ActionBarSherlock/test/app/src/com/actionbarsherlock/tests/app/.

Source file: FeatureCustomView.java

  18 
vote

public void enableCustomView() throws InterruptedException {
  final CountDownLatch latch=new CountDownLatch(1);
  runOnUiThread(new Runnable(){
    @Override public void run(){
      getSupportActionBar().setDisplayShowCustomEnabled(true);
      latch.countDown();
    }
  }
);
  latch.await();
}
 

Example 8

From project accent, under directory /src/test/java/net/lshift/accent/.

Source file: ConnectionBehaviourTest.java

  17 
vote

@Test public void shouldKeepAttemptingToReconnect() throws Exception {
  ConnectionFactory unconnectableFactory=createMock(ConnectionFactory.class);
  expect(unconnectableFactory.newConnection()).andStubThrow(new ConnectException("Boom"));
  replay(unconnectableFactory);
  final CountDownLatch attemptLatch=new CountDownLatch(4);
  ConnectionFailureListener eventingListener=new ConnectionFailureListener(){
    @Override public void connectionFailure(    Exception e){
      if (e instanceof ConnectException) {
        attemptLatch.countDown();
      }
 else {
        System.out.println("WARNING: Received unexpected exception - " + e);
      }
    }
  }
;
  AccentConnection conn=new AccentConnection(unconnectableFactory,eventingListener);
  assertTrue(attemptLatch.await(5000,TimeUnit.MILLISECONDS));
}
 

Example 9

From project adbcj, under directory /mysql/mina/src/test/java/.

Source file: Test.java

  17 
vote

/** 
 * @param args
 */
public static void main(String[] args) throws Exception {
  ConnectionManager connectionManager=ConnectionManagerProvider.createConnectionManager("adbcj:mysql://localhost/adbcjtck","adbcjtck","adbcjtck");
  final boolean[] callbacks={false,false};
  final CountDownLatch latch=new CountDownLatch(2);
  DbFuture<Connection> connectFuture=connectionManager.connect().addListener(new DbListener<Connection>(){
    public void onCompletion(    DbFuture<Connection> future) throws Exception {
      callbacks[0]=true;
      latch.countDown();
    }
  }
);
  Connection connection=connectFuture.get(5,TimeUnit.SECONDS);
  assertTrue(!connection.isClosed());
  DbFuture<Void> closeFuture=connection.close(true).addListener(new DbListener<Void>(){
    public void onCompletion(    DbFuture<Void> future) throws Exception {
      callbacks[1]=true;
      latch.countDown();
    }
  }
);
  closeFuture.get(5,TimeUnit.SECONDS);
  assertTrue(connection.isClosed());
  latch.await(1,TimeUnit.SECONDS);
  assertTrue(callbacks[0],"Callback on connection future was not invoked");
  assertTrue(callbacks[1],"Callback on close future was not invoked");
  connectionManager.close(true);
}
 

Example 10

From project aether-core, under directory /aether-connector-asynchttpclient/src/main/java/org/eclipse/aether/connector/async/.

Source file: AsyncRepositoryConnector.java

  17 
vote

/** 
 * Use the async http client library to download artifacts and metadata.
 * @param artifactDownloads The artifact downloads to perform, may be {@code null} or empty.
 * @param metadataDownloads The metadata downloads to perform, may be {@code null} or empty.
 */
public void get(Collection<? extends ArtifactDownload> artifactDownloads,Collection<? extends MetadataDownload> metadataDownloads){
  if (closed.get()) {
    throw new IllegalStateException("connector closed");
  }
  artifactDownloads=safe(artifactDownloads);
  metadataDownloads=safe(metadataDownloads);
  CountDownLatch latch=new CountDownLatch(artifactDownloads.size() + metadataDownloads.size());
  Collection<GetTask<?>> tasks=new ArrayList<GetTask<?>>();
  for (  MetadataDownload download : metadataDownloads) {
    String resource=layout.getPath(download.getMetadata()).getPath();
    GetTask<?> task=new GetTask<MetadataTransfer>(resource,download.getFile(),download.getChecksumPolicy(),latch,download,METADATA,false);
    tasks.add(task);
    task.run();
  }
  for (  ArtifactDownload download : artifactDownloads) {
    String resource=layout.getPath(download.getArtifact()).getPath();
    GetTask<?> task=new GetTask<ArtifactTransfer>(resource,download.isExistenceCheck() ? null : download.getFile(),download.getChecksumPolicy(),latch,download,ARTIFACT,true);
    tasks.add(task);
    task.run();
  }
  await(latch);
  for (  GetTask<?> task : tasks) {
    task.flush();
  }
}
 

Example 11

From project agit, under directory /agit-integration-tests/src/main/java/com/madgag/agit/.

Source file: GitAsyncTaskTest.java

  17 
vote

private Repository executeAndWaitFor(final GitOperation operation) throws InterruptedException, IOException {
  final CountDownLatch latch=new CountDownLatch(1);
  Log.d(TAG,"About to start " + operation);
  new Thread(){
    public void run(){
      Looper.prepare();
      Log.d(TAG,"In run method for " + operation);
      GitAsyncTask task=injector.getInstance(GitAsyncTaskFactory.class).createTaskFor(operation,new OperationLifecycleSupport(){
        public void startedWith(        OpNotification ongoingNotification){
          Log.i(TAG,"Started " + operation + " with "+ ongoingNotification);
        }
        public void publish(        Progress progress){
        }
        public void error(        OpNotification notification){
          Log.i(TAG,"Errored " + operation + " with "+ notification);
        }
        public void success(        OpNotification completionNotification){
        }
        public void completed(        OpNotification completionNotification){
          Log.i(TAG,"Completed " + operation + " with "+ completionNotification);
          latch.countDown();
        }
      }
);
      task.execute();
      Log.d(TAG,"Called execute() on task for " + operation);
      Looper.loop();
    }
  }
.start();
  long startTime=currentTimeMillis();
  Log.i(TAG,"Waiting for " + operation + " to complete - currentThread="+ currentThread());
  boolean timeout=!latch.await(7 * 60,SECONDS);
  long duration=currentTimeMillis() - startTime;
  Log.i(TAG,"Finished waiting - timeout=" + timeout + " duration="+ duration);
  assertThat("Timeout for " + operation,timeout,is(false));
  return new FileRepository(operation.getGitDir());
}
 

Example 12

From project airlift, under directory /dbpool/src/test/java/io/airlift/dbpool/.

Source file: ManagedDataSourceTest.java

  17 
vote

@Test public void testAcquirePermitInterrupted() throws Exception {
  final ManagedDataSource dataSource=new MockManagedDataSource(1,new Duration(5000,MILLISECONDS));
  assertEquals(dataSource.getMaxConnectionWaitMillis(),5000);
  Connection connection=dataSource.getConnection();
  assertEquals(dataSource.getConnectionsActive(),1);
  final CountDownLatch startLatch=new CountDownLatch(1);
  final CountDownLatch endLatch=new CountDownLatch(1);
  final AtomicBoolean wasInterrupted=new AtomicBoolean();
  final AtomicReference<SQLException> exception=new AtomicReference<SQLException>();
  Thread createThread=new Thread(){
    @Override public void run(){
      startLatch.countDown();
      try {
        dataSource.getConnection();
      }
 catch (      SQLException e) {
        exception.set(e);
      }
 finally {
        wasInterrupted.set(isInterrupted());
        endLatch.countDown();
      }
    }
  }
;
  createThread.start();
  startLatch.await();
  createThread.interrupt();
  endLatch.await();
  assertTrue(wasInterrupted.get(),"createThread.isInterrupted()");
  SQLException sqlException=exception.get();
  assertNotNull(sqlException);
  assertInstanceOf(sqlException.getCause(),InterruptedException.class);
  connection.close();
  assertEquals(dataSource.getConnectionsActive(),0);
}
 

Example 13

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/aladdin/handler/.

Source file: CommandMessageHandler.java

  17 
vote

public void startSession() throws Exception {
  if (pools.length == 1) {
    final PoolableObject conn=(PoolableObject)pools[0].borrowObject();
    connPoolMap.put(conn,pools[0]);
    MessageHandlerRunner runnable=null;
    if (conn instanceof MessageHandlerRunnerProvider) {
      MessageHandlerRunnerProvider provider=(MessageHandlerRunnerProvider)conn;
      runnable=provider.getRunner();
    }
 else {
      runnable=newQueryRunnable(null,conn,query,parameter,packet);
    }
    runnable.init(this);
    runnable.run();
  }
 else {
    final CountDownLatch latch=new CountDownLatch(pools.length);
    for (    ObjectPool pool : pools) {
      final PoolableObject conn=(PoolableObject)pool.borrowObject();
      connPoolMap.put(conn,pool);
      QueryRunnable runnable=newQueryRunnable(latch,conn,query,parameter,packet);
      runnable.init(this);
      ProxyRuntimeContext.getInstance().getClientSideExecutor().execute(runnable);
    }
    if (timeout > 0) {
      latch.await(timeout,TimeUnit.MILLISECONDS);
    }
 else {
      latch.await();
    }
  }
  endSession();
  packet.wirteToConnection(source);
}
 

Example 14

From project android-cropimage, under directory /src/com/android/camera/.

Source file: CropImage.java

  17 
vote

private void startFaceDetection(){
  if (isFinishing()) {
    return;
  }
  mImageView.setImageBitmapResetBase(mBitmap,true);
  Util.startBackgroundJob(this,null,getResources().getString(R.string.runningFaceDetection),new Runnable(){
    public void run(){
      final CountDownLatch latch=new CountDownLatch(1);
      final Bitmap b=(mImage != null) ? mImage.fullSizeBitmap(IImage.UNCONSTRAINED,1024 * 1024) : mBitmap;
      mHandler.post(new Runnable(){
        public void run(){
          if (b != mBitmap && b != null) {
            mImageView.setImageBitmapResetBase(b,true);
            mBitmap.recycle();
            mBitmap=b;
          }
          if (mImageView.getScale() == 1F) {
            mImageView.center(true,true);
          }
          latch.countDown();
        }
      }
);
      try {
        latch.await();
      }
 catch (      InterruptedException e) {
        throw new RuntimeException(e);
      }
      mRunFaceDetection.run();
    }
  }
,mHandler);
}
 

Example 15

From project android_packages_apps_Gallery, under directory /src/com/android/camera/.

Source file: CropImage.java

  17 
vote

private void startFaceDetection(){
  if (isFinishing()) {
    return;
  }
  mImageView.setImageBitmapResetBase(mBitmap,true);
  Util.startBackgroundJob(this,null,getResources().getString(R.string.runningFaceDetection),new Runnable(){
    public void run(){
      final CountDownLatch latch=new CountDownLatch(1);
      final Bitmap b=(mImage != null) ? mImage.fullSizeBitmap(IImage.UNCONSTRAINED,1024 * 1024) : mBitmap;
      mHandler.post(new Runnable(){
        public void run(){
          if (b != mBitmap && b != null) {
            mImageView.setImageBitmapResetBase(b,true);
            mBitmap.recycle();
            mBitmap=b;
          }
          if (mImageView.getScale() == 1F) {
            mImageView.center(true,true);
          }
          latch.countDown();
        }
      }
);
      try {
        latch.await();
      }
 catch (      InterruptedException e) {
        throw new RuntimeException(e);
      }
      mRunFaceDetection.run();
    }
  }
,mHandler);
}
 

Example 16

From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/media/.

Source file: CropImage.java

  17 
vote

private void startFaceDetection(){
  if (isFinishing()) {
    return;
  }
  mImageView.setImageBitmapResetBase(mBitmap,true);
  Util.startBackgroundJob(this,null,getResources().getString(Res.string.running_face_detection),new Runnable(){
    public void run(){
      final CountDownLatch latch=new CountDownLatch(1);
      final Bitmap b=mBitmap;
      mHandler.post(new Runnable(){
        public void run(){
          if (b != mBitmap && b != null) {
            mImageView.setImageBitmapResetBase(b,true);
            mBitmap.recycle();
            mBitmap=b;
          }
          if (mImageView.getScale() == 1.0f) {
            mImageView.center(true,true);
          }
          latch.countDown();
        }
      }
);
      try {
        latch.await();
      }
 catch (      InterruptedException e) {
        throw new RuntimeException(e);
      }
      mRunFaceDetection.run();
    }
  }
,mHandler);
}
 

Example 17

From project archaius, under directory /archaius-core/src/test/java/com/netflix/config/.

Source file: ConcurrentMapConfigurationTest.java

  17 
vote

@Test public void testConcurrency(){
  final ConcurrentMapConfiguration conf=new ConcurrentMapConfiguration();
  ExecutorService exectuor=Executors.newFixedThreadPool(20);
  final CountDownLatch doneSignal=new CountDownLatch(1000);
  for (int i=0; i < 1000; i++) {
    final Integer index=i;
    exectuor.submit(new Runnable(){
      public void run(){
        conf.addProperty("key",index);
        conf.addProperty("key","stringValue");
        doneSignal.countDown();
        try {
          Thread.sleep(50);
        }
 catch (        InterruptedException e) {
        }
      }
    }
);
  }
  try {
    doneSignal.await();
  }
 catch (  InterruptedException e) {
  }
  List prop=(List)conf.getProperty("key");
  assertEquals(2000,prop.size());
}
 

Example 18

From project ardverk-dht, under directory /components/core/src/test/java/org/ardverk/dht/routing/.

Source file: RouteTableTest.java

  17 
vote

@Test public void addContact() throws InterruptedException {
  DefaultRouteTable routeTable=createRouteTable();
  final CountDownLatch latch=new CountDownLatch(1);
  routeTable.addRouteTableListener(new RouteTableAdapter(){
    @Override public void handleContactAdded(    Bucket bucket,    Contact contact){
      latch.countDown();
    }
  }
);
  Contact contact=createContact();
  routeTable.add(contact);
  if (!latch.await(1L,TimeUnit.SECONDS)) {
    TestCase.fail("Shouldn't have failed!");
  }
  TestCase.assertEquals(2,routeTable.size());
  TestCase.assertEquals(1,routeTable.getBuckets().length);
  TestCase.assertEquals(2,routeTable.getBuckets()[0].getActiveCount());
}
 

Example 19

From project arquillian-container-osgi, under directory /container-embedded/src/test/java/org/jboss/test/arquillian/container/osgi/.

Source file: ARQ465TestCase.java

  17 
vote

@Test public void testStartLevel() throws Exception {
  assertNotNull("StartLevel injected",startLevel);
  int initialStartLevel=startLevel.getInitialBundleStartLevel();
  assertEquals("Initial bundle start level",1,initialStartLevel);
  assertEquals("Bundle RESOLVED",Bundle.RESOLVED,bundle.getState());
  assertEquals("arq465-bundle",bundle.getSymbolicName());
  int bundleStartLevel=startLevel.getBundleStartLevel(bundle);
  assertEquals("Bundle start level",3,bundleStartLevel);
  try {
    bundle.start(Bundle.START_TRANSIENT);
    fail("Bundle cannot be started due to the Framework's current start level");
  }
 catch (  BundleException ex) {
  }
  assertEquals("Bundle RESOLVED",Bundle.RESOLVED,bundle.getState());
  bundle.start();
  assertEquals("Bundle RESOLVED",Bundle.RESOLVED,bundle.getState());
  final CountDownLatch latch=new CountDownLatch(1);
  context.addFrameworkListener(new FrameworkListener(){
    public void frameworkEvent(    FrameworkEvent event){
      if (event.getType() == FrameworkEvent.STARTLEVEL_CHANGED)       latch.countDown();
    }
  }
);
  startLevel.setStartLevel(3);
  latch.await(3,TimeUnit.SECONDS);
  assertEquals("Bundle ACTIVE",Bundle.ACTIVE,bundle.getState());
  bundle.stop();
  assertEquals("Bundle RESOLVED",Bundle.RESOLVED,bundle.getState());
  bundle.uninstall();
  assertEquals("Bundle UNINSTALLED",Bundle.UNINSTALLED,bundle.getState());
}
 

Example 20

From project arquillian-core, under directory /core/impl-base/src/test/java/org/jboss/arquillian/core/impl/context/.

Source file: ContextActivationTestCase.java

  17 
vote

@Test public void shouldNotBeAbleToReadFromDifferentThread() throws Exception {
  final CountDownLatch latch=new CountDownLatch(1);
  final ManagerTestContext context=new ManagerTestContextImpl();
  try {
    context.activate();
    context.getObjectStore().add(Object.class,new Object());
    Thread thread=new Thread(){
      public void run(){
        Assert.assertFalse(context.isActive());
        latch.countDown();
      }
    }
;
    thread.start();
    if (!latch.await(1,TimeUnit.SECONDS)) {
      Assert.fail("Thread never called?");
    }
  }
  finally {
    context.deactivate();
    context.destroy();
  }
}
 

Example 21

From project arquillian-extension-warp, under directory /impl/src/test/java/org/jboss/arquillian/warp/impl/client/execution/.

Source file: TestMultiThreadEvents.java

  17 
vote

@Test public void testEventsAreDeliverableFromAnotherThread() throws Exception {
  ManagerBuilder builder=ManagerBuilder.from().extension(Observer.class);
  Manager manager=builder.create();
  manager.start();
  latch=new CountDownLatch(1);
  new Thread(new FiringRunnable(manager)).start();
  latch.await();
  manager.shutdown();
}
 

Example 22

From project arquillian-graphene, under directory /graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/.

Source file: TestGrapheneContextTheadLocality.java

  17 
vote

@Test public void context_holds_one_instance_per_thread(){
  final CountDownLatch secondInstanceSet=new CountDownLatch(1);
  final CountDownLatch firstInstanceVerified=new CountDownLatch(1);
  final WebDriver driver1=mock(WebDriver.class);
  final WebDriver driver2=mock(WebDriver.class);
  new Thread(new Runnable(){
    public void run(){
      GrapheneContext.set(driver1);
      await(secondInstanceSet);
      assertSame(driver1,GrapheneContext.get());
      firstInstanceVerified.countDown();
    }
  }
).start();
  new Thread(new Runnable(){
    public void run(){
      GrapheneContext.set(driver2);
      secondInstanceSet.countDown();
      assertSame(driver2,GrapheneContext.get());
    }
  }
).start();
  await(firstInstanceVerified);
}
 

Example 23

From project arquillian_deprecated, under directory /impl-base/src/test/java/org/jboss/arquillian/impl/core/context/.

Source file: ContextActivationTestCase.java

  17 
vote

@Test public void shouldNotBeAbleToReadFromDifferentThread() throws Exception {
  final CountDownLatch latch=new CountDownLatch(1);
  final SuiteContext context=new SuiteContextImpl();
  try {
    context.activate();
    context.getObjectStore().add(Object.class,new Object());
    Thread thread=new Thread(){
      public void run(){
        Assert.assertFalse(context.isActive());
        latch.countDown();
      }
    }
;
    thread.start();
    if (!latch.await(1,TimeUnit.SECONDS)) {
      Assert.fail("Thread never called?");
    }
  }
  finally {
    context.deactivate();
    context.destroy();
  }
}
 

Example 24

From project avro, under directory /lang/java/ipc/src/test/java/org/apache/avro/ipc/.

Source file: TestNettyServerConcurrentExecution.java

  17 
vote

@Test(timeout=30000) public void test() throws Exception {
  final CountDownLatch waitLatch=new CountDownLatch(1);
  server=new NettyServer(new SpecificResponder(Simple.class,new SimpleImpl(waitLatch)),new InetSocketAddress(0),new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool()),new ExecutionHandler(Executors.newCachedThreadPool()));
  server.start();
  transceiver=new NettyTransceiver(new InetSocketAddress(server.getPort()),TestNettyServer.CONNECT_TIMEOUT_MILLIS);
  final Simple.Callback simpleClient=SpecificRequestor.getClient(Simple.Callback.class,transceiver);
  Assert.assertEquals(3,simpleClient.add(1,2));
  new Thread(){
    @Override public void run(){
      setName(TestNettyServerConcurrentExecution.class.getSimpleName() + "Ack Thread");
      try {
        waitLatch.await();
        simpleClient.ack();
      }
 catch (      InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
.start();
  String response=simpleClient.hello("wait");
  Assert.assertEquals("wait",response);
}
 

Example 25

From project azkaban, under directory /azkaban/src/java/azkaban/util/process/.

Source file: AzkabanProcess.java

  17 
vote

public AzkabanProcess(final List<String> cmd,final Map<String,String> env,final String workingDir,final Logger logger){
  this.cmd=cmd;
  this.env=env;
  this.workingDir=workingDir;
  this.processId=-1;
  this.startupLatch=new CountDownLatch(1);
  this.completeLatch=new CountDownLatch(1);
  this.logger=logger;
}
 

Example 26

From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/.

Source file: CropCropImage.java

  17 
vote

private void startFaceDetection(){
  if (isFinishing()) {
    return;
  }
  mImageView.setImageBitmapResetBase(mBitmap,true);
  CropUtil.startBackgroundJob(this,null,"Please wait\u2026",new Runnable(){
    public void run(){
      final CountDownLatch latch=new CountDownLatch(1);
      final Bitmap b=(mImage != null) ? mImage.fullSizeBitmap(CropIImage.UNCONSTRAINED,1024 * 1024) : mBitmap;
      mHandler.post(new Runnable(){
        public void run(){
          if (b != mBitmap && b != null) {
            Bitmap toRecycle=mBitmap;
            mBitmap=b;
            mImageView.setImageBitmapResetBase(mBitmap,true);
            toRecycle.recycle();
          }
          if (mImageView.getScale() == 1F) {
            mImageView.center(true,true);
          }
          latch.countDown();
        }
      }
);
      try {
        latch.await();
      }
 catch (      InterruptedException e) {
        throw new RuntimeException(e);
      }
      mRunFaceDetection.run();
    }
  }
,mHandler);
}
 

Example 27

From project CamelInAction-source, under directory /chapter10/client/src/test/java/camelinaction/.

Source file: RiderAutoPartsCallbackTest.java

  17 
vote

@Test public void testCallback() throws Exception {
  final List<String> relates=new ArrayList<String>();
  final CountDownLatch latch=new CountDownLatch(numPartners);
  Synchronization callback=new SynchronizationAdapter(){
    @Override public void onComplete(    Exchange exchange){
      relates.add(exchange.getOut().getBody(String.class));
      latch.countDown();
    }
    @Override public void onFailure(    Exchange exchange){
      latch.countDown();
    }
  }
;
  String body="bumper";
  for (int i=0; i < numPartners; i++) {
    template.asyncCallbackRequestBody("seda:partner:" + i,body,callback);
  }
  LOG.info("Send " + numPartners + " messages to partners.");
  boolean all=latch.await(1500,TimeUnit.MILLISECONDS);
  LOG.info("Got " + relates.size() + " replies, is all? "+ all);
  for (  String related : relates) {
    LOG.info("Related item category is: " + related);
  }
  assertEquals(3,relates.size());
  assertEquals("bumper extension",relates.get(0));
  assertEquals("bumper filter",relates.get(1));
  assertEquals("bumper cover",relates.get(2));
}
 

Example 28

From project camelpe, under directory /examples/loan-broker-common/src/test/java/net/camelpe/examples/loanbroker/queue/.

Source file: LoanBrokerQueueInContainerTest.java

  17 
vote

@Test public void assertThatLoanBrokerProcessesLoanRequest() throws Exception {
  final String ssn="Client-A";
  final String loanRequest="Request quote for lowest rate of lending bank";
  final CountDownLatch loanReplyReceived=new CountDownLatch(1);
  final AtomicReference<Message> receivedLoanReply=new AtomicReference<Message>();
  final MessageListener loanReplyListenerDelegate=new MessageListener(){
    @Override public void onMessage(    final Message arg0){
      receivedLoanReply.set(arg0);
      loanReplyReceived.countDown();
    }
  }
;
  final LoanReplyListener loanReplyListener=new LoanReplyListener(jmsServer,loanReplyListenerDelegate);
  loanReplyListener.start();
  final LoanRequestSender loanRequestSender=new LoanRequestSender(jmsServer);
  loanRequestSender.start();
  loanRequestSender.requestLoan(ssn,loanRequest);
  loanRequestSender.stop();
  loanReplyReceived.await();
  loanReplyListener.stop();
}
 

Example 29

From project Catroid-maven-playground, under directory /src/main/java/at/tugraz/ist/catroid/content/bricks/.

Source file: BroadcastWaitBrick.java

  17 
vote

public void execute(){
  Vector<BroadcastScript> receiver=projectManager.messageContainer.getReceiverOfMessage(broadcastMessage);
  if (receiver == null) {
    return;
  }
  if (receiver.size() == 0) {
    return;
  }
  CountDownLatch simultaneousStart=new CountDownLatch(1);
  CountDownLatch wait=new CountDownLatch(receiver.size());
  for (  BroadcastScript receiverScript : receiver) {
    receiverScript.executeBroadcastWait(simultaneousStart,wait);
  }
  simultaneousStart.countDown();
  try {
    wait.await();
  }
 catch (  InterruptedException e) {
  }
}
 

Example 30

From project Cilia_1, under directory /tests/runtime/src/test/java/cilia/runtime/dynamic/test/.

Source file: CiliaDynamicTest.java

  17 
vote

private void api_registerListener(ApplicationRuntime application){
  CountDownLatch done=new CountDownLatch(1);
  ChainCallbacks callback=new ChainCallbacks(done);
  try {
    application.addListener(null,(ChainCallback)callback);
    Assert.fail("Exception not thrown");
  }
 catch (  CiliaIllegalParameterException e) {
  }
catch (  Exception e) {
    Assert.fail("Invalid exception thrown " + e.getMessage());
  }
  try {
    application.addListener("(chain=",(ChainCallback)callback);
    Assert.fail("Exception not thrown");
  }
 catch (  CiliaInvalidSyntaxException e) {
    assertNotNull(e.getMessage());
  }
catch (  Exception e) {
    Assert.fail("Invalid exception thrown " + e.getMessage());
  }
  try {
    callback.result=false;
    application.addListener("(&(chain=*)(node=*))",(NodeCallback)callback);
    Builder builder=getCiliaContextService().getBuilder();
    builder.create("Chain2");
    builder.done();
synchronized (done) {
      done.await(5000,TimeUnit.MILLISECONDS);
    }
    Assert.assertTrue("Callback never received " + callback.result,callback.result);
  }
 catch (  Exception e) {
    Assert.fail("Invalid exception thrown " + e.getMessage());
  }
}
 

Example 31

From project cloudhopper-smpp, under directory /src/test/java/com/cloudhopper/smpp/demo/.

Source file: PerformanceClientMain.java

  17 
vote

@Override public void run(){
  CountDownLatch allSubmitResponseReceivedSignal=new CountDownLatch(1);
  DefaultSmppSessionHandler sessionHandler=new ClientSmppSessionHandler(allSubmitResponseReceivedSignal);
  String text160="\u20AC Lorem [ipsum] dolor sit amet, consectetur adipiscing elit. Proin feugiat, leo id commodo tincidunt, nibh diam ornare est, vitae accumsan risus lacus sed sem metus.";
  byte[] textBytes=CharsetUtil.encode(text160,CharsetUtil.CHARSET_GSM);
  try {
    session=clientBootstrap.bind(config,sessionHandler);
    allSessionsBoundSignal.countDown();
    startSendingSignal.await();
    while (SUBMIT_SENT.getAndIncrement() < SUBMIT_TO_SEND) {
      SubmitSm submit=new SubmitSm();
      submit.setSourceAddress(new Address((byte)0x03,(byte)0x00,"40404"));
      submit.setDestAddress(new Address((byte)0x01,(byte)0x01,"44555519205"));
      submit.setShortMessage(textBytes);
      this.submitRequestSent++;
      sendingDone.set(true);
      session.sendRequestPdu(submit,30000,false);
    }
    logger.info("before waiting sendWindow.size: {}",session.getSendWindow().getSize());
    allSubmitResponseReceivedSignal.await();
    logger.info("after waiting sendWindow.size: {}",session.getSendWindow().getSize());
    session.unbind(5000);
  }
 catch (  Exception e) {
    logger.error("",e);
    this.cause=e;
  }
}
 

Example 32

From project CouchbaseMock, under directory /src/main/java/org/couchbase/mock/http/.

Source file: BucketsStreamingHandler.java

  17 
vote

public BucketsStreamingHandler(HarakiriMonitor monitor,Bucket bucket,OutputStream output){
  this.output=output;
  this.bucket=bucket;
  this.monitor=monitor;
  this.completed=new CountDownLatch(1);
  updateHandlerLock=new ReentrantLock();
}
 

Example 33

From project crash, under directory /shell/core/src/test/java/org/crsh/.

Source file: BaseProcessContext.java

  17 
vote

private BaseProcessContext(ShellProcess process){
  this.process=process;
  this.latch=new CountDownLatch(1);
  this.response=null;
  this.width=32;
}
 

Example 34

From project cron, under directory /tck/src/test/java/org/jboss/seam/cron/test/asynchronous/beans/.

Source file: SomeAsynchMethods.java

  17 
vote

public void reset(){
  statusEvent=null;
  haystackCount=null;
  statusLatch=new CountDownLatch(1);
  heystackLatch=new CountDownLatch(1);
}
 

Example 35

From project cropimage, under directory /src/com/droid4you/util/cropimage/.

Source file: CropImage.java

  17 
vote

private void startFaceDetection(){
  if (isFinishing()) {
    return;
  }
  mImageView.setImageBitmapResetBase(mBitmap,true);
  Util.startBackgroundJob(this,null,"Please wait\u2026",new Runnable(){
    public void run(){
      final CountDownLatch latch=new CountDownLatch(1);
      final Bitmap b=(mImage != null) ? mImage.fullSizeBitmap(IImage.UNCONSTRAINED,1024 * 1024) : mBitmap;
      mHandler.post(new Runnable(){
        public void run(){
          if (b != mBitmap && b != null) {
            mImageView.setImageBitmapResetBase(b,true);
            mBitmap.recycle();
            mBitmap=b;
          }
          if (mImageView.getScale() == 1F) {
            mImageView.center(true,true);
          }
          latch.countDown();
        }
      }
);
      try {
        latch.await();
      }
 catch (      InterruptedException e) {
        throw new RuntimeException(e);
      }
      mRunFaceDetection.run();
    }
  }
,mHandler);
}
 

Example 36

From project curator, under directory /curator-client/src/main/java/com/netflix/curator/.

Source file: CuratorZookeeperClient.java

  17 
vote

void internalBlockUntilConnectedOrTimedOut() throws InterruptedException {
  long waitTimeMs=connectionTimeoutMs;
  while (!state.isConnected() && (waitTimeMs > 0)) {
    final CountDownLatch latch=new CountDownLatch(1);
    Watcher tempWatcher=new Watcher(){
      @Override public void process(      WatchedEvent event){
        latch.countDown();
      }
    }
;
    state.addParentWatcher(tempWatcher);
    long startTimeMs=System.currentTimeMillis();
    try {
      latch.await(1,TimeUnit.SECONDS);
    }
  finally {
      state.removeParentWatcher(tempWatcher);
    }
    long elapsed=Math.max(1,System.currentTimeMillis() - startTimeMs);
    waitTimeMs-=elapsed;
  }
}
 

Example 37

From project danbo, under directory /src/us/donmai/danbooru/danbo/cropimage/.

Source file: CropImage.java

  17 
vote

private void startFaceDetection(){
  if (isFinishing()) {
    return;
  }
  mImageView.setImageBitmapResetBase(mBitmap,true);
  Util.startBackgroundJob(this,null,"Please wait\u2026",new Runnable(){
    public void run(){
      final CountDownLatch latch=new CountDownLatch(1);
      final Bitmap b=(mImage != null) ? mImage.fullSizeBitmap(IImage.UNCONSTRAINED,1024 * 1024) : mBitmap;
      mHandler.post(new Runnable(){
        public void run(){
          if (b != mBitmap && b != null) {
            mImageView.setImageBitmapResetBase(b,true);
            mBitmap.recycle();
            mBitmap=b;
          }
          if (mImageView.getScale() == 1F) {
            mImageView.center(true,true);
          }
          latch.countDown();
        }
      }
);
      try {
        latch.await();
      }
 catch (      InterruptedException e) {
        throw new RuntimeException(e);
      }
      mRunFaceDetection.run();
    }
  }
,mHandler);
}
 

Example 38

From project alljoyn_java, under directory /samples/android/secure/logonclient/src/org/alljoyn/bus/samples/logonclient/.

Source file: Client.java

  16 
vote

public boolean requested(String authMechanism,String authPeer,int count,String userName,AuthRequest[] requests){
  PasswordRequest passwordRequest=null;
  UserNameRequest userNameRequest=null;
  for (  AuthRequest request : requests) {
    if (request instanceof PasswordRequest) {
      passwordRequest=(PasswordRequest)request;
    }
 else     if (request instanceof UserNameRequest) {
      userNameRequest=(UserNameRequest)request;
    }
  }
  try {
    if (count <= 3) {
      mLatch=new CountDownLatch(1);
      sendUiMessage(MESSAGE_SHOW_LOGON_DIALOG,null);
      mLatch.await();
      userNameRequest.setUserName(mUserName);
      passwordRequest.setPassword(mPassword.toCharArray());
      return true;
    }
  }
 catch (  InterruptedException ex) {
    Log.e(TAG,"Error waiting for logon",ex);
  }
  return false;
}
 

Example 39

From project Blitz, under directory /src/com/laxser/blitz/web/portal/impl/.

Source file: PipeImpl.java

  16 
vote

private synchronized void doStart(Writer writer) throws IOException {
  if (this.out != null) {
    throw new IllegalStateException("has been started.");
  }
  this.out=writer;
  if (logger.isDebugEnabled()) {
    logger.debug("start pipe " + getInvocation().getRequestPath().getUri());
  }
  writer.flush();
  latch=new CountDownLatch(windows.size());
  state=1;
  if (blocking != null) {
    for (    Window window : blocking) {
      doFire(window);
    }
    blocking=null;
  }
}