Examples of CyclicBarrier


Examples of java.util.concurrent.CyclicBarrier

        // 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

Examples of java.util.concurrent.CyclicBarrier

   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

Examples of java.util.concurrent.CyclicBarrier

    */
   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

Examples of java.util.concurrent.CyclicBarrier

        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

Examples of java.util.concurrent.CyclicBarrier

        conf.setOption(TimedRuleExectionOption.YES);

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

        final CyclicBarrier barrier = new CyclicBarrier(2);
        final AtomicBoolean aBool = new AtomicBoolean(true);
        AgendaEventListener agendaEventListener = new DefaultAgendaEventListener() {
            public void afterMatchFired(org.kie.api.event.rule.AfterMatchFiredEvent event) {
                try {
                    if (aBool.get()) {
                        barrier.await();
                        aBool.set(false);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        };
        ksession.addEventListener(agendaEventListener);

        List list = new ArrayList();
        ksession.setGlobal("list", list);

        // Using the Pseudo Clock.
        SessionClock clock = ksession.getSessionClock();
        SessionPseudoClock pseudoClock = (SessionPseudoClock) clock;

        // Insert the event.
        String eventOne = "one";
        ksession.insert(eventOne);

        // Advance the time .... so the timer will fire.
        pseudoClock.advanceTime(10000, TimeUnit.MILLISECONDS);

        // Rule doesn't fire in PHREAK. This is because you need to call 'fireAllRules' after you've inserted the fact, otherwise the timer
        // job is not created.

        ksession.fireAllRules();

        // Rule still doesn't fire, because the DefaultTimerJob is created now, and now we need to advance the timer again.

        pseudoClock.advanceTime(30000, TimeUnit.MILLISECONDS);
        barrier.await();
        barrier.reset();
        aBool.set(true);

        pseudoClock.advanceTime(10000, TimeUnit.MILLISECONDS);
        barrier.await();
        barrier.reset();
        aBool.set(true);

        String eventTwo = "two";
        ksession.insert(eventTwo);
        ksession.fireAllRules();

        // 60
        pseudoClock.advanceTime(10000, TimeUnit.MILLISECONDS);
        barrier.await();
        barrier.reset();
        aBool.set(true);

        // 70
        pseudoClock.advanceTime(10000, TimeUnit.MILLISECONDS);
        barrier.await();
        barrier.reset();
        aBool.set(true);

        //From here, the second rule should fire.
        //phaser.register();
        pseudoClock.advanceTime(10000, TimeUnit.MILLISECONDS);
        barrier.await();
        barrier.reset();
        aBool.set(true);

        // Now 2 rules have fired, and those will now fire every 10 seconds.
        pseudoClock.advanceTime(20000, TimeUnit.MILLISECONDS);
        barrier.await();
        barrier.reset();

        pseudoClock.advanceTime(20000, TimeUnit.MILLISECONDS);
        aBool.set(true);
        barrier.await();
        barrier.reset();

        pseudoClock.advanceTime(20000, TimeUnit.MILLISECONDS);
        aBool.set(true);
        barrier.await();
        barrier.reset();

        ksession.destroy();
    }
View Full Code Here

Examples of java.util.concurrent.CyclicBarrier

   public void testConcurrentAddRemove() throws Exception {
      InterceptorChain ic = new InterceptorChain(new ComponentMetadataRepo());
      ic.setFirstInChain(new CallInterceptor());
      ic.addInterceptor(new ActivationInterceptor(), 1);
      CyclicBarrier barrier = new CyclicBarrier(4);
      List<Future<Void>> futures = new ArrayList<Future<Void>>(2);
      ExecutorService executorService = Executors.newFixedThreadPool(3);
      try {
         // We do test concurrent add/remove of different types per thread,
         // so that the final result is predictable (testable) and that we
         // can not possibly fail because of the InterceptorChain checking
         // that no interceptor is ever added twice.
         futures.add(executorService.submit(new InterceptorChainUpdater(ic, barrier, new CacheMgmtInterceptor())));
         futures.add(executorService.submit(new InterceptorChainUpdater(ic, barrier, new DistCacheStoreInterceptor())));
         futures.add(executorService.submit(new InterceptorChainUpdater(ic, barrier, new InvalidationInterceptor())));
         barrier.await(); // wait for all threads to be ready
         barrier.await(); // wait for all threads to finish
         log.debug("All threads finished, let's shutdown the executor and check whether any exceptions were reported");
         for (Future<Void> future : futures) future.get();
      } finally {
         executorService.shutdownNow();
      }
View Full Code Here

Examples of java.util.concurrent.CyclicBarrier

      try {
         final TransactionFactory gtf = new TransactionFactory();
         gtf.init(false, false, true, false);
         final String k1 = k(m, 1), k2 = k(m, 2), v1 = v(m, 1), v2 = v(m, 2);
         final ConcurrentMap<Object, Modification> localMods = new ConcurrentHashMap<Object, Modification>();
         final CyclicBarrier barrier = new CyclicBarrier(2);
         DummyInMemoryCacheStore underlying = new DummyInMemoryCacheStore();
         store = new AsyncStore(underlying, asyncConfig) {
            @Override
            protected void applyModificationsSync(List<Modification> mods) throws CacheLoaderException {
               for (Modification mod : mods)
                  localMods.put(getKey(mod), mod);

               super.applyModificationsSync(mods);
               try {
                  barrier.await(waitTimeout, waitUnit);
               } catch (TimeoutException e) {
                  assert false : "Timed out applying for modifications";
               } catch (Exception e) {
                  throw new CacheLoaderException("Barrier failed", e);
               }
            }

            private Object getKey(Modification modification) {
               switch (modification.getType()) {
                  case STORE:
                     return ((Store) modification).getStoredEntry().getKey();
                  case REMOVE:
                     return ((Remove) modification).getKey();
                  default:
                     return null;
               }
            }
         };
         dummyCfg = new DummyInMemoryCacheStore.Cfg();
         dummyCfg.setStoreName(m.getName());
         store.init(dummyCfg, null, null);
         store.start();

         List<Modification> mods = new ArrayList<Modification>();
         mods.add(new Store(TestInternalCacheEntryFactory.create(k1, v1)));
         mods.add(new Store(TestInternalCacheEntryFactory.create(k2, v2)));
         mods.add(new Remove(k1));
         GlobalTransaction tx = gtf.newGlobalTransaction(null, false);
         store.prepare(mods, tx, false);

         assert 0 == localMods.size();
         assert !store.containsKey(k1);
         assert !store.containsKey(k2);

         store.commit(tx);
         barrier.await(waitTimeout, waitUnit); // Wait for store
         barrier.await(waitTimeout, waitUnit); // Wait for remove
         assert store.load(k2).getValue().equals(v2);
         assert !store.containsKey(k1);
         assert 2 == localMods.size();
         assert new Remove(k1).equals(localMods.get(k1));
      } finally {
View Full Code Here

Examples of java.util.concurrent.CyclicBarrier

         gtf.init(false, false, true, false);
         final String k1 = k(m, 1), k2 = k(m, 2), k3 = k(m, 3), v1 = v(m, 1), v2 = v(m, 2), v3 = v(m, 3);
         final AtomicInteger storeCount = new AtomicInteger();
         final AtomicInteger removeCount = new AtomicInteger();
         final AtomicInteger clearCount = new AtomicInteger();
         final CyclicBarrier barrier = new CyclicBarrier(2);
         DummyInMemoryCacheStore underlying = new DummyInMemoryCacheStore() {
            @Override
            public void store(InternalCacheEntry ed) {
               super.store(ed);
               storeCount.getAndIncrement();
            }

            @Override
            public boolean remove(Object key) {
               boolean ret = super.remove(key);
               removeCount.getAndIncrement();
               return ret;
            }

            @Override
            public void clear() {
               super.clear();
               clearCount.getAndIncrement();
            }
         };
         store = new AsyncStore(underlying, asyncConfig) {
            @Override
            protected void applyModificationsSync(List<Modification> mods)
                  throws CacheLoaderException {
               super.applyModificationsSync(mods);
               try {
                  log.tracef("Wait to apply modifications: %s", mods);
                  barrier.await(waitTimeout, waitUnit);
               } catch (TimeoutException e) {
                  assert false : "Timed out applying for modifications";
               } catch (Exception e) {
                  throw new CacheLoaderException("Barrier failed", e);
               }
            }
         };
         dummyCfg = new DummyInMemoryCacheStore.Cfg();
         dummyCfg.setStoreName(m.getName());
         store.init(dummyCfg, null, null);
         store.start();

         List<Modification> mods = new ArrayList<Modification>();
         mods.add(new Store(TestInternalCacheEntryFactory.create(k1, v1)));
         mods.add(new Store(TestInternalCacheEntryFactory.create(k1, v2)));
         mods.add(new Store(TestInternalCacheEntryFactory.create(k2, v1)));
         mods.add(new Store(TestInternalCacheEntryFactory.create(k2, v2)));
         mods.add(new Remove(k1));
         GlobalTransaction tx = gtf.newGlobalTransaction(null, false);
         store.prepare(mods, tx, false);
         Thread.sleep(200); //verify that work is not performed until commit
         assert 0 == storeCount.get();
         assert 0 == removeCount.get();
         assert 0 == clearCount.get();
         store.commit(tx);
         log.tracef("Wait for modifications to be queued: %s", mods);
         barrier.await(waitTimeout, waitUnit); // Wait for single store to be applied
         barrier.await(waitTimeout, waitUnit); // Wait for single remove to be applied
         assert 1 == storeCount.get() : "Store count was " + storeCount.get();
         assert 1 == removeCount.get();
         assert 0 == clearCount.get();

         storeCount.set(0);
         removeCount.set(0);
         clearCount.set(0);
         mods = new ArrayList<Modification>();
         mods.add(new Store(TestInternalCacheEntryFactory.create(k1, v1)));
         mods.add(new Remove(k1));
         mods.add(new Clear());
         mods.add(new Store(TestInternalCacheEntryFactory.create(k2, v2)));
         mods.add(new Remove(k2));
         tx = gtf.newGlobalTransaction(null, false);
         store.prepare(mods, tx, false);
         Thread.sleep(200); //verify that work is not performed until commit
         assert 0 == storeCount.get();
         assert 0 == removeCount.get();
         assert 0 == clearCount.get();
         store.commit(tx);
         barrier.await(waitTimeout, waitUnit);
         assert 0 == storeCount.get() : "Store count was " + storeCount.get();
         assert 1 == removeCount.get();
         assert 1 == clearCount.get();

         storeCount.set(0);
         removeCount.set(0);
         clearCount.set(0);
         mods = new ArrayList<Modification>();
         mods.add(new Store(TestInternalCacheEntryFactory.create(k1, v1)));
         mods.add(new Remove(k1));
         mods.add(new Store(TestInternalCacheEntryFactory.create(k2, v2)));
         mods.add(new Remove(k2));
         mods.add(new Store(TestInternalCacheEntryFactory.create(k3, v3)));
         tx = gtf.newGlobalTransaction(null, false);
         store.prepare(mods, tx, false);
         Thread.sleep(200);
         assert 0 == storeCount.get();
         assert 0 == removeCount.get();
         assert 0 == clearCount.get();
         store.commit(tx);
         barrier.await(waitTimeout, waitUnit); // Wait for store to be applied
         barrier.await(waitTimeout, waitUnit); // Wait for first removal to be applied
         barrier.await(waitTimeout, waitUnit); // Wait for second removal to be applied
         assert 1 == storeCount.get() : "Store count was " + storeCount.get();
         assert 2 == removeCount.get();
         assert 0 == clearCount.get();

         storeCount.set(0);
         removeCount.set(0);
         clearCount.set(0);
         mods = new ArrayList<Modification>();
         mods.add(new Clear());
         mods.add(new Remove(k1));
         tx = gtf.newGlobalTransaction(null, false);
         store.prepare(mods, tx, false);
         Thread.sleep(200);
         assert 0 == storeCount.get();
         assert 0 == removeCount.get();
         assert 0 == clearCount.get();
         store.commit(tx);
         barrier.await(waitTimeout, waitUnit);
         assert 0 == storeCount.get() : "Store count was " + storeCount.get();
         assert 1 == removeCount.get();
         assert 1 == clearCount.get();

         storeCount.set(0);
         removeCount.set(0);
         clearCount.set(0);
         mods = new ArrayList<Modification>();
         mods.add(new Clear());
         mods.add(new Store(TestInternalCacheEntryFactory.create(k1, v1)));
         tx = gtf.newGlobalTransaction(null, false);
         store.prepare(mods, tx, false);
         Thread.sleep(200);
         assert 0 == storeCount.get();
         assert 0 == removeCount.get();
         assert 0 == clearCount.get();
         store.commit(tx);
         barrier.await(waitTimeout, waitUnit);
         assert 1 == storeCount.get() : "Store count was " + storeCount.get();
         assert 0 == removeCount.get();
         assert 1 == clearCount.get();
      } finally {
         store.delegate.clear();
View Full Code Here

Examples of java.util.concurrent.CyclicBarrier

   public void testNoTimeoutAndCorrectness() throws Throwable {
      runTest(true);
   }

   private void runTest(final boolean checkCorrectness) throws Throwable {
      final CyclicBarrier barrier = new CyclicBarrier(THREADS);
      final Random rnd = new Random();
      final AtomicBoolean correctness = new AtomicBoolean(Boolean.TRUE);
      List<Future<Boolean>> result = new ArrayList<Future<Boolean>>();
      for (int t = 0; t < THREADS; t++) {
         final int part = t;
         Future<Boolean> f = fork(new Callable<Boolean>() {

            @Override
            public Boolean call() throws Exception {
               try {
                  for (int i = 0; i < OP_COUNT; i++) {
                     barrier();
                     executeOperation(i);
                     barrier();
                     checkCorrectness(i);
                     printProgress(i);
                     if (!correctness.get()) break;

                  }
               } catch (Throwable t) {
                  correctness.set(false);
                  throw new Exception(t);
               }
               return correctness.get();
            }

            private void printProgress(int i) {
               if (i % 100 == 0) print("Progressing  = " + i);
            }

            private void executeOperation(int iteration) {
               int node = rnd.nextInt(NUM_NODES - 1);
               switch (rnd.nextInt(4)) {
                  case 0: {
                     cache(node).put("k", "v_" + part + "_" + iteration);
                     break;
                  }
                  case 1: {
                     cache(node).remove("k");
                     break;
                  }
                  case 2: {
                     cache(node).putIfAbsent("k", "v" + part);
                     break;
                  }
                  case 3: {
                     cache(node).replace("k", "v" + part);
                     break;
                  }
                  default:
                     throw new IllegalStateException();
               }
            }

            private void checkCorrectness(int i) {
               if (checkCorrectness) {
                  log.tracef("Checking correctness for iteration %s", i);
                  print("Checking correctness");

                  List<Address> owners = advancedCache(0).getDistributionManager().locate("k");
                  assert owners.size() == 2;

                  InternalCacheEntry entry0 = advancedCache(owners.get(0)).getDataContainer().get("k");
                  InternalCacheEntry entry1 = advancedCache(owners.get(1)).getDataContainer().get("k");
                  Object mainOwnerValue = entry0 == null ? null : entry0.getValue();
                  Object otherOwnerValue = entry1 == null ? null : entry1.getValue();
                  log.tracef("Main owner value is %, other Owner Value is %s", mainOwnerValue, otherOwnerValue);
                  boolean equals = mainOwnerValue == null? otherOwnerValue == null : mainOwnerValue.equals(otherOwnerValue);
                  if (!equals) {
                     print("Consistency error. On main owner(" + owners.get(0) + ") we had " +
                                 mainOwnerValue + " and on backup owner(" + owners.get(1) + ") we had " + otherOwnerValue);
                     log.trace("Consistency error. On main owner(" + owners.get(0) + ") we had " +
                                     mainOwnerValue + " and on backup owner(" + owners.get(1) + ") we had " + otherOwnerValue);
                     correctness.set(false);
                     return;
                  }

                  print("otherOwnerValue = " + otherOwnerValue);
                  print("mainOwnerValue = " + mainOwnerValue);
                  for (int q = 0; q < NUM_NODES; q++) {
                     print(q, cache(0).get("k"));
                  }

                  Object expectedValue = cache(0).get("k");
                  log.tracef("Original value read from cache 0 is %s", expectedValue);
                  for (int j = 0; j < NUM_NODES; j++) {
                     Object actualValue = cache(j).get("k");
                     boolean areEquals = expectedValue == null ? actualValue == null : expectedValue.equals(actualValue);
                     print("Are " + actualValue + " and " + expectedValue + " equals ? " + areEquals);
                     if (!areEquals) {
                        correctness.set(false);
                        print("Consistency error. On cache 0 we had " + expectedValue + " and on " + j + " we had " + actualValue);
                        log.trace("Consistency error. On cache 0 we had " + expectedValue + " and on " + j + " we had " + actualValue);
                     }

                  }
               }
            }

            private void barrier() throws BrokenBarrierException, java.util.concurrent.TimeoutException, InterruptedException {
               barrier.await(10000, TimeUnit.MILLISECONDS);
               log.tracef("Just passed barrier.");
            }

         });
         result.add(f);
View Full Code Here

Examples of java.util.concurrent.CyclicBarrier

      failed.set(false);
      quit.set(false);
      caches.get(0).put(SHARED_KEY, "initialValue");
      final SharedState state = new SharedState(THREAD_COUNT);
      final PostOperationStateCheck stateCheck = new PostOperationStateCheck(caches, state, operation);
      final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT, stateCheck);
      ExecutorService exec = Executors.newFixedThreadPool(THREAD_COUNT);
      for (int threadIndex = 0; threadIndex < THREAD_COUNT; threadIndex++) {
         Runnable validMover = new ValidMover(caches, barrier, threadIndex, state, operation);
         exec.execute(validMover);
      }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.