Package java.util.concurrent.atomic

Examples of java.util.concurrent.atomic.AtomicBoolean


    int rsIdx = 0;
    HRegionServer regionServer = TEST_UTIL.getHBaseCluster().getRegionServer(rsIdx);
    HRegionInfo hri = getNonMetaRegion(regionServer.getOnlineRegions());
    LOG.debug("Asking RS to close region " + hri.getRegionNameAsString());

    AtomicBoolean closeEventProcessed = new AtomicBoolean(false);
    EventHandlerListener listener =
      new CloseRegionEventListener(hri.getRegionNameAsString(),
          closeEventProcessed);
    cluster.getMaster().executorService.registerListener(EventType.RS_ZK_REGION_CLOSED, listener);

    cluster.getMaster().assignmentManager.unassign(hri);

    while (!closeEventProcessed.get()) {
      Threads.sleep(100);
    }
    LOG.info("Done with testCloseRegion");
  }
View Full Code Here


        };
    }

    private void pathInBackground(final String path, final byte[] data, final String givenPath)
    {
        final AtomicBoolean firstTime = new AtomicBoolean(true);
        OperationAndData<PathAndBytes> operationAndData = new OperationAndData<PathAndBytes>(this, new PathAndBytes(path, data), backgrounding.getCallback(),
            new OperationAndData.ErrorCallback<PathAndBytes>()
            {
                public void retriesExhausted(OperationAndData<PathAndBytes> operationAndData)
                {
                    if ( doProtected )
                    {
                        // all retries have failed, findProtectedNodeInForeground(..) included, schedule a clean up
                        findAndDeleteProtectedNodeInBackground(path, protectedId, null);
                        // assign a new id if this builder is used again later
                        protectedId = UUID.randomUUID().toString();
                    }
                }
            },
            backgrounding.getContext())
        {
            @Override
            void callPerformBackgroundOperation() throws Exception
            {
                boolean callSuper = true;
                boolean localFirstTime = firstTime.getAndSet(false);
                if ( !localFirstTime && doProtected )
                {
                    String createdPath = null;
                    try
                    {
View Full Code Here

    private String pathInForeground(final String path, final byte[] data) throws Exception
    {
        TimeTrace trace = client.getZookeeperClient().startTracer("CreateBuilderImpl-Foreground");

        final AtomicBoolean firstTime = new AtomicBoolean(true);
        String returnPath = RetryLoop.callWithRetry
            (
                client.getZookeeperClient(),
                new Callable<String>()
                {
                    @Override
                    public String call() throws Exception
                    {
                        boolean localFirstTime = firstTime.getAndSet(false);

                        String createdPath = null;
                        if ( !localFirstTime && doProtected )
                        {
                            createdPath = findProtectedNodeInForeground(path);
View Full Code Here

    AssignmentManagerWithExtrasForTesting am = setUpMockedAssignmentManager(this.server,
        this.serverManager);
    try {
      // Boolean variable used for waiting until randomAssignment is called and new
      // plan is generated.
      AtomicBoolean gate = new AtomicBoolean(false);
      if (balancer instanceof MockedLoadBalancer) {
        ((MockedLoadBalancer) balancer).setGateVariable(gate);
      }
      ZKAssign.createNodeOffline(this.watcher, REGIONINFO, SERVERNAME_A);
      int v = ZKAssign.getVersion(this.watcher, REGIONINFO);
      ZKAssign.transitionNode(this.watcher, REGIONINFO, SERVERNAME_A, EventType.M_ZK_REGION_OFFLINE,
          EventType.RS_ZK_REGION_FAILED_OPEN, v);
      String path = ZKAssign.getNodeName(this.watcher, REGIONINFO.getEncodedName());
      RegionState state = new RegionState(REGIONINFO, State.OPENING, System.currentTimeMillis(),
          SERVERNAME_A);
      am.regionsInTransition.put(REGIONINFO.getEncodedName(), state);
      // a dummy plan inserted into the regionPlans. This plan is cleared and new one is formed
      am.regionPlans.put(REGIONINFO.getEncodedName(), new RegionPlan(REGIONINFO, null, SERVERNAME_A));
      RegionPlan regionPlan = am.regionPlans.get(REGIONINFO.getEncodedName());
      List<ServerName> serverList = new ArrayList<ServerName>(2);
      serverList.add(SERVERNAME_B);
      Mockito.when(this.serverManager.getOnlineServersList()).thenReturn(serverList);
      am.nodeDataChanged(path);
      // here we are waiting until the random assignment in the load balancer is called.
      while (!gate.get()) {
        Thread.sleep(10);
      }
      // new region plan may take some time to get updated after random assignment is called and
      // gate is set to true.
      RegionPlan newRegionPlan = am.regionPlans.get(REGIONINFO.getEncodedName());
View Full Code Here

    Mockito.when(this.serverManager.getDrainingServersList()).thenReturn(destServers);
    // To avoid cast exception in DisableTableHandler process.
    //Server server = new HMaster(HTU.getConfiguration());
    AssignmentManagerWithExtrasForTesting am = setUpMockedAssignmentManager(server,
        this.serverManager);
    AtomicBoolean gate = new AtomicBoolean(false);
    if (balancer instanceof MockedLoadBalancer) {
      ((MockedLoadBalancer) balancer).setGateVariable(gate);
    }
    try{
      // set table in disabling state.
      am.getZKTable().setDisablingTable(REGIONINFO.getTableNameAsString());
      am.joinCluster();
      // should not call retainAssignment if we get empty regions in assignAllUserRegions.
      assertFalse(
          "Assign should not be invoked for disabling table regions during clean cluster startup.",
          gate.get());
      // need to change table state from disabling to disabled.
      assertTrue("Table should be disabled.",
          am.getZKTable().isDisabledTable(REGIONINFO.getTableNameAsString()));
    } finally {
      this.server.getConfiguration().setClass(HConstants.HBASE_MASTER_LOADBALANCER_CLASS,
View Full Code Here

        ct.setMetaLocation(SN);
        // Call the method that HBASE-4288 calls.  It will try and verify the
        // meta location and will fail on first attempt then go into a long wait.
        // So, do this in a thread and then reset meta location to break it out
        // of its wait after a bit of time.
        final AtomicBoolean metaSet = new AtomicBoolean(false);
        final CountDownLatch latch = new CountDownLatch(1);
        Thread t = new Thread() {
          @Override
          public void run() {
            try {
              latch.countDown();
              metaSet.set(ct.waitForMeta(100000) !=  null);
            } catch (Exception e) {
              throw new RuntimeException(e);
            }
          }
        };
        t.start();
        latch.await();
        Threads.sleep(1);
        // Now reset the meta as though it were redeployed.
        ct.setMetaLocation(SN);
        t.join();
        Assert.assertTrue(metaSet.get());
      } finally {
        // Clean out root and meta locations or later tests will be confused...
        // they presume start fresh in zk.
        ct.resetMetaLocation();
        RootLocationEditor.deleteRootLocation(this.watcher);
View Full Code Here

                              final ZooKeeperWatcher zk)
    throws KeeperException {

    this.conf = conf;
    this.zookeeper = zk;
    this.replicating = new AtomicBoolean();
    setZNodes(abortable);
  }
View Full Code Here

    final int NUM_INDEX_THREADS = 2;
    final int NUM_SEARCH_THREADS = 3;

    final int RUN_TIME_SEC = LuceneTestCase.TEST_NIGHTLY ? 300 : RANDOM_MULTIPLIER;

    final AtomicBoolean failed = new AtomicBoolean();
    final AtomicInteger addCount = new AtomicInteger();
    final AtomicInteger delCount = new AtomicInteger();
    final AtomicInteger packCount = new AtomicInteger();

    final Set<String> delIDs = Collections.synchronizedSet(new HashSet<String>());
    final List<SubDocs> allSubDocs = Collections.synchronizedList(new ArrayList<SubDocs>());

    final long stopTime = System.currentTimeMillis() + RUN_TIME_SEC*1000;
    Thread[] threads = new Thread[NUM_INDEX_THREADS];
    for(int thread=0;thread<NUM_INDEX_THREADS;thread++) {
      threads[thread] = new Thread() {
          @Override
          public void run() {
            // TODO: would be better if this were cross thread, so that we make sure one thread deleting anothers added docs works:
            final List<String> toDeleteIDs = new ArrayList<String>();
            final List<SubDocs> toDeleteSubDocs = new ArrayList<SubDocs>();
            while(System.currentTimeMillis() < stopTime && !failed.get()) {
              try {
                Document doc = docs.nextDoc();
                if (doc == null) {
                  break;
                }
                final String addedField;
                if (random.nextBoolean()) {
                  addedField = "extra" + random.nextInt(10);
                  doc.add(new Field(addedField, "a random field", Field.Store.NO, Field.Index.ANALYZED));
                } else {
                  addedField = null;
                }
                if (random.nextBoolean()) {
                  if (VERBOSE) {
                    System.out.println(Thread.currentThread().getName() + ": add doc id:" + doc.get("docid"));
                  }

                  if (random.nextBoolean()) {
                    // Add a pack of adjacent sub-docs
                    final String packID;
                    final SubDocs delSubDocs;
                    if (toDeleteSubDocs.size() > 0 && random.nextBoolean()) {
                      delSubDocs = toDeleteSubDocs.get(random.nextInt(toDeleteSubDocs.size()));
                      assert !delSubDocs.deleted;
                      toDeleteSubDocs.remove(delSubDocs);
                      // reuse prior packID
                      packID = delSubDocs.packID;
                    } else {
                      delSubDocs = null;
                      // make new packID
                      packID = packCount.getAndIncrement() + "";
                    }

                    final Field packIDField = newField("packID", packID, Field.Store.YES, Field.Index.NOT_ANALYZED);
                    final List<String> docIDs = new ArrayList<String>();
                    final SubDocs subDocs = new SubDocs(packID, docIDs);
                    final List<Document> docsList = new ArrayList<Document>();

                    allSubDocs.add(subDocs);
                    doc.add(packIDField);
                    docsList.add(cloneDoc(doc));
                    docIDs.add(doc.get("docid"));

                    final int maxDocCount = _TestUtil.nextInt(random, 1, 10);
                    while(docsList.size() < maxDocCount) {
                      doc = docs.nextDoc();
                      if (doc == null) {
                        break;
                      }
                      docsList.add(cloneDoc(doc));
                      docIDs.add(doc.get("docid"));
                    }
                    addCount.addAndGet(docsList.size());

                    if (delSubDocs != null) {
                      delSubDocs.deleted = true;
                      delIDs.addAll(delSubDocs.subIDs);
                      delCount.addAndGet(delSubDocs.subIDs.size());
                      if (VERBOSE) {
                        System.out.println("TEST: update pack packID=" + delSubDocs.packID + " count=" + docsList.size() + " docs=" + docIDs);
                      }
                      writer.updateDocuments(new Term("packID", delSubDocs.packID), docsList);
                      /*
                      // non-atomic:
                      writer.deleteDocuments(new Term("packID", delSubDocs.packID));
                      for(Document subDoc : docsList) {
                        writer.addDocument(subDoc);
                      }
                      */
                    } else {
                      if (VERBOSE) {
                        System.out.println("TEST: add pack packID=" + packID + " count=" + docsList.size() + " docs=" + docIDs);
                      }
                      writer.addDocuments(docsList);
                     
                      /*
                      // non-atomic:
                      for(Document subDoc : docsList) {
                        writer.addDocument(subDoc);
                      }
                      */
                    }
                    doc.removeField("packID");

                    if (random.nextInt(5) == 2) {
                      if (VERBOSE) {
                        //System.out.println(Thread.currentThread().getName() + ": buffer del id:" + packID);
                      }
                      toDeleteSubDocs.add(subDocs);
                    }

                  } else {
                    writer.addDocument(doc);
                    addCount.getAndIncrement();

                    if (random.nextInt(5) == 3) {
                      if (VERBOSE) {
                        //System.out.println(Thread.currentThread().getName() + ": buffer del id:" + doc.get("docid"));
                      }
                      toDeleteIDs.add(doc.get("docid"));
                    }
                  }
                } else {
                  // we use update but it never replaces a
                  // prior doc
                  if (VERBOSE) {
                    System.out.println(Thread.currentThread().getName() + ": update doc id:" + doc.get("docid"));
                  }
                  writer.updateDocument(new Term("docid", doc.get("docid")), doc);
                  addCount.getAndIncrement();

                  if (random.nextInt(5) == 3) {
                    if (VERBOSE) {
                      //System.out.println(Thread.currentThread().getName() + ": buffer del id:" + doc.get("docid"));
                    }
                    toDeleteIDs.add(doc.get("docid"));
                  }
                }

                if (random.nextInt(30) == 17) {
                  if (VERBOSE) {
                    System.out.println(Thread.currentThread().getName() + ": apply " + toDeleteIDs.size() + " deletes");
                  }
                  for(String id : toDeleteIDs) {
                    if (VERBOSE) {
                      System.out.println(Thread.currentThread().getName() + ": del term=id:" + id);
                    }
                    writer.deleteDocuments(new Term("docid", id));
                  }
                  final int count = delCount.addAndGet(toDeleteIDs.size());
                  if (VERBOSE) {
                    System.out.println(Thread.currentThread().getName() + ": tot " + count + " deletes");
                  }
                  delIDs.addAll(toDeleteIDs);
                  toDeleteIDs.clear();

                  for(SubDocs subDocs : toDeleteSubDocs) {
                    assert !subDocs.deleted;
                    writer.deleteDocuments(new Term("packID", subDocs.packID));
                    subDocs.deleted = true;
                    if (VERBOSE) {
                      System.out.println("  del subs: " + subDocs.subIDs + " packID=" + subDocs.packID);
                    }
                    delIDs.addAll(subDocs.subIDs);
                    delCount.addAndGet(subDocs.subIDs.size());
                  }
                  toDeleteSubDocs.clear();
                }
                if (addedField != null) {
                  doc.removeField(addedField);
                }
              } catch (Throwable t) {
                System.out.println(Thread.currentThread().getName() + ": hit exc");
                t.printStackTrace();
                failed.set(true);
                throw new RuntimeException(t);
              }
            }
            if (VERBOSE) {
              System.out.println(Thread.currentThread().getName() + ": indexing done");
            }
          }
        };
      threads[thread].setDaemon(true);
      threads[thread].start();
    }

    if (VERBOSE) {
      System.out.println("TEST: DONE start indexing threads [" + (System.currentTimeMillis()-t0) + " ms]");
    }

    // let index build up a bit
    Thread.sleep(100);

    IndexReader r = IndexReader.open(writer, true);
    boolean any = false;

    // silly starting guess:
    final AtomicInteger totTermCount = new AtomicInteger(100);

    final ExecutorService es = Executors.newCachedThreadPool();

    while(System.currentTimeMillis() < stopTime && !failed.get()) {
      if (random.nextBoolean()) {
        if (VERBOSE) {
          System.out.println("TEST: now reopen r=" + r);
        }
        final IndexReader r2 = r.reopen();
        if (r != r2) {
          r.close();
          r = r2;
        }
      } else {
        if (VERBOSE) {
          System.out.println("TEST: now close reader=" + r);
        }
        r.close();
        writer.commit();
        final Set<String> openDeletedFiles = dir.getOpenDeletedFiles();
        if (openDeletedFiles.size() > 0) {
          System.out.println("OBD files: " + openDeletedFiles);
        }
        any |= openDeletedFiles.size() > 0;
        //assertEquals("open but deleted: " + openDeletedFiles, 0, openDeletedFiles.size());
        if (VERBOSE) {
          System.out.println("TEST: now open");
        }
        r = IndexReader.open(writer, true);
      }
      if (VERBOSE) {
        System.out.println("TEST: got new reader=" + r);
      }
      //System.out.println("numDocs=" + r.numDocs() + "
      //openDelFileCount=" + dir.openDeleteFileCount());

      smokeTestReader(r);

      if (r.numDocs() > 0) {

        final IndexSearcher s = new IndexSearcher(r, es);

        // run search threads
        final long searchStopTime = System.currentTimeMillis() + 500;
        final Thread[] searchThreads = new Thread[NUM_SEARCH_THREADS];
        final AtomicInteger totHits = new AtomicInteger();
        for(int thread=0;thread<NUM_SEARCH_THREADS;thread++) {
          searchThreads[thread] = new Thread() {
              @Override
              public void run() {
                try {
                  TermEnum termEnum = s.getIndexReader().terms(new Term("body", ""));
                  int seenTermCount = 0;
                  int shift;
                  int trigger;
                  if (totTermCount.get() < 10) {
                    shift = 0;
                    trigger = 1;
                  } else {
                    trigger = totTermCount.get()/10;
                    shift = random.nextInt(trigger);
                  }
                  while(System.currentTimeMillis() < searchStopTime) {
                    Term term = termEnum.term();
                    if (term == null) {
                      if (seenTermCount < 10) {
                        break;
                      }
                      totTermCount.set(seenTermCount);
                      seenTermCount = 0;
                      trigger = totTermCount.get()/10;
                      //System.out.println("trigger " + trigger);
                      shift = random.nextInt(trigger);
                      termEnum = s.getIndexReader().terms(new Term("body", ""));
                      continue;
                    }
                    seenTermCount++;
                    // search 10 terms
                    if (trigger == 0) {
                      trigger = 1;
                    }
                    if ((seenTermCount + shift) % trigger == 0) {
                      //if (VERBOSE) {
                      //System.out.println(Thread.currentThread().getName() + " now search body:" + term.utf8ToString());
                      //}
                      totHits.addAndGet(runQuery(s, new TermQuery(term)));
                    }
                    termEnum.next();
                  }
                  if (VERBOSE) {
                    System.out.println(Thread.currentThread().getName() + ": search done");
                  }
                } catch (Throwable t) {
                  System.out.println(Thread.currentThread().getName() + ": hit exc");
                  failed.set(true);
                  t.printStackTrace(System.out);
                  throw new RuntimeException(t);
                }
              }
            };
View Full Code Here

        }
    }
    @Test
    public void testBusConfigureCreateBus() {
        ClassPathXmlApplicationContext context = null;
        final AtomicBoolean b = new AtomicBoolean();
        try {
            context = new ClassPathXmlApplicationContext("org/apache/cxf/bus/spring/customerBus2.xml");
            Bus cxf1 = (Bus)context.getBean("cxf1");
           
            assertTrue(cxf1.getOutInterceptors().size() == 1);
            assertTrue(cxf1.getInInterceptors().size() == 0);
           
            Bus cxf2 = (Bus)context.getBean("cxf2");
           
            assertTrue(cxf2.getInInterceptors().size() == 1);
            assertTrue(cxf2.getOutInterceptors().size() == 0);
           
            cxf2.getExtension(BusLifeCycleManager.class)
                .registerLifeCycleListener(new BusLifeCycleListener() {
                    public void initComplete() {
                    }

                    public void preShutdown() {
                    }

                    public void postShutdown() {
                        b.set(true);
                    }
                   
                });
        } finally {
            if (context != null) {
                context.close();
            }
        }
        assertTrue("postShutdown not called", b.get());
    }
View Full Code Here

        {
            _queue =
                    new FlowControllingBlockingQueue(_prefetchHighMark, _prefetchLowMark,
                                                     new FlowControllingBlockingQueue.ThresholdListener()
                                                     {
                                                         private final AtomicBoolean _suspendState = new AtomicBoolean();

                                                         public void aboveThreshold(int currentValue)
                                                         {
                                                             // If the session has been closed don't waste time creating a thread to do
                                                             // flow control
                                                             if (!(AMQSession.this.isClosed() || AMQSession.this.isClosing()))
                                                             {
                                                                 // Only execute change if previous state
                                                                 // was False
                                                                 if (!_suspendState.getAndSet(true))
                                                                 {
                                                                     if (_logger.isDebugEnabled())
                                                                     {
                                                                         _logger.debug(
                                                                                 "Above threshold(" + _prefetchHighMark
                                                                                 + ") so suspending channel. Current value is " + currentValue);
                                                                     }
                                                                     try
                                                                     {
                                                                         Threading.getThreadFactory().createThread(new SuspenderRunner(_suspendState)).start();
                                                                     }
                                                                     catch (Exception e)
                                                                     {
                                                                         throw new RuntimeException("Failed to create thread", e);
                                                                     }
                                                                 }
                                                             }
                                                         }

                                                         public void underThreshold(int currentValue)
                                                         {
                                                             // If the session has been closed don't waste time creating a thread to do
                                                             // flow control
                                                             if (!(AMQSession.this.isClosed() || AMQSession.this.isClosing()))
                                                             {
                                                                 // Only execute change if previous state
                                                                 // was true
                                                                 if (_suspendState.getAndSet(false))
                                                                 {
                                                                     if (_logger.isDebugEnabled())
                                                                     {

                                                                         _logger.debug(
View Full Code Here

TOP

Related Classes of java.util.concurrent.atomic.AtomicBoolean

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.