java.util.concurrent.atomic.AtomicInteger Java Examples

The following examples show how to use java.util.concurrent.atomic.AtomicInteger. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReactorHeadTransformerTest.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Test
public void testExceptionInSubscriberTerminatesSubscription() {
    AtomicInteger errorCounter = new AtomicInteger();
    Disposable subscription = combined.subscribe(
            next -> {
                if (next.equals("T3")) {
                    throw new RuntimeException("simulated error");
                }
            },
            e -> errorCounter.incrementAndGet()
    );

    // Wait until hot observable emits error
    while (!terminateFlag.get()) {
    }

    await().timeout(5, TimeUnit.SECONDS).until(subscription::isDisposed);
    assertThat(errorCounter.get()).isEqualTo(1);
}
 
Example #2
Source File: SimpleRequestController.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * 1) check the regions is allowed. 2) check the concurrent tasks for
 * regions. 3) check the total concurrent tasks. 4) check the concurrent
 * tasks for server.
 *
 * @param loc the destination of data
 * @param heapSizeOfRow the data size
 * @return either Include {@link RequestController.ReturnCode} or skip
 *         {@link RequestController.ReturnCode}
 */
@Override
public ReturnCode canTakeOperation(HRegionLocation loc, long heapSizeOfRow) {
  RegionInfo regionInfo = loc.getRegion();
  if (regionsIncluded.contains(regionInfo)) {
    // We already know what to do with this region.
    return ReturnCode.INCLUDE;
  }
  AtomicInteger regionCnt = taskCounterPerRegion.get(loc.getRegion().getRegionName());
  if (regionCnt != null && regionCnt.get() >= maxConcurrentTasksPerRegion) {
    // Too many tasks on this region already.
    return ReturnCode.SKIP;
  }
  int newServers = serversIncluded.size()
          + (serversIncluded.contains(loc.getServerName()) ? 0 : 1);
  if ((newServers + tasksInProgress.get()) > maxTotalConcurrentTasks) {
    // Too many tasks.
    return ReturnCode.SKIP;
  }
  AtomicInteger serverCnt = taskCounterPerServer.get(loc.getServerName());
  if (serverCnt != null && serverCnt.get() >= maxConcurrentTasksPerServer) {
    // Too many tasks for this individual server
    return ReturnCode.SKIP;
  }
  return ReturnCode.INCLUDE;
}
 
Example #3
Source File: CacheBlockOnReadAbstractTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Params(baseline = 9, atomicityMode = TRANSACTIONAL, cacheMode = REPLICATED)
@Test
public void testStopBaselineTransactionalReplicated() throws Exception {
    AtomicInteger cntDownCntr = new AtomicInteger(0);

    doTest(
        asMessagePredicate(discoEvt -> discoEvt.type() == EventType.EVT_NODE_LEFT),
        () -> {
            IgniteEx node = baseline.get(baseline.size() - cntDownCntr.get() - 1);

            TestRecordingCommunicationSpi.spi(node).stopBlock();

            cntDownCntr.incrementAndGet();

            for (int i = 0; i < cntDownCntr.get(); i++)
                cntFinishedReadOperations.countDown(); // This node and previously stopped nodes as well.

            stopGrid(node.name());
        }
    );
}
 
Example #4
Source File: TestSuiteTestBase.java    From vertx-unit with Apache License 2.0 6 votes vote down vote up
@Test
public void runTest() {
  AtomicInteger count = new AtomicInteger();
  AtomicBoolean sameContext = new AtomicBoolean();
  TestSuite suite = TestSuite.create("my_suite").
      test("my_test", context -> {
        sameContext.set(checkTest(context));
        count.compareAndSet(0, 1);
      });
  TestReporter reporter = new TestReporter();
  run(suite, reporter);
  reporter.await();
  assertTrue(sameContext.get());
  assertEquals(1, count.get());
  assertEquals(0, reporter.exceptions.size());
  assertEquals(1, reporter.results.size());
  TestResult result = reporter.results.get(0);
  assertEquals("my_test", result.name());
  assertTrue(result.succeeded());
  assertFalse(result.failed());
  assertNull(result.failure());
}
 
Example #5
Source File: TimedHandler.java    From micrometer with Apache License 2.0 6 votes vote down vote up
public TimedHandler(MeterRegistry registry, Iterable<Tag> tags, HttpServletRequestTagsProvider tagsProvider) {
    this.registry = registry;
    this.tags = tags;
    this.tagsProvider = tagsProvider;

    this.openRequests = LongTaskTimer.builder("jetty.server.dispatches.open")
            .description("Jetty dispatches that are currently in progress")
            .tags(tags)
            .register(registry);

    this.asyncDispatches = Counter.builder("jetty.server.async.dispatches")
            .description("Asynchronous dispatches")
            .tags(tags)
            .register(registry);

    this.asyncExpires = Counter.builder("jetty.server.async.expires")
            .description("Asynchronous operations that timed out before completing")
            .tags(tags)
            .register(registry);

    Gauge.builder("jetty.server.async.waits", asyncWaits, AtomicInteger::doubleValue)
            .description("Pending asynchronous wait operations")
            .baseUnit(BaseUnits.OPERATIONS)
            .tags(tags)
            .register(registry);
}
 
Example #6
Source File: PluginLoaderTest.java    From gadtry with Apache License 2.0 6 votes vote down vote up
@Test
public void onlyAccessSpiPackagesTest()
        throws ClassNotFoundException, IOException
{
    Module module = pluginLoader.getModules().get(0);
    ClassLoader moduleClassLoader = module.getModuleClassLoader();

    try {
        moduleClassLoader.loadClass(PluginLoader.class.getName());
        Assert.fail();
    }
    catch (ClassNotFoundException ignored) {
    }

    moduleClassLoader.loadClass(AopFactory.class.getName());
    moduleClassLoader.loadClass(AtomicInteger.class.getName());
    Assert.assertTrue(Driver.class.isAssignableFrom(moduleClassLoader.loadClass("org.h2.Driver")));

    Assert.assertNull(moduleClassLoader.getResource("version1"));

    Assert.assertNotNull(moduleClassLoader.getResources("version2").nextElement());
    Assert.assertNotNull(moduleClassLoader.getResource("version2"));

    Assert.assertNotNull(this.getClass().getClassLoader().getResource("version1"));
}
 
Example #7
Source File: DecimalFormat.java    From dragonwell8_jdk with GNU General Public License v2.0 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 #8
Source File: MaintainedPeersTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void remove_existingPeer() {
  // Initial add
  final Peer peer = createPeer();
  assertThat(maintainedPeers.add(peer)).isTrue();
  assertThat(maintainedPeers.size()).isEqualTo(1);
  assertThat(maintainedPeers.contains(peer)).isTrue();

  // Test remove
  final AtomicInteger callbackCount = new AtomicInteger(0);
  maintainedPeers.subscribeRemove(
      (addedPeer, wasRemoved) -> {
        callbackCount.incrementAndGet();
        assertThat(addedPeer).isEqualTo(peer);
        assertThat(wasRemoved).isTrue();
      });
  assertThat(maintainedPeers.remove(peer)).isTrue();
  assertThat(callbackCount).hasValue(1);
  assertThat(maintainedPeers.size()).isEqualTo(0);
  assertThat(maintainedPeers.contains(peer)).isFalse();
}
 
Example #9
Source File: DomElement2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Test case for Bug #1905.
 *
 * @throws Exception if the test fails
 */
@Test
public void getChildElements() throws Exception {
    final String xml = "<events>\n"
            + "  <something/>\n"
            + "</events>";
    getMockWebConnection().setDefaultResponse(xml, MimeType.TEXT_XML);
    getWebClient().setWebConnection(getMockWebConnection());
    final XmlPage page = getWebClient().getPage(URL_FIRST);
    final DomElement root = page.getDocumentElement();
    final AtomicInteger count = new AtomicInteger(0);
    root.getChildElements().forEach(e -> count.incrementAndGet());
    assertEquals(1, count.get());

    count.set(0);
    root.getChildren().forEach(e -> count.incrementAndGet());
    assertEquals(3, count.get());
}
 
Example #10
Source File: ShadowRootTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void attachEvent_stateTreeCanFound() {
    ShadowRoot bodyShadow = new UI().getElement().attachShadow();
    Element child = ElementFactory.createDiv();

    AtomicInteger attached = new AtomicInteger();

    child.addAttachListener(event -> {
        Assert.assertNotNull(event.getSource().getNode().getOwner());
        Assert.assertNotEquals(NullOwner.get(),
                event.getSource().getNode().getOwner());
    });
    child.addAttachListener(event -> attached.incrementAndGet());

    bodyShadow.appendChild(child);
    Assert.assertEquals(1, attached.get());
}
 
Example #11
Source File: DelayOverflow.java    From jdk8u-dev-jdk with GNU General Public License v2.0 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 #12
Source File: HeaderExchangeHandlerTest.java    From dubbox with Apache License 2.0 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 #13
Source File: ForecastingFilter.java    From kieker with Apache License 2.0 6 votes vote down vote up
private void setFieldsByConfiguration(final Configuration config, final boolean update) {
	if (!update || this.isPropertyUpdateable(CONFIG_PROPERTY_NAME_DELTA_TIME)) {
		this.deltat = new AtomicLong(config.getLongProperty(CONFIG_PROPERTY_NAME_DELTA_TIME));
	}

	if (!update || this.isPropertyUpdateable(CONFIG_PROPERTY_NAME_DELTA_UNIT)) {
		this.tunit = TimeUnit.valueOf(config.getStringProperty(CONFIG_PROPERTY_NAME_DELTA_UNIT));
	}

	if (!update || this.isPropertyUpdateable(CONFIG_PROPERTY_NAME_FC_METHOD)) {
		this.forecastMethod.set(ForecastMethod.valueOf(config.getStringProperty(CONFIG_PROPERTY_NAME_FC_METHOD)));
	}

	if (!update || this.isPropertyUpdateable(CONFIG_PROPERTY_NAME_TS_WINDOW_CAPACITY)) {
		this.timeSeriesWindowCapacity = new AtomicInteger(config.getIntProperty(CONFIG_PROPERTY_NAME_TS_WINDOW_CAPACITY));
	}

	if (!update || this.isPropertyUpdateable(CONFIG_PROPERTY_NAME_FC_CONFIDENCE)) {
		this.forecastConfidence = new AtomicInteger(config.getIntProperty(CONFIG_PROPERTY_NAME_FC_CONFIDENCE));
	}
}
 
Example #14
Source File: HDBConnection.java    From herddb with Apache License 2.0 6 votes vote down vote up
public CompletableFuture<List<DMLResult>> executeUpdatesAsync(
        String tableSpace, String query, long tx, boolean returnValues,
        boolean usePreparedStatement, List<List<Object>> batch
) {
    if (batch.isEmpty()) {
        return CompletableFuture.completedFuture(Collections.emptyList());
    }
    if (discoverTablespaceFromSql) {
        tableSpace = discoverTablespace(tableSpace, query);
    }
    if (closed) {
        return FutureUtils.exception(new HDBException("client is closed"));
    }
    CompletableFuture<List<DMLResult>> res = new CompletableFuture<>();

    AtomicInteger count = new AtomicInteger(0);
    executeStatementsAsyncInternal(tableSpace, res, query, tx, returnValues, usePreparedStatement, batch, count);
    return res;
}
 
Example #15
Source File: DelayLocalExecutionInjection.java    From incubator-ratis with Apache License 2.0 6 votes vote down vote up
@Override
public boolean execute(Object localId, Object remoteId, Object... args) {
  if (localId == null) {
    return false;
  }
  final String localIdStr = localId.toString();
  final AtomicInteger d = delays.get(localIdStr);
  if (d == null) {
    return false;
  }
  LOG.info("{} delay {} ms, args={}", localIdStr, d.get(),
      Arrays.toString(args));
  try {
    RaftTestUtil.delay(d::get);
  } catch (InterruptedException e) {
    LOG.debug("Interrupted while delaying " + localIdStr);
  }
  return true;
}
 
Example #16
Source File: WeightedRoundRobinMultiplexer.java    From hadoop with Apache License 2.0 6 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 #17
Source File: BlockingStreamingToStreamingServiceTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Test
public void echoServiceUsingPayloadWriterWithSerializerWithTrailers() throws Exception {
    echoService((ctx, request, response) -> {
        response.setHeader(TRAILER, X_TOTAL_LENGTH);
        try (HttpPayloadWriter<String> pw = response.sendMetaData(textSerializer())) {
            AtomicInteger totalLength = new AtomicInteger();
            request.payloadBody(textDeserializer()).forEach(chunk -> {
                try {
                    totalLength.addAndGet(chunk.length());
                    pw.write(chunk);
                } catch (IOException e) {
                    throwException(e);
                }
            });
            pw.setTrailer(X_TOTAL_LENGTH, totalLength.toString());
        }
    });
}
 
Example #18
Source File: KotlinRepl.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public KotlinRepl(KotlinReplProperties properties) {
  compiler = ReplBuilding.buildCompiler(properties);
  evaluator = ReplBuilding.buildEvaluator(properties);
  ReentrantReadWriteLock stateLock = new ReentrantReadWriteLock();
  state = new AggregatedReplStageState(
      compiler.createState(stateLock),
      evaluator.createState(stateLock),
      stateLock);
  counter = new AtomicInteger(0);

  writer = new ClassWriter(properties.getOutputDir());
  maxResult = properties.getMaxResult();
  shortenTypes = properties.getShortenTypes();

  ctx = new KotlinContext();
  properties.getReceiver().kc = ctx;

  contextUpdater = new ContextUpdater(
      state, ctx.vars, ctx.functions);

  for (String line: properties.getCodeOnLoad()) {
    eval(line);
  }
}
 
Example #19
Source File: TestRingBuffer.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testIterateForwards() {
    final RingBuffer<Integer> ringBuffer = new RingBuffer<>(10);

    final int[] values = new int[]{3, 5, 20, 7};
    for (final int v : values) {
        ringBuffer.add(v);
    }

    final AtomicInteger countHolder = new AtomicInteger(0);
    ringBuffer.forEach(new ForEachEvaluator<Integer>() {
        int counter = 0;

        @Override
        public boolean evaluate(final Integer value) {
            final int expected = values[counter++];
            countHolder.incrementAndGet();
            assertEquals(expected, value.intValue());
            return true;
        }

    }, IterationDirection.FORWARD);

    assertEquals(4, countHolder.get());
}
 
Example #20
Source File: VerifyClassLinkage.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void verify(String clazz, byte[] data, Map<String,Boolean> loadable, ClassLoader loader, AtomicInteger maxWarn)
        throws IOException, BuildException {
    //log("Verifying linkage of " + clazz.replace('/', '.'), Project.MSG_DEBUG);
    Set<String> dependencies = dependencies(data);
    //System.err.println(clazz + " -> " + dependencies);
    for (String clazz2 : dependencies) {
        Boolean exists = loadable.get(clazz2);
        if (exists == null) {
            exists = loader.getResource(clazz2.replace('.', '/') + ".class") != null;
            loadable.put(clazz2, exists);
        }
        if (!exists) {
            String message = clazz + " cannot access " + clazz2;
            if (failOnError) {
                throw new BuildException(message, getLocation());
            } else if (maxWarn.getAndDecrement() > 0) {
                log("Warning: " + message, Project.MSG_WARN);
            } else {
                log("(additional warnings not reported)", Project.MSG_WARN);
                return;
            }
        } else {
            //log("Working reference to " + clazz2, Project.MSG_DEBUG);
        }
    }
}
 
Example #21
Source File: CodecsTest.java    From vertx-kafka-client with Apache License 2.0 5 votes vote down vote up
private <K, V> void testCodec(TestContext ctx,
                              String prefix,
                              Function<Properties,KafkaWriteStream<K, V>> producerFactory,
                              Function<Properties, KafkaReadStream<K, V>> consumerFactory,
                              Function<Integer, K> keyConv,
                              Function<Integer, V> valueConv) throws Exception {
  Properties producerConfig = kafkaCluster.useTo().getProducerProperties(prefix+"the_producer");
  KafkaWriteStream<K, V> writeStream = producerFactory.apply(producerConfig);
  producer = writeStream;
  writeStream.exceptionHandler(ctx::fail);
  int numMessages = 100000;
  ConcurrentLinkedDeque<K> keys = new ConcurrentLinkedDeque<K>();
  ConcurrentLinkedDeque<V> values = new ConcurrentLinkedDeque<V>();
  for (int i = 0;i < numMessages;i++) {
    K key = keyConv.apply(i);
    V value = valueConv.apply(i);
    keys.add(key);
    values.add(value);
    writeStream.write(new ProducerRecord<>(prefix + topic, 0, key, value));
  }
  Async done = ctx.async();
  Properties consumerConfig = kafkaCluster.useTo().getConsumerProperties(prefix+"the_consumer", prefix+"the_consumer", OffsetResetStrategy.EARLIEST);
  KafkaReadStream<K, V> readStream = consumerFactory.apply(consumerConfig);
  consumer = readStream;
  AtomicInteger count = new AtomicInteger(numMessages);
  readStream.exceptionHandler(ctx::fail);
  readStream.handler(rec -> {
    ctx.assertEquals(keys.pop(), rec.key());
    ctx.assertEquals(values.pop(), rec.value());
    if (count.decrementAndGet() == 0) {
      done.complete();
    }
  });
  readStream.subscribe(Collections.singleton(prefix + topic));
}
 
Example #22
Source File: ZkUtils.java    From samza with Apache License 2.0 5 votes vote down vote up
public ZkUtils(ZkKeyBuilder zkKeyBuilder, ZkClient zkClient, int connectionTimeoutMs, int sessionTimeOutMs, MetricsRegistry metricsRegistry) {
  this.keyBuilder = zkKeyBuilder;
  this.connectionTimeoutMs = connectionTimeoutMs;
  this.zkClient = zkClient;
  this.metrics = new ZkUtilsMetrics(metricsRegistry);
  this.currentGeneration = new AtomicInteger(0);
  this.sessionTimeoutMs = sessionTimeOutMs;
}
 
Example #23
Source File: SetEntryOperationsTest.java    From Chronicle-Map with Apache License 2.0 5 votes vote down vote up
@Test
public void setEntryOperationsTest() {
    AtomicInteger insertCounter = new AtomicInteger();
    AtomicInteger remoteCounter = new AtomicInteger();
    try (ChronicleSet<String> fruits = ChronicleSet
            .of(String.class)
            .entries(3)
            .averageKey("apple")
            .entryOperations(new SetEntryOperations<String, Void>() {
                @Override
                public Void remove(@NotNull SetEntry<String> entry) {
                    remoteCounter.addAndGet(1);
                    entry.doRemove();
                    return null;
                }

                @Override
                public Void insert(@NotNull SetAbsentEntry<String> absentEntry) {
                    insertCounter.addAndGet(1);
                    absentEntry.doInsert();
                    return null;
                }
            })
            .create()) {
        fruits.add("apple");
        fruits.add("banana");
        fruits.remove("banana");
        fruits.remove("grapes");

        Assert.assertEquals(2, insertCounter.get());
        Assert.assertEquals(1, remoteCounter.get());
    }
}
 
Example #24
Source File: RequestDetails.java    From async-gamequery-lib with MIT License 5 votes vote down vote up
/**
 * Copy Constructor
 *
 * @param requestDetails An {@link RequestDetails} that will be used as reference for the copy
 */
public RequestDetails(RequestDetails<Req, Res> requestDetails) {
    this.request = requestDetails.getRequest();
    this.clientPromise = requestDetails.getClientPromise();
    this.status = requestDetails.getStatus();
    this.priority = requestDetails.getPriority();
    this.retries = new AtomicInteger(requestDetails.getRetries());
    this.expectedResponseClass = requestDetails.getExpectedResponseClass();
}
 
Example #25
Source File: LoggingRandomDelaySubscriber.java    From demo-java-x with MIT License 5 votes vote down vote up
@Override
public void onSubscribe(Subscription subscription) {
	log("Subscribed...");
	this.subscription = subscription;
	this.buffer = new AtomicInteger();
	requestItems();
}
 
Example #26
Source File: QoSBucket.java    From hasor with Apache License 2.0 5 votes vote down vote up
public QoSBucket(int rate, int peak, int timeWindow) {
    this.rate = rate;
    this.peak = peak;
    this.timeWindow = timeWindow;
    double initialToken = rate * timeWindow / 1000d;
    //初始的token为零不合理, 改为1。
    this.tokens = initialToken >= 1 ? new AtomicInteger((int) initialToken) : new AtomicInteger(1);
    //增加此保存值,是为了double转int时候的不精确;如果不累及这个误差,累计的结果会非常大(修正参数)
    this.leftDouble = initialToken - Math.floor(initialToken);
    this.lastRefreshTime = System.currentTimeMillis();
}
 
Example #27
Source File: RegistryAdminService.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * construct an instance of the service, using the
 * specified binding source to bond to ZK
 * @param name service name
 * @param bindingSource provider of ZK binding information
 */
public RegistryAdminService(String name,
    RegistryBindingSource bindingSource) {
  super(name, bindingSource);
  executor = Executors.newCachedThreadPool(
      new ThreadFactory() {
        private AtomicInteger counter = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
          return new Thread(r,
              "RegistryAdminService " + counter.getAndIncrement());
        }
      });
}
 
Example #28
Source File: file_s.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
private AggregateOnTheFlyTask(AtomicExchange result, Exchange original, AtomicInteger total,
                              CompletionService<Exchange> completion, AtomicBoolean running,
                              CountDownLatch aggregationOnTheFlyDone, AtomicBoolean allTasksSubmitted,
                              AtomicException executionException) {
    this.result = result;
    this.original = original;
    this.total = total;
    this.completion = completion;
    this.running = running;
    this.aggregationOnTheFlyDone = aggregationOnTheFlyDone;
    this.allTasksSubmitted = allTasksSubmitted;
    this.executionException = executionException;
}
 
Example #29
Source File: WorkerProcessPoolFactory.java    From buck with Apache License 2.0 5 votes vote down vote up
private WorkerProcessPool createWorkerProcessPool(
    ExecutionContext context,
    WorkerProcessParams paramsToUse,
    ConcurrentMap<String, WorkerProcessPool> processPoolMap,
    String key,
    HashCode workerHash) {
  ProcessExecutorParams processParams =
      ProcessExecutorParams.builder()
          .setCommand(getCommand(context.getPlatform(), paramsToUse))
          .setEnvironment(getEnvironmentForProcess(context, paramsToUse))
          .setDirectory(filesystem.getRootPath().getPath())
          .build();

  Path workerTmpDir = paramsToUse.getTempDir();
  AtomicInteger workerNumber = new AtomicInteger(0);

  WorkerProcessPool newPool =
      new WorkerProcessPool(
          paramsToUse.getMaxWorkers(),
          workerHash,
          () -> {
            Path tmpDir = workerTmpDir.resolve(Integer.toString(workerNumber.getAndIncrement()));
            filesystem.mkdirs(tmpDir);
            WorkerProcess process = createWorkerProcess(processParams, context, tmpDir);
            process.ensureLaunchAndHandshake();
            return process;
          });
  WorkerProcessPool previousPool = processPoolMap.putIfAbsent(key, newPool);
  // If putIfAbsent does not return null, then that means another thread beat this thread
  // into putting an WorkerProcessPool in the map for this key. If that's the case, then we
  // should ignore newPool and return the existing one.
  return previousPool == null ? newPool : previousPool;
}
 
Example #30
Source File: MultiFromResourceTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void simpleSynchronousTest() {
    MultiAssertSubscriber<Integer> subscriber = MultiAssertSubscriber.create(10);
    AtomicInteger cleanup = new AtomicInteger();
    Multi.createFrom().resource(() -> 1, r -> Multi.createFrom().range(r, 11))
            .withFinalizer(cleanup::set)
            .subscribe(subscriber);
    subscriber
            .assertReceived(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
            .assertCompletedSuccessfully()
            .assertHasNotFailed();
    assertThat(cleanup.get()).isEqualTo(1);
}