Package java.util.concurrent

Examples of java.util.concurrent.CyclicBarrier


                  cache1.getRpcManager().getMembers().size() == 2;
         }
      });

      // Every PutKeyValueCommand will be blocked before committing the entry on cache1
      CyclicBarrier beforeCommitCache1Barrier = new CyclicBarrier(2);
      BlockingInterceptor blockingInterceptor1 = new BlockingInterceptor(beforeCommitCache1Barrier,
            op.getCommandClass(), true);
      cache1.addInterceptorAfter(blockingInterceptor1, EntryWrappingInterceptor.class);

      // Wait for cache0 to collect the state to send to cache1 (including our previous value).
      blockingRpcManager0.waitForCommandToBlock();

      // Put/Replace/Remove from cache0 with cache0 as primary owner, cache1 will become a backup owner for the retry
      // The put command will be blocked on cache1 just before committing the entry.
      Future<Object> future = fork(new Callable<Object>() {
         @Override
         public Object call() throws Exception {
            return op.perform(cache0, key);
         }
      });

      // Wait for the entry to be wrapped on cache1
      beforeCommitCache1Barrier.await(10, TimeUnit.SECONDS);

      // Allow the state to be applied on cache1 (writing the old value for our entry)
      blockingRpcManager0.stopBlocking();

      // Wait for cache1 to finish applying the state, but don't allow the rebalance confirmation to be processed.
      // (It would change the topology and it would trigger a retry for the command.)
      checkPoint.awaitStrict("pre_rebalance_confirmation_" + rebalanceTopologyId + "_from_" + address(1), 10, SECONDS);

      // Now allow the command to commit on cache1
      beforeCommitCache1Barrier.await(10, TimeUnit.SECONDS);

      // Wait for the command to finish and check that it didn't fail
      Object result = future.get(10, TimeUnit.SECONDS);
      assertEquals(op.getReturnValue(), result);
      log.tracef("%s operation is done", op);
View Full Code Here


                  cache2.getRpcManager().getMembers().size() == 3;
         }
      });

      // Every ClusteredGetKeyValueCommand will be blocked before returning on cache0
      CyclicBarrier beforeCache0Barrier = new CyclicBarrier(2);
      BlockingInterceptor blockingInterceptor0 = new BlockingInterceptor(beforeCache0Barrier,
            GetKeyValueCommand.class, false);
      cache0.addInterceptorBefore(blockingInterceptor0, StateTransferInterceptor.class);

      // Every PutKeyValueCommand will be blocked before returning on cache1
      CyclicBarrier afterCache1Barrier = new CyclicBarrier(2);
      BlockingInterceptor blockingInterceptor1 = new BlockingInterceptor(afterCache1Barrier,
            op.getCommandClass(), false);
      cache1.addInterceptorBefore(blockingInterceptor1, StateTransferInterceptor.class);

      // Every PutKeyValueCommand will be blocked before reaching the distribution interceptor on cache2
      CyclicBarrier beforeCache2Barrier = new CyclicBarrier(2);
      BlockingInterceptor blockingInterceptor2 = new BlockingInterceptor(beforeCache2Barrier,
      op.getCommandClass(), true);
      cache2.addInterceptorBefore(blockingInterceptor2, NonTxConcurrentDistributionInterceptor.class);


      final MagicKey key = getKeyForCache2();

      // Prepare for replace: put a previous value in cache0 and cache1
      if (op.getPreviousValue() != null) {
         cache0.withFlags(Flag.CACHE_MODE_LOCAL).put(key, op.getPreviousValue());
         cache1.withFlags(Flag.CACHE_MODE_LOCAL).put(key, op.getPreviousValue());
      }

      // Put from cache0 with cache0 as primary owner, cache2 will become a backup owner for the retry
      // The put command will be blocked on cache1 and cache2.
      Future<Object> future = fork(new Callable<Object>() {
         @Override
         public Object call() throws Exception {
            switch (op) {
               case PUT:
                  return cache0.put(key, op.getValue());
               case PUT_IF_ABSENT:
                  return cache0.putIfAbsent(key, op.getValue());
               case REPLACE:
                  return cache0.replace(key, op.getValue());
               case REPLACE_EXACT:
                  return cache0.replace(key, op.getPreviousValue(), op.getValue());
               case REMOVE:
                  return cache0.remove(key);
               case REMOVE_EXACT:
                  return cache0.remove(key, op.getPreviousValue());
               default:
                  throw new IllegalArgumentException("Unsupported operation: " + op);
            }
         }
      });

      // Wait for the value to be written on cache1
      afterCache1Barrier.await(10, TimeUnit.SECONDS);
      afterCache1Barrier.await(10, TimeUnit.SECONDS);

      // Allow the command to proceed on cache2
      beforeCache2Barrier.await(10, TimeUnit.SECONDS);
      beforeCache2Barrier.await(10, TimeUnit.SECONDS);

      // Check that the put command didn't fail
      Object result = future.get(10, TimeUnit.SECONDS);
      assertEquals(op.getReturnValue(), result);
      log.tracef("%s operation is done", op);
View Full Code Here

      final AdvancedCache<Object, Object> cache0 = advancedCache(0);
      AdvancedCache<Object, Object> cache1 = advancedCache(1);
      AdvancedCache<Object, Object> cache2 = advancedCache(2);

      // Every PutKeyValueCommand will be blocked before reaching the distribution interceptor
      CyclicBarrier distInterceptorBarrier = new CyclicBarrier(2);
      BlockingInterceptor blockingInterceptor = new BlockingInterceptor(distInterceptorBarrier, PutKeyValueCommand.class, false);
      cache0.addInterceptorBefore(blockingInterceptor, NonTxConcurrentDistributionInterceptor.class);

      for (int i = 0; i < NUM_KEYS; i++) {
         // Try to put a key/value from cache0 with cache1 the primary owner
         final MagicKey key = new MagicKey("key" + i, cache1);
         Future<Object> future = fork(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
               return conditional ? cache0.putIfAbsent(key, "v") : cache0.put(key, "v");
            }
         });

         // After the put command passed through EntryWrappingInterceptor, kill cache1
         distInterceptorBarrier.await(10, TimeUnit.SECONDS);
         cache1.stop();

         // Wait for the new topology to be installed and unblock the command
         TestingUtil.waitForRehashToComplete(cache0, cache2);
         distInterceptorBarrier.await(10, TimeUnit.SECONDS);

         // StateTransferInterceptor retries the command, and it should block again in BlockingInterceptor.
         distInterceptorBarrier.await(10, TimeUnit.SECONDS);
         distInterceptorBarrier.await(10, TimeUnit.SECONDS);

         if (cache2.getAdvancedCache().getDistributionManager().getPrimaryLocation(key).equals(address(2))) {
            // cache2 forwards the command back to cache0, blocking again
            distInterceptorBarrier.await(10, TimeUnit.SECONDS);
            distInterceptorBarrier.await(10, TimeUnit.SECONDS);
         }
         // Check that the put command didn't fail
         Object result = future.get(10, TimeUnit.SECONDS);
         assertNull(result);
         log.tracef("Put operation is done");
View Full Code Here

      final MagicKey key = getKeyForCache2(duringJoinTopology.getPendingCH());
      log.tracef("Rebalance started. Found key %s with current owners %s and pending owners %s", key,
            duringJoinTopology.getCurrentCH().locateOwners(key), duringJoinTopology.getPendingCH().locateOwners(key));

      // Every PutKeyValueCommand will be blocked before reaching the distribution interceptor on cache1
      CyclicBarrier beforeCache1Barrier = new CyclicBarrier(2);
      BlockingInterceptor blockingInterceptor1 = new BlockingInterceptor(beforeCache1Barrier,
            PutKeyValueCommand.class, false);
      cache1.addInterceptorBefore(blockingInterceptor1, NonTxConcurrentDistributionInterceptor.class);

      // Every PutKeyValueCommand will be blocked after returning to the distribution interceptor on cache2
      CyclicBarrier afterCache2Barrier = new CyclicBarrier(2);
      BlockingInterceptor blockingInterceptor2 = new BlockingInterceptor(afterCache2Barrier,
            PutKeyValueCommand.class, true);
      cache2.addInterceptorBefore(blockingInterceptor2, StateTransferInterceptor.class);

      // Put from cache0 with cache0 as primary owner, cache2 will become the primary owner for the retry
      Future<Object> future = fork(new Callable<Object>() {
         @Override
         public Object call() throws Exception {
            return conditional ? cache0.putIfAbsent(key, "v") : cache0.put(key, "v");
         }
      });

      // Wait for the command to be executed on cache2 and unblock it
      afterCache2Barrier.await(10, TimeUnit.SECONDS);
      afterCache2Barrier.await(10, TimeUnit.SECONDS);

      // Allow the topology update to proceed on all the caches
      int postJoinTopologyId = duringJoinTopologyId + 1;
      checkPoint.trigger("allow_topology_" + postJoinTopologyId + "_on_" + address(0));
      checkPoint.trigger("allow_topology_" + postJoinTopologyId + "_on_" + address(1));
      checkPoint.trigger("allow_topology_" + postJoinTopologyId + "_on_" + address(2));

      // Wait for the topology to change everywhere
      TestingUtil.waitForRehashToComplete(cache0, cache1, cache2);

      // Allow the put command to throw an OutdatedTopologyException on cache1
      log.tracef("Unblocking the put command on node " + address(1));
      beforeCache1Barrier.await(10, TimeUnit.SECONDS);
      beforeCache1Barrier.await(10, TimeUnit.SECONDS);

      // Allow the retry to proceed on cache1, if it's still a member.
      // (In my tests, the backup was always cache0.)
      CacheTopology postJoinTopology = ltm0.getCacheTopology(CACHE_NAME);
      if (postJoinTopology.getCurrentCH().locateOwners(key).contains(address(1))) {
         beforeCache1Barrier.await(10, TimeUnit.SECONDS);
         beforeCache1Barrier.await(10, TimeUnit.SECONDS);
      }
      // And allow the retry to finish successfully on cache2
      afterCache2Barrier.await(10, TimeUnit.SECONDS);
      afterCache2Barrier.await(10, TimeUnit.SECONDS);

      // Check that the put command didn't fail
      Object result = future.get(10, TimeUnit.SECONDS);
      assertNull(result);
      log.tracef("Put operation is done");
View Full Code Here

    //pApplet_.registerMethod("dispose", this);
   
    // by default, automatically serialize mouse and keyboard events
   
   
    barrier_ = new CyclicBarrier(config_.numFollowers_ + 1);
   
    //set the initial window location of the processing sketch
    pApplet_.frame.setLocation(config_.getWindowLocation()[0],config_.getWindowLocation()[1]);
   
    pApplet_.frame.setTitle(pApplet_.getClass().getName()+ " window, rank: " + config_.getRank());
View Full Code Here

   
    @Test(timeout=10000)
    public void testLock3() throws InterruptedException {
        final int THREADS = 10;
        final UpgradableReentrantReadWriteLock lock = new UpgradableReentrantReadWriteLock(true);
        final CyclicBarrier sync = new CyclicBarrier( THREADS );
        final AtomicBoolean success = new AtomicBoolean( true );
       
        Runnable r1 = new Runnable() {
            public void run() {
                try {
                    lock.readLock();
                    sync.await();
                    lock.writeLock();
                    lock.writeUnlock();
                    lock.readUnlock();
                } catch ( Exception e ) {
                    e.printStackTrace();
                    success.set( false );
                }
            }
        };
        Runnable r2 = new Runnable() {
            public void run() {
                try {
                    sync.await();
                    lock.writeLock();
                    lock.writeUnlock();
                } catch ( Exception e ) {
                    e.printStackTrace();
                    success.set( false );
View Full Code Here

        // Set the body of the email to be sent
        final String body = "This is a test of the async SMTP Service";

        // Define a barrier for us to wait upon while email is sent through the JMS Queue
        final CyclicBarrier barrier = new CyclicBarrier(2);

        // Set a handler which will ensure the body was received properly
        smtpServerService.setHandler(new SMTPServerService.TestReceiveHandler() {
            @Override
            public void handle(final String contents) throws AssertionError {
                try {

                    // Perform assertion
                    Assert.assertTrue("message received does not contain body sent in email", contents.contains(body));

                    // Should probably be the second and last to arrive, but this
                    // Thread can block indefinitely w/ no timeout needed.  If
                    // the test waiting on the barrier times out, it'll trigger a test
                    // failure and undeployment of the SMTP Service
                    barrier.await();
                } catch (final InterruptedException e) {
                    // Swallow, this would occur if undeployment were triggered
                    // because the test failed (and we'd get a proper
                    // AssertionFailureError on the client side)
                } catch (final BrokenBarrierException e) {
                    throw new RuntimeException("Broken test setup", e);
                }
            }
        });

        // Construct and send the message async
        final MailMessageBuilder.MailMessage message =
                new MailMessageBuilder().from("alr@continuousdev.org").addTo("alr@continuousdev.org")
                        .subject("Test").body(body).contentType("text/plain").build();
        mailService.queueMailForDelivery(message);

        // Wait on the barrier until the message is received by the SMTP
        // server (pass) or the test times out (failure)
        try {
            barrier.await(5, TimeUnit.SECONDS);
        } catch (final InterruptedException e) {
            throw new RuntimeException("Broken test setup", e);
        } catch (final BrokenBarrierException e) {
            throw new RuntimeException("Broken test setup", e);
        } catch (final TimeoutException e) {
View Full Code Here

   public void testConcurrentAccessToCache() throws Exception {


      final AtomicReference<Exception> throwableHolder = new AtomicReference<>();
      final CyclicBarrier counter = new CyclicBarrier(NUMBER_OF_THREADS);

      ExecutorService executorService = Executors.newFixedThreadPool(NUMBER_OF_THREADS);
      for(int i = 0; i < NUMBER_OF_THREADS; ++i) {
         executorService.execute(new Runnable() {
            @Override
            public void run() {
               try {
                  counter.await();
                  service.cacheResult("Thread " + Thread.currentThread().getId());
               } catch (Exception t) {
                  throwableHolder.set(t);
               }
            }
View Full Code Here

    */
   public void testReadUncommitted() throws Throwable
   {
      final LockStrategy s = new LockStrategyReadUncommitted();
      final Semaphore sem = new MyFIFOSemaphore(1);
      final CyclicBarrier barrier = new CyclicBarrier(2);

      Thread t1 = new Thread("t1")
      {
         Lock lock = null;

         public void run()
         {
            try
            {
               sem.acquire(); // we're first to the semaphore

               // log("waiting on barrier");
               barrier.await(); // wait until t2 joins us
               // log("passed barrier");
               lock = s.readLock();
               lock.tryLock(TIMEOUT, TimeUnit.MILLISECONDS);
               log("1st read: value is " + value);
               assertEquals(10, value);
               sem.release(); // give t2 time to make the modification
               TestingUtil.sleepThread(100);

               sem.acquire(); // to read the uncommitted modification by t2
               log("2nd read: value is " + value + "; we should see t2's uncommitted change (20)");
               assertEquals(20, value); // we're seeing the modification by t2 before t2 committed (a.k.a. released the lock)
               sem.release();
               TestingUtil.sleepThread(100);

               sem.acquire(); // to read the committed change by t2
               log("3rd read: value is still " + value + "; we should see t2's committed change");
               assertEquals(20, value);
            }
            catch (Throwable ex)
            {
               t1_ex = ex;
            }
            finally
            {
               if (lock != null)
                  lock.unlock();
               sem.release();
            }
         }
      };


      Thread t2 = new Thread("t2")
      {
         Lock lock = null;

         public void run()
         {
            try
            {
               TestingUtil.sleepThread(100);
               barrier.await();
               sem.acquire();
               lock = s.writeLock();
               lock.tryLock(TIMEOUT, TimeUnit.MILLISECONDS);
               log("changing value from " + value + " to 20");
               value = 20;
View Full Code Here

        conf.setOption( TimedRuleExectionOption.YES );

        KnowledgeBase kbase = loadKnowledgeBaseFromString(str );
        KieSession ksession = createKnowledgeSession(kbase, conf);

        final CyclicBarrier barrier = new CyclicBarrier(2);

        AgendaEventListener agendaEventListener = new DefaultAgendaEventListener() {
            public void afterMatchFired(org.kie.api.event.rule.AfterMatchFiredEvent event) {
                try {
                    barrier.await();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        };
        ksession.addEventListener(agendaEventListener);

        List list = new ArrayList();

        PseudoClockScheduler timeService = ( PseudoClockScheduler ) ksession.<SessionClock>getSessionClock();
        timeService.advanceTime( new Date().getTime(), TimeUnit.MILLISECONDS );

        ksession.setGlobal( "list", list );

        ksession.fireAllRules();
        assertEquals(0, list.size());

        timeService.advanceTime(35, TimeUnit.SECONDS);
        barrier.await();
        barrier.reset();
        assertEquals(1, list.size());

        timeService.advanceTime(10, TimeUnit.SECONDS);
        barrier.await();
        barrier.reset();
        assertEquals(2, list.size());

        timeService.advanceTime(10, TimeUnit.SECONDS);
        barrier.await();
        barrier.reset();
        assertEquals( 3, list.size() );
    }
View Full Code Here

TOP

Related Classes of java.util.concurrent.CyclicBarrier

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.