Package java.util.concurrent

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


   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

      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

         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

   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

      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

         if (tm.getStatus() == Status.STATUS_ACTIVE) tm.commit();
         else tm.rollback();
      }

      int nbWriters = 10;
      CyclicBarrier barrier = new CyclicBarrier(nbWriters + 1);
      List<Future<Void>> futures = new ArrayList<Future<Void>>(nbWriters);
      ExecutorService executorService = Executors.newCachedThreadPool(new ThreadFactory() {
         volatile int i = 0;
         @Override
         public Thread newThread(Runnable r) {
            int ii = i++;
            return new Thread(r, "EntryWriter-" + ii + ", WriteSkewTest");
         }
      });

      try {
         for (int i = 0; i < nbWriters; i++) {
            log.debug("Schedule execution");
            Future<Void> future = executorService.submit(new EntryWriter(barrier));
            futures.add(future);
         }
         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

   protected void teardown() {
      TestingUtil.killCacheManagers(cacheManager);
   }

   public void testConcurrentGetCacheCalls() throws Exception {
      final CyclicBarrier barrier = new CyclicBarrier(NUM_THREADS + 1);
      List<Future<Void>> futures = new ArrayList<Future<Void>>(NUM_THREADS);
      ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS);
      for (int i = 0; i < NUM_THREADS; i++) {
         log.debug("Schedule execution");
         final String name = "cache" + (i % NUM_CACHES);

         Future<Void> future = executorService.submit(new Callable<Void>(){
            @Override
            public Void call() throws Exception {
               try {
                  barrier.await();
                  cacheManager.getCache(name).put("a", "b");
                  return null;
               } catch (Throwable t) {
                  log.error("Got", t);
                  throw new RuntimeException(t);
               finally {
                  log.debug("Wait for all execution paths to finish");
                  barrier.await();
               }
            }
         });
         futures.add(future);
      }
      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();
      executorService.shutdownNow();
   }
View Full Code Here

        connectionWaitSecs);
    conf.setLong(YarnConfiguration
        .RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_MS,
        connectionRetryIntervalMs);
    conf.setLong(YarnConfiguration.NM_SLEEP_DELAY_BEFORE_SIGKILL_MS, 5000);
    CyclicBarrier syncBarrier = new CyclicBarrier(2);
    nm = new MyNodeManager2(syncBarrier, conf);
    nm.init(conf);
    nm.start();
    // start a container
    ContainerId cId = TestNodeManagerShutdown.createContainerId();
    FileContext localFS = FileContext.getLocalFSFileContext();
    TestNodeManagerShutdown.startContainer(nm, cId, localFS, nmLocalDir,
      new File("start_file.txt"));

    try {
      syncBarrier.await(10000, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
    }
    Assert.assertFalse("Containers not cleaned up when NM stopped",
      assertionFailedInThread.get());
    Assert.assertTrue(((MyNodeManager2) nm).isStopped);
View Full Code Here

    Configuration conf = new Configuration();
    conf.set(MRJobConfig.MR_AM_STAGING_DIR, stagingDir);
    AsyncDispatcher dispatcher = new AsyncDispatcher();
    dispatcher.init(conf);
    dispatcher.start();
    CyclicBarrier syncBarrier = new CyclicBarrier(2);
    OutputCommitter committer = new TestingOutputCommitter(syncBarrier, false);
    CommitterEventHandler commitHandler =
        createCommitterEventHandler(dispatcher, committer);
    commitHandler.init(conf);
    commitHandler.start();

    JobImpl job = createRunningStubbedJob(conf, dispatcher, 2, null);
    completeJobTasks(job);
    assertJobState(job, JobStateInternal.COMMITTING);

    // let the committer fail and verify the job fails
    syncBarrier.await();
    assertJobState(job, JobStateInternal.FAILED);
    dispatcher.stop();
    commitHandler.stop();
  }
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.