Java Code Examples for java.util.concurrent.atomic.AtomicInteger

The following are top voted examples for showing how to use java.util.concurrent.atomic.AtomicInteger. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: hadoop   File: WeightedRoundRobinMultiplexer.java   View source code 7 votes vote down vote up
public WeightedRoundRobinMultiplexer(int aNumQueues, String ns,
  Configuration conf) {
  if (aNumQueues <= 0) {
    throw new IllegalArgumentException("Requested queues (" + aNumQueues +
      ") must be greater than zero.");
  }

  this.numQueues = aNumQueues;
  this.queueWeights = conf.getInts(ns + "." +
    IPC_CALLQUEUE_WRRMUX_WEIGHTS_KEY);

  if (this.queueWeights.length == 0) {
    this.queueWeights = getDefaultQueueWeights(this.numQueues);
  } else if (this.queueWeights.length != this.numQueues) {
    throw new IllegalArgumentException(ns + "." +
      IPC_CALLQUEUE_WRRMUX_WEIGHTS_KEY + " must specify exactly " +
      this.numQueues + " weights: one for each priority level.");
  }

  this.currentQueueIndex = new AtomicInteger(0);
  this.requestsLeft = new AtomicInteger(this.queueWeights[0]);

  LOG.info("WeightedRoundRobinMultiplexer is being used.");
}
 
Example 2
Project: https-github.com-apache-zookeeper   File: LeaderElectionSupportTest.java   View source code 6 votes vote down vote up
@Test
public void testNodes9() throws IOException, InterruptedException,
    KeeperException {

  int testIterations = 9;
  final CountDownLatch latch = new CountDownLatch(testIterations);
  final AtomicInteger failureCounter = new AtomicInteger();

  for (int i = 0; i < testIterations; i++) {
    runElectionSupportThread(latch, failureCounter);
  }

  Assert.assertEquals(0, failureCounter.get());

  if (!latch.await(10, TimeUnit.SECONDS)) {
    logger
        .info(
            "Waited for all threads to start, but timed out. We had {} failures.",
            failureCounter);
  }
}
 
Example 3
Project: GitHub   File: ListPreloaderTest.java   View source code 6 votes vote down vote up
@Test
public void testGetItemsIsCalledIncreasing() {
  final AtomicBoolean called = new AtomicBoolean(false);
  final AtomicInteger calledCount = new AtomicInteger();

  ListPreloaderAdapter preloaderAdapter = new ListPreloaderAdapter() {
    @NonNull
    @Override
    public List<Object> getPreloadItems(int position) {
      called.set(true);
      final int count = calledCount.getAndIncrement();
      assertEquals(11 + count, position);
      return super.getPreloadItems(position);
    }
  };
  ListPreloader<Object> preloader = new ListPreloader<>(requestManager,
      preloaderAdapter, preloaderAdapter, 10);
  preloader.onScroll(null, 1, 10, 30);
  assertEquals(10, calledCount.get());
}
 
Example 4
Project: incubator-netbeans   File: JavaRefactoringActionsProviderTest.java   View source code 6 votes vote down vote up
public void test211193() throws Exception {
    writeFilesAndWaitForScan(src,
            new File("t/A.java", "package t;\n"
            + "public class A {\n"
            + "    public static void foo() {\n"
            + "        int someArray[] = {};\n"
            + "    }\n"
            + "}"));
    FileObject testFile = src.getFileObject("t/A.java");
    DataObject testFileDO = DataObject.find(testFile);
    EditorCookie ec = testFileDO.getLookup().lookup(EditorCookie.class);
    ec.open();
    ec.getOpenedPanes()[0].setCaretPosition(71);
    ec.getOpenedPanes()[0].moveCaretPosition(80);
    final AtomicInteger called = new AtomicInteger();
    ContextAnalyzer.SHOW = new ContextAnalyzer.ShowUI() {
        @Override
        public void show(RefactoringUI ui, TopComponent activetc) {
            assertNotNull(ui);
            called.incrementAndGet();
        }
    };
    int expectedCount = 0;
    new RefactoringActionsProvider().doRename(Lookups.fixed(ec));
    assertEquals(++expectedCount, called.get());
}
 
Example 5
Project: kafka-0.11.0.0-src-with-comment   File: WorkerSourceTaskTest.java   View source code 6 votes vote down vote up
private CountDownLatch expectPolls(int minimum, final AtomicInteger count) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(minimum);
    // Note that we stub these to allow any number of calls because the thread will continue to
    // run. The count passed in + latch returned just makes sure we get *at least* that number of
    // calls
    EasyMock.expect(sourceTask.poll())
            .andStubAnswer(new IAnswer<List<SourceRecord>>() {
                @Override
                public List<SourceRecord> answer() throws Throwable {
                    count.incrementAndGet();
                    latch.countDown();
                    return RECORDS;
                }
            });
    // Fallout of the poll() call
    expectSendRecordAnyTimes();
    return latch;
}
 
Example 6
Project: concurrentli   File: AutoResetEventTest.java   View source code 6 votes vote down vote up
@Test
public void test() throws InterruptedException {
  AtomicInteger incrementor = new AtomicInteger();
  ResettableEvent are = new ResettableEvent(true);
  ResettableEvent done = new ResettableEvent(false);

  ExecutorService threadPool = Executors.newFixedThreadPool(3);
  for (int i = 0; i < 10; i++) {
    threadPool.submit(Interrupted.unchecked(() -> {
      are.getAndReset();
      incrementor.incrementAndGet();
      done.set();
    }));
  }

  done.getAndReset();
  Thread.sleep(100); // give a little time to other threads to increment, if there's indeed a bug
  assertEquals(1, incrementor.get());
  threadPool.shutdownNow();
}
 
Example 7
Project: monarch   File: ForceableLinkedBlockingQueue.java   View source code 6 votes vote down vote up
/**
 * Inserts the specified element at the tail of this queue if it is possible to do so immediately
 * without exceeding the queue's capacity, returning {@code true} upon success and {@code false}
 * if this queue is full. When using a capacity-restricted queue, this method is generally
 * preferable to method {@link BlockingQueue#add add}, which can fail to insert an element only by
 * throwing an exception.
 *
 * @throws NullPointerException if the specified element is null
 */
public boolean offer(E e) {
  if (e == null)
    throw new NullPointerException();
  final AtomicInteger count = this.count;
  if (count.get() >= capacity) // GEMFIRE changed == to >=
    return false;
  int c = -1;
  final ReentrantLock putLock = this.putLock;
  putLock.lock();
  try {
    if (count.get() < capacity) {
      enqueue(e);
      c = count.getAndIncrement();
      if (c + 1 < capacity)
        notFull.signal();
    }
  } finally {
    putLock.unlock();
  }
  if (c == 0)
    signalNotEmpty();
  return c >= 0;
}
 
Example 8
Project: android-deferred   File: MultiplePromisesTest.java   View source code 6 votes vote down vote up
@Test
public void testFutures() {
	final Callable<Integer> callable1 = successCallable(999, 100);
	final Callable<String> callable2 = successCallable("HI", 1000);
	
	ExecutorService es = deferredManager.getExecutorService();
	Future<Integer> future1 = es.submit(callable1);
	Future<String> future2 = es.submit(callable2);
	final AtomicInteger doneCount = new AtomicInteger();
	deferredManager.when(future1, future2).done(new DoneCallback<MultipleResults>() {
		@Override
		public void onDone(MultipleResults result) {
			Assert.assertEquals(2, result.size());
			Assert.assertEquals(999, result.get(0).getResult());
			Assert.assertEquals("HI", result.get(1).getResult());
			doneCount.incrementAndGet();
		}
	});
	
	waitForCompletion();
	Assert.assertEquals(1, doneCount.get());
}
 
Example 9
Project: redg   File: PluggableDefaultValueStrategyTest.java   View source code 6 votes vote down vote up
@Test
public void testProvider_StaticNumberProvider() {
    PluggableDefaultValueStrategy strategy = new PluggableDefaultValueStrategy();
    strategy.addProvider(new StaticNumberProvider(42L));

    assertEquals(Long.valueOf(42L), strategy.getDefaultValue(TestUtils.getCM("", "", "", Long.class, false), Long.class));
    assertNull(strategy.getDefaultValue(TestUtils.getCM("", "", "", String.class, false), String.class));
    assertEquals(42L, (long) strategy.getDefaultValue(TestUtils.getCM("", "", "", Long.class, true), Long.class));
    assertEquals(42, (int) strategy.getDefaultValue(TestUtils.getCM("", "", "", Integer.class, true), Integer.class));
    assertEquals(42.0, strategy.getDefaultValue(TestUtils.getCM("", "", "", Double.class, true), Double.class), 0.0);
    assertEquals(42.0f, strategy.getDefaultValue(TestUtils.getCM("", "", "", Float.class, true), Float.class), 0f);
    assertEquals(new BigDecimal(42), strategy.getDefaultValue(TestUtils.getCM("", "", "", BigDecimal.class, true), BigDecimal.class));
    assertEquals((byte) 42, (byte) strategy.getDefaultValue(TestUtils.getCM("", "", "", Byte.class, true), Byte.class));
    assertEquals((short) 42, (short) strategy.getDefaultValue(TestUtils.getCM("", "", "", Short.class, true), Short.class));
    assertEquals(42, strategy.getDefaultValue(TestUtils.getCM("", "", "", AtomicInteger.class, true), AtomicInteger.class).get());
    assertEquals(42L, strategy.getDefaultValue(TestUtils.getCM("", "", "", AtomicLong.class, true), AtomicLong.class).get());

    assertNull(new StaticNumberProvider(BigDecimal.ONE).convertNumber(new BigDecimal(0), String.class));
}
 
Example 10
Project: CustomListView   File: SmartExecutor.java   View source code 6 votes vote down vote up
public static ThreadPoolExecutor createDefaultThreadPool() {
    // 控制最多4个keep在pool中
    int corePoolSize = Math.min(4, CPU_CORE);
    return new ThreadPoolExecutor(
            corePoolSize,
            Integer.MAX_VALUE,
            DEFAULT_CACHE_SENCOND, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>(),
            new ThreadFactory() {
                static final String NAME = "lite-";
                AtomicInteger IDS = new AtomicInteger(1);

                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r, NAME + IDS.getAndIncrement());
                }
            },
            new ThreadPoolExecutor.DiscardPolicy());
}
 
Example 11
Project: googles-monorepo-demo   File: ConcurrentHashMultisetTest.java   View source code 6 votes vote down vote up
public void testSerializationWithMapMaker_preservesIdentityKeyEquivalence() {
  ConcurrentMap<String, AtomicInteger> map =
      new MapMaker().keyEquivalence(Equivalence.identity()).makeMap();

  ConcurrentHashMultiset<String> multiset = ConcurrentHashMultiset.create(map);
  multiset = reserializeAndAssert(multiset);

  String s1 = new String("a");
  String s2 = new String("a");
  assertEquals(s1, s2); // Stating the obvious.
  assertTrue(s1 != s2); // Stating the obvious.

  multiset.add(s1);
  assertTrue(multiset.contains(s1));
  assertFalse(multiset.contains(s2));
  assertEquals(1, multiset.count(s1));
  assertEquals(0, multiset.count(s2));
}
 
Example 12
Project: hekate   File: FailoverAggregateTest.java   View source code 6 votes vote down vote up
@Test
public void testPartialSuccess() throws Exception {
    repeat(2, i -> {
        int attempts = i + 1;

        failures.set(attempts);

        AtomicInteger failoverCalls = new AtomicInteger();

        AggregateResult<String> result = get(sender.get().withFailover(context -> {
            failoverCalls.incrementAndGet();

            return context.retry();
        }).aggregate("test"));

        assertTrue(result.isSuccess());
        assertEquals(channels.size(), result.results().size());

        assertEquals(attempts, failoverCalls.get());
    });
}
 
Example 13
Project: GitHub   File: CallTest.java   View source code 6 votes vote down vote up
@Test public void requestBeforeExecuteCreates() throws IOException {
  Retrofit retrofit = new Retrofit.Builder()
      .baseUrl(server.url("/"))
      .addConverterFactory(new ToStringConverterFactory())
      .build();
  Service service = retrofit.create(Service.class);

  server.enqueue(new MockResponse());

  final AtomicInteger writeCount = new AtomicInteger();
  Object a = new Object() {
    @Override public String toString() {
      writeCount.incrementAndGet();
      return "Hello";
    }
  };
  Call<String> call = service.postRequestBody(a);

  call.request();
  assertThat(writeCount.get()).isEqualTo(1);

  call.execute();
  assertThat(writeCount.get()).isEqualTo(1);
}
 
Example 14
Project: OpenJSharp   File: DecimalFormat.java   View source code 6 votes vote down vote up
/**
 * Formats an Object producing an <code>AttributedCharacterIterator</code>.
 * You can use the returned <code>AttributedCharacterIterator</code>
 * to build the resulting String, as well as to determine information
 * about the resulting String.
 * <p>
 * Each attribute key of the AttributedCharacterIterator will be of type
 * <code>NumberFormat.Field</code>, with the attribute value being the
 * same as the attribute key.
 *
 * @exception NullPointerException if obj is null.
 * @exception IllegalArgumentException when the Format cannot format the
 *            given object.
 * @exception        ArithmeticException if rounding is needed with rounding
 *                   mode being set to RoundingMode.UNNECESSARY
 * @param obj The object to format
 * @return AttributedCharacterIterator describing the formatted value.
 * @since 1.4
 */
@Override
public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
    CharacterIteratorFieldDelegate delegate =
                     new CharacterIteratorFieldDelegate();
    StringBuffer sb = new StringBuffer();

    if (obj instanceof Double || obj instanceof Float) {
        format(((Number)obj).doubleValue(), sb, delegate);
    } else if (obj instanceof Long || obj instanceof Integer ||
               obj instanceof Short || obj instanceof Byte ||
               obj instanceof AtomicInteger || obj instanceof AtomicLong) {
        format(((Number)obj).longValue(), sb, delegate);
    } else if (obj instanceof BigDecimal) {
        format((BigDecimal)obj, sb, delegate);
    } else if (obj instanceof BigInteger) {
        format((BigInteger)obj, sb, delegate, false);
    } else if (obj == null) {
        throw new NullPointerException(
            "formatToCharacterIterator must be passed non-null object");
    } else {
        throw new IllegalArgumentException(
            "Cannot format given Object as a Number");
    }
    return delegate.getIterator(sb.toString());
}
 
Example 15
Project: dubbox-hystrix   File: HeaderExchangeHandlerTest.java   View source code 6 votes vote down vote up
@Test
public void test_received_request_twoway_error_reqeustBroken() throws RemotingException{
    final Request request = new Request();
    request.setTwoWay(true);
    request.setData(new BizException());
    request.setBroken(true);
    
    final AtomicInteger count = new AtomicInteger(0);
    final Channel mchannel = new MockedChannel(){
        @Override
        public void send(Object message) throws RemotingException {
            Response res = (Response)message;
            Assert.assertEquals(request.getId(), res.getId());
            Assert.assertEquals(request.getVersion(), res.getVersion());
            Assert.assertEquals(Response.BAD_REQUEST, res.getStatus());
            Assert.assertNull(res.getResult());
            Assert.assertTrue(res.getErrorMessage().contains(BizException.class.getName()));
            count.incrementAndGet();
        }
    };
    HeaderExchangeHandler hexhandler = new HeaderExchangeHandler(new MockedExchangeHandler());
    hexhandler.received(mchannel, request);
    Assert.assertEquals(1, count.get());
}
 
Example 16
Project: guava-mock   File: SupplementalMonitorTest.java   View source code 6 votes vote down vote up
private static void verifyOccupiedMethodsInAnotherThread(final Monitor monitor,
    boolean expectedIsOccupied, boolean expectedIsOccupiedByCurrentThread,
    int expectedOccupiedDepth) {
  final AtomicBoolean actualIsOccupied = new AtomicBoolean();
  final AtomicBoolean actualIsOccupiedByCurrentThread = new AtomicBoolean();
  final AtomicInteger actualOccupiedDepth = new AtomicInteger();
  final AtomicReference<Throwable> thrown = new AtomicReference<Throwable>();
  joinUninterruptibly(startThread(new Runnable() {
    @Override public void run() {
      try {
        actualIsOccupied.set(monitor.isOccupied());
        actualIsOccupiedByCurrentThread.set(monitor.isOccupiedByCurrentThread());
        actualOccupiedDepth.set(monitor.getOccupiedDepth());
      } catch (Throwable t) {
        thrown.set(t);
      }
    }
  }));
  assertNull(thrown.get());
  assertEquals(expectedIsOccupied, actualIsOccupied.get());
  assertEquals(expectedIsOccupiedByCurrentThread, actualIsOccupiedByCurrentThread.get());
  assertEquals(expectedOccupiedDepth, actualOccupiedDepth.get());
}
 
Example 17
Project: https-github.com-apache-zookeeper   File: LeaderElectionSupportTest.java   View source code 6 votes vote down vote up
@Test
public void testNodes3() throws IOException, InterruptedException,
    KeeperException {

  int testIterations = 3;
  final CountDownLatch latch = new CountDownLatch(testIterations);
  final AtomicInteger failureCounter = new AtomicInteger();

  for (int i = 0; i < testIterations; i++) {
    runElectionSupportThread(latch, failureCounter);
  }

  Assert.assertEquals(0, failureCounter.get());

  if (!latch.await(10, TimeUnit.SECONDS)) {
    logger
        .info(
            "Waited for all threads to start, but timed out. We had {} failures.",
            failureCounter);
  }
}
 
Example 18
Project: sqs-utils   File: MessageWorkerTest.java   View source code 6 votes vote down vote up
@Test
public void testWorkDelegatesMethodCall() throws Exception {
    // given
    AtomicInteger counter = new AtomicInteger(0);
    MessageWorker<String, Integer> uut = new MessageWorker<String, Integer>() {
        @Override
        public Integer work(String object) {
            return counter.incrementAndGet();
        }
    };
    MessageHeaders messageHeaders = mock(MessageHeaders.class);

    // when
    uut.work("dummy value", messageHeaders);

    // then
    assertEquals(1, counter.intValue());
    verifyZeroInteractions(messageHeaders);
}
 
Example 19
Project: openjdk-jdk10   File: DelayOverflow.java   View source code 6 votes vote down vote up
void test(String[] args) throws Throwable {
    for (int how=0; how<4; how++) {
        final CountDownLatch done = new CountDownLatch(1);
        final AtomicInteger count = new AtomicInteger(0);
        final Timer timer = new Timer();
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                checkScheduledExecutionTime(this);
                count.incrementAndGet();
                done.countDown();
            }};

        scheduleNow(timer, task, how);
        done.await();
        equal(count.get(), 1);
        checkScheduledExecutionTime(task);
        if (new java.util.Random().nextBoolean())
            sleep(10);
        check(task.cancel());
        timer.cancel();
        checkScheduledExecutionTime(task);
    }
}
 
Example 20
Project: RxJava3-preview   File: MaybeFromCallableTest.java   View source code 6 votes vote down vote up
@Test
public void fromCallable() {
    final AtomicInteger atomicInteger = new AtomicInteger();

    Maybe.fromCallable(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            atomicInteger.incrementAndGet();
            return null;
        }
    })
        .test()
        .assertResult();

    assertEquals(1, atomicInteger.get());
}
 
Example 21
Project: ditb   File: HBaseFsck.java   View source code 6 votes vote down vote up
/**
 * TODO -- need to add tests for this.
 */
private void reportTablesInFlux() {
  AtomicInteger numSkipped = new AtomicInteger(0);
  HTableDescriptor[] allTables = getTables(numSkipped);
  errors.print("Number of Tables: " + allTables.length);
  if (details) {
    if (numSkipped.get() > 0) {
      errors.detail("Number of Tables in flux: " + numSkipped.get());
    }
    for (HTableDescriptor td : allTables) {
      errors.detail("  Table: " + td.getTableName() + "\t" +
                         (td.isReadOnly() ? "ro" : "rw") + "\t" +
                          (td.isMetaRegion() ? "META" : "    ") + "\t" +
                         " families: " + td.getFamilies().size());
    }
  }
}
 
Example 22
Project: GitHub   File: CallTest.java   View source code 6 votes vote down vote up
@Test public void requestAfterExecuteReturnsCachedValue() throws IOException {
  Retrofit retrofit = new Retrofit.Builder()
      .baseUrl(server.url("/"))
      .addConverterFactory(new ToStringConverterFactory())
      .build();
  Service service = retrofit.create(Service.class);

  server.enqueue(new MockResponse());

  final AtomicInteger writeCount = new AtomicInteger();
  Object a = new Object() {
    @Override public String toString() {
      writeCount.incrementAndGet();
      return "Hello";
    }
  };
  Call<String> call = service.postRequestBody(a);

  call.execute();
  assertThat(writeCount.get()).isEqualTo(1);

  call.request();
  assertThat(writeCount.get()).isEqualTo(1);
}
 
Example 23
Project: sstore-soft   File: StreamServer.java   View source code 6 votes vote down vote up
public StreamServer(Socket aClientSocket, RateLimiter rateLimiter, long startTime, int duration,
    BufferedReader dataSource, AtomicInteger consumedTuples, int maxTupels) {

  try {
    _duration = duration;
    _sourceBuffer = dataSource;
    _rateLimiter = rateLimiter;
    _clientSocket = aClientSocket;
    _startTime = startTime;
    _cosumedTuples = consumedTuples;
    _maxTuples = maxTupels;
    _output = new BufferedOutputStream(_clientSocket.getOutputStream());
    this.start();
  } catch (IOException e) {
    System.out.println(e.getMessage());
  }
}
 
Example 24
Project: fluid   File: KafkaSourceTest.java   View source code 6 votes vote down vote up
@Test
public void testSource() throws InterruptedException {
  KafkaUsage usage = new KafkaUsage();
  String topic = UUID.randomUUID().toString();
  List<Integer> results = new ArrayList<>();
  KafkaSource<Integer> source = new KafkaSource<>(vertx,
    getKafkaConfig()
      .put("topic", topic)
      .put("value.serializer", IntegerSerializer.class.getName())
      .put("value.deserializer", IntegerDeserializer.class.getName())
  );
  source
    .transformPayload(i -> i + 1)
    .to(Sink.forEachPayload(results::add));

  AtomicInteger counter = new AtomicInteger();
  usage.produceIntegers(10, null,
    () -> new ProducerRecord<>(topic, counter.getAndIncrement()));

  await().atMost(1, TimeUnit.MINUTES).until(() -> results.size() >= 10);
  assertThat(results).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
 
Example 25
Project: incubator-netbeans   File: Stamps.java   View source code 6 votes vote down vote up
private static boolean highestStampForDir(File file, AtomicReference<File> newestFile, AtomicLong result, AtomicInteger crc) {
    if (file.getName().equals(".nbattrs")) { // NOI18N
        return true;
    }

    File[] children = file.listFiles();
    if (children == null) {
        if (crc != null) {
            crc.addAndGet(file.getName().length());
        }
        long time = file.lastModified();
        if (time > result.longValue()) {
            newestFile.set(file);
            result.set(time);
        }
        return false;
    }
    
    for (File f : children) {
        highestStampForDir(f, newestFile, result, crc);
    }
    return true;
}
 
Example 26
Project: Elasticsearch   File: SearchDfsQueryThenFetchAsyncAction.java   View source code 6 votes vote down vote up
void executeFetch(final int shardIndex, final SearchShardTarget shardTarget, final AtomicInteger counter,
                  final ShardFetchSearchRequest fetchSearchRequest, DiscoveryNode node) {
    searchService.sendExecuteFetch(node, fetchSearchRequest, new ActionListener<FetchSearchResult>() {
        @Override
        public void onResponse(FetchSearchResult result) {
            result.shardTarget(shardTarget);
            fetchResults.set(shardIndex, result);
            if (counter.decrementAndGet() == 0) {
                finishHim();
            }
        }

        @Override
        public void onFailure(Throwable t) {
            // the search context might not be cleared on the node where the fetch was executed for example
            // because the action was rejected by the thread pool. in this case we need to send a dedicated
            // request to clear the search context. by setting docIdsToLoad to null, the context will be cleared
            // in TransportSearchTypeAction.releaseIrrelevantSearchContexts() after the search request is done.
            docIdsToLoad.set(shardIndex, null);
            onFetchFailure(t, fetchSearchRequest, shardIndex, shardTarget, counter);
        }
    });
}
 
Example 27
Project: fastmq   File: LogStorageImplTest.java   View source code 6 votes vote down vote up
@Test
public void asyncRemoveLedger() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    AtomicInteger counter = new AtomicInteger();
    logInfoStorage.asyncRemoveLogInfo("HelloWorldTest1", new CommonCallback<Void, LedgerStorageException>() {
        @Override public void onCompleted(Void data, Version version) {
            counter.incrementAndGet();
            latch.countDown();
        }

        @Override public void onThrowable(LedgerStorageException throwable) {
            throwable.printStackTrace();
            latch.countDown();
        }
    });
    latch.await();
    Assert.assertEquals(1, counter.get());
}
 
Example 28
Project: openjdk-jdk10   File: CompletableFutureTest.java   View source code 6 votes vote down vote up
/**
 * If a whenComplete action throws an exception when triggered by
 * a normal completion, it completes exceptionally
 */
public void testWhenComplete_sourceCompletedNormallyActionFailed() {
    for (boolean createIncomplete : new boolean[] { true, false })
    for (ExecutionMode m : ExecutionMode.values())
    for (Integer v1 : new Integer[] { 1, null })
{
    final AtomicInteger a = new AtomicInteger(0);
    final CFException ex = new CFException();
    final CompletableFuture<Integer> f = new CompletableFuture<>();
    if (!createIncomplete) assertTrue(f.complete(v1));
    final CompletableFuture<Integer> g = m.whenComplete
        (f,
         (Integer result, Throwable t) -> {
            m.checkExecutionMode();
            threadAssertSame(result, v1);
            threadAssertNull(t);
            a.getAndIncrement();
            throw ex;
        });
    if (createIncomplete) assertTrue(f.complete(v1));

    checkCompletedWithWrappedException(g, ex);
    checkCompletedNormally(f, v1);
    assertEquals(1, a.get());
}}
 
Example 29
Project: openjdk-jdk10   File: DecimalFormat.java   View source code 6 votes vote down vote up
/**
 * Formats a number and appends the resulting text to the given string
 * buffer.
 * The number can be of any subclass of {@link java.lang.Number}.
 * <p>
 * This implementation uses the maximum precision permitted.
 * @param number     the number to format
 * @param toAppendTo the <code>StringBuffer</code> to which the formatted
 *                   text is to be appended
 * @param pos        On input: an alignment field, if desired.
 *                   On output: the offsets of the alignment field.
 * @return           the value passed in as <code>toAppendTo</code>
 * @exception        IllegalArgumentException if <code>number</code> is
 *                   null or not an instance of <code>Number</code>.
 * @exception        NullPointerException if <code>toAppendTo</code> or
 *                   <code>pos</code> is null
 * @exception        ArithmeticException if rounding is needed with rounding
 *                   mode being set to RoundingMode.UNNECESSARY
 * @see              java.text.FieldPosition
 */
@Override
public final StringBuffer format(Object number,
                                 StringBuffer toAppendTo,
                                 FieldPosition pos) {
    if (number instanceof Long || number instanceof Integer ||
               number instanceof Short || number instanceof Byte ||
               number instanceof AtomicInteger ||
               number instanceof AtomicLong ||
               (number instanceof BigInteger &&
                ((BigInteger)number).bitLength () < 64)) {
        return format(((Number)number).longValue(), toAppendTo, pos);
    } else if (number instanceof BigDecimal) {
        return format((BigDecimal)number, toAppendTo, pos);
    } else if (number instanceof BigInteger) {
        return format((BigInteger)number, toAppendTo, pos);
    } else if (number instanceof Number) {
        return format(((Number)number).doubleValue(), toAppendTo, pos);
    } else {
        throw new IllegalArgumentException("Cannot format given Object as a Number");
    }
}
 
Example 30
Project: talchain   File: BlockchainValidation.java   View source code 6 votes vote down vote up
public static void checkHeaders(Ethereum ethereum, AtomicInteger fatalErrors) {
    int blockNumber = (int) ethereum.getBlockchain().getBestBlock().getHeader().getNumber();
    byte[] lastParentHash = null;
    testLogger.info("Checking headers from best block: {}", blockNumber);

    try {
        while (blockNumber >= 0) {
            Block currentBlock = ethereum.getBlockchain().getBlockByNumber(blockNumber);
            if (lastParentHash != null) {
                assert FastByteComparisons.equal(currentBlock.getHash(), lastParentHash);
            }
            lastParentHash = currentBlock.getHeader().getParentHash();
            assert lastParentHash != null;
            blockNumber--;
        }

        testLogger.info("Checking headers successful, ended on block: {}", blockNumber + 1);
    } catch (Exception | AssertionError ex) {
        testLogger.error(String.format("Block header validation error on block #%s", blockNumber), ex);
        fatalErrors.incrementAndGet();
    }
}
 
Example 31
Project: greycat   File: TrampolineCallback.java   View source code 6 votes vote down vote up
private static void insert(final Node position, final AtomicInteger counter, final DeferCounter defer, final int max) {
    final int time = counter.incrementAndGet();
    position.travelInTime(time, new Callback<Node>() {
        public void on(Node timedNode) {
            timedNode.set("lat", Type.DOUBLE, time + 10.5);
            timedNode.set("long", Type.DOUBLE, time + 10.5);
            defer.count();
            if (time != max) {
                position.graph().scheduler().dispatch(SchedulerAffinity.SAME_THREAD, new Job() {
                    public void run() {
                        insert(position, counter, defer, max);
                    }
                });
            }
        }
    });
}
 
Example 32
Project: sstore-soft   File: SamplingFilter.java   View source code 6 votes vote down vote up
@Override
protected FilterResult filter(AbstractTraceElement<? extends CatalogType> element) {
    FilterResult result = FilterResult.ALLOW;
    if (element instanceof TransactionTrace) {
        final boolean trace = LOG.isTraceEnabled();
        final String proc_name = element.getCatalogItemName();
        final AtomicInteger proc_counter = this.proc_counters.get(proc_name);
        
        if (proc_counter == null) {
            if (trace) LOG.trace("Procedure " + proc_name + " is not included in whitelist. Skipping...");
            result = FilterResult.SKIP;
        } else {
            int proc_idx = proc_counter.getAndIncrement();
            int proc_rate = this.proc_rates.get(proc_name);
            result = (proc_rate != 0 && proc_idx % proc_rate == 0 ? FilterResult.ALLOW : FilterResult.SKIP);
        }
    }
    return (result);
}
 
Example 33
Project: util4j   File: TestQueues.java   View source code 5 votes vote down vote up
public void testOrder(final TaskQueueExecutor o)
    	 {
    		 final AtomicInteger atomicInteger=new AtomicInteger(0);
    		 for(int i=0;i<1000;i++)
    		 {
    			 final int x=i;
				 o.execute(new Task() {
						@Override
						public void run() {
							int sleep=RandomUtils.nextInt(100);
							if(x%2==0)
							{
								System.err.println("i="+x+",value="+atomicInteger.incrementAndGet()+",sleep="+sleep);
							}else
							{
								System.err.println("i="+x+",value="+atomicInteger.decrementAndGet()+",sleep="+sleep);
							}
//							try {
//								Thread.sleep(sleep);
//							} catch (InterruptedException e) {
//								e.printStackTrace();
//							}
						}
						@Override
						public String name() {
							return "";
						}
					});
    		 }
    	 }
 
Example 34
Project: s-store   File: ConcurrentHashMultiset.java   View source code 5 votes vote down vote up
/**
 * Removes a number of occurrences of the specified element from this multiset. If the multiset
 * contains fewer than this number of occurrences to begin with, all occurrences will be removed.
 *
 * @param element the element whose occurrences should be removed
 * @param occurrences the number of occurrences of the element to remove
 * @return the count of the element before the operation; possibly zero
 * @throws IllegalArgumentException if {@code occurrences} is negative
 */
/*
 * TODO(cpovirk): remove and removeExactly currently accept null inputs only
 * if occurrences == 0. This satisfies both NullPointerTester and
 * CollectionRemoveTester.testRemove_nullAllowed, but it's not clear that it's
 * a good policy, especially because, in order for the test to pass, the
 * parameter must be misleadingly annotated as @Nullable. I suspect that
 * we'll want to remove @Nullable, add an eager checkNotNull, and loosen up
 * testRemove_nullAllowed.
 */
@Override public int remove(@Nullable Object element, int occurrences) {
  if (occurrences == 0) {
    return count(element);
  }
  checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences);

  AtomicInteger existingCounter = Maps.safeGet(countMap, element);
  if (existingCounter == null) {
    return 0;
  }
  while (true) {
    int oldValue = existingCounter.get();
    if (oldValue != 0) {
      int newValue = Math.max(0, oldValue - occurrences);
      if (existingCounter.compareAndSet(oldValue, newValue)) {
        if (newValue == 0) {
          // Just CASed to 0; remove the entry to clean up the map. If the removal fails,
          // another thread has already replaced it with a new counter, which is fine.
          countMap.remove(element, existingCounter);
        }
        return oldValue;
      }
    } else {
      return 0;
    }
  }
}
 
Example 35
Project: flume-release-1.7.0   File: EventQueueBackingStoreFile.java   View source code 5 votes vote down vote up
@Override
protected void decrementFileID(int fileID) {
  AtomicInteger counter = logFileIDReferenceCounts.get(fileID);
  Preconditions.checkState(counter != null, "null counter ");
  int count = counter.decrementAndGet();
  if (count == 0) {
    logFileIDReferenceCounts.remove(fileID);
  }
}
 
Example 36
Project: jetcache   File: LoadingCacheTest.java   View source code 5 votes vote down vote up
public static void loadingCacheTest(AbstractCacheBuilder builder, long waitMillis) throws Exception {
    AtomicInteger count = new AtomicInteger(0);
    builder.loader((key) -> key + "_V" + count.getAndIncrement());
    Cache cache = builder.buildCache();
    loadingCacheTestImpl(cache, waitMillis);
    nullValueTest(cache, waitMillis);
}
 
Example 37
Project: Elasticsearch   File: IndicesStore.java   View source code 5 votes vote down vote up
public ShardActiveResponseHandler(ShardId shardId, ClusterState clusterState, int expectedActiveCopies) {
    this.shardId = shardId;
    this.expectedActiveCopies = expectedActiveCopies;
    this.clusterState = clusterState;
    this.awaitingResponses = new AtomicInteger(expectedActiveCopies);
    this.activeCopies = new AtomicInteger();
}
 
Example 38
Project: short-text-search   File: ConcurrentLRUCache.java   View source code 5 votes vote down vote up
public String getKeyAndHitCount(){
    StringBuilder status = new StringBuilder();
    AtomicInteger i = new AtomicInteger();

    cache.entrySet().stream().sorted((a,b)->b.getValue().getCount()-a.getValue().getCount()).forEach(entry->status.append(i.incrementAndGet()).append("\t").append(entry.getKey()).append("\t").append(entry.getValue().getCount()).append("\n"));

    return status.toString();
}
 
Example 39
Project: EpiStats   File: FilterOperation.java   View source code 5 votes vote down vote up
@Override
public void accept(RankingList list, ObservableTask task) throws OperationException {
	task.setTitle("Filtrage des catégories ..");
	task.setProgress(0);

	AtomicInteger p = new AtomicInteger();

	this.expression.removeAllArguments();
	this.expression.addArguments(list.getArguments(this.expression.getExpressionString(), p));

	if (!this.expression.checkSyntax())
		throw new OperationException(this.expression.getErrorMessage());

	List<Ranking> l = list.list(this.category);
	if (l.isEmpty())
		return;

	int total = list.collection.size;
	for (int i = 0; i < total; i++) {
		if (task.isCancelled())
			return;

		task.setMessage("Joueur: " + list.collection.names.get(i));
		p.set(i);

		if (this.expression.calculate() == 0d) {
			for (Ranking r : l)
				r.remove(i);
		}
		task.setProgress(i / (double) total);
	}
}
 
Example 40
Project: kafka-connect-fs   File: AbstractPolicy.java   View source code 5 votes vote down vote up
public AbstractPolicy(FsSourceTaskConfig conf) throws IOException {
    this.fileSystems = new ArrayList<>();
    this.conf = conf;
    this.executions = new AtomicInteger(0);
    this.recursive = conf.getBoolean(FsSourceTaskConfig.POLICY_RECURSIVE);
    this.fileRegexp = Pattern.compile(conf.getString(FsSourceTaskConfig.POLICY_REGEXP));
    this.interrupted = false;

    Map<String, Object> customConfigs = customConfigs();
    logAll(customConfigs);
    configFs(customConfigs);
    configPolicy(customConfigs);
}