Java Code Examples for java.util.concurrent.atomic.AtomicLong.get()

The following are Jave code examples for showing how to use get() of the java.util.concurrent.atomic.AtomicLong class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: boohee_v5.6   File: OperatorGroupBy.java   View Source Code Vote up 6 votes
private void emitItem(GroupState<K, T> groupState, Object item) {
    Queue<Object> q = groupState.buffer;
    AtomicLong keyRequested = groupState.requested;
    REQUESTED.decrementAndGet(this);
    if (keyRequested == null || keyRequested.get() <= 0 || !(q == null || q.isEmpty())) {
        q.add(item);
        BUFFERED_COUNT.incrementAndGet(this);
        if (groupState.count.getAndIncrement() == 0) {
            pollQueue(groupState);
        }
    } else {
        nl.accept(groupState.getObserver(), item);
        if (keyRequested.get() != Long.MAX_VALUE) {
            keyRequested.decrementAndGet();
        }
    }
    requestMoreIfNecessary();
}
 
Example 2
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: StoreStatsService.java   View Source Code Vote up 5 votes
public long getPutMessageSizeTotal() {
    long rs = 0;
    for (AtomicLong data : putMessageTopicSizeTotal.values()) {
        rs += data.get();
    }
    return rs;
}
 
Example 3
Project: rmq4note   File: StoreStatsService.java   View Source Code Vote up 5 votes
public long getPutMessageTimesTotal() {
    long rs = 0;
    for (AtomicLong data : putMessageTopicTimesTotal.values()) {
        rs += data.get();
    }
    return rs;
}
 
Example 4
Project: boohee_v5.6   File: OperatorOnBackpressureDrop.java   View Source Code Vote up 5 votes
public Subscriber<? super T> call(final Subscriber<? super T> child) {
    final AtomicLong requested = new AtomicLong();
    child.setProducer(new Producer() {
        public void request(long n) {
            BackpressureUtils.getAndAddRequest(requested, n);
        }
    });
    return new Subscriber<T>(child) {
        public void onStart() {
            request(Long.MAX_VALUE);
        }

        public void onCompleted() {
            child.onCompleted();
        }

        public void onError(Throwable e) {
            child.onError(e);
        }

        public void onNext(T t) {
            if (requested.get() > 0) {
                child.onNext(t);
                requested.decrementAndGet();
            } else if (OperatorOnBackpressureDrop.this.onDrop != null) {
                OperatorOnBackpressureDrop.this.onDrop.call(t);
            }
        }
    };
}
 
Example 5
Project: reactive-grpc   File: BackpressureIntegrationTest.java   View Source Code Vote up 5 votes
private static void updateNumberOfWaits(AtomicLong start, AtomicLong maxTime) {
    Long now = System.currentTimeMillis();
    Long startValue = start.get();
    if (startValue != 0 && now - startValue > 1000) {
        maxTime.incrementAndGet();
    }
    start.set(now);
}
 
Example 6
Project: openjdk-jdk10   File: Test7009231.java   View Source Code Vote up 5 votes
protected void clearBit(AtomicLong atomic, long lMask) {
    long lWord;
    do {
        lWord = atomic.get();
    } while (!atomic.compareAndSet(lWord, lWord & ~lMask));

    if ((atomic.get() & lMask) != 0L) {
        throw new InternalError();
    }
}
 
Example 7
Project: cas-5.1.0   File: HazelcastTicketRegistry.java   View Source Code Vote up 5 votes
@Override
public long deleteAll() {
    final Collection<TicketDefinition> metadata = this.ticketCatalog.findAll();
    final AtomicLong count = new AtomicLong();
    metadata.forEach(r -> {
        final IMap<String, Ticket> instance = getTicketMapInstanceByMetadata(r);
        if (instance != null) {
            count.addAndGet(instance.size());
            instance.evictAll();
            instance.clear();
        }
    });
    return count.get();
}
 
Example 8
Project: openjdk-jdk10   File: Test7009231.java   View Source Code Vote up 5 votes
protected void setBit(AtomicLong atomic, long lMask) {
    long lWord;
    do {
        lWord = atomic.get();
    } while (!atomic.compareAndSet(lWord, lWord | lMask));

    if ((atomic.get() & lMask) == 0L) {
        throw new InternalError();
    }
}
 
Example 9
Project: reading-and-annotate-rocketmq-3.4.6   File: StoreStatsService.java   View Source Code Vote up 5 votes
public long getPutMessageSizeTotal() {
    long rs = 0;
    for (AtomicLong data : putMessageTopicSizeTotal.values()) {
        rs += data.get();
    }
    return rs;
}
 
Example 10
Project: RxJava3-preview   File: QueueDrainHelper.java   View Source Code Vote up 5 votes
/**
 * Accumulates requests (not validated) and handles the completed mode draining of the queue based on the requests.
 *
 * <p>
 * Post-completion backpressure handles the case when a source produces values based on
 * requests when it is active but more values are available even after its completion.
 * In this case, the onComplete() can't just emit the contents of the queue but has to
 * coordinate with the requested amounts. This requires two distinct modes: active and
 * completed. In active mode, requests flow through and the queue is not accessed but
 * in completed mode, requests no-longer reach the upstream but help in draining the queue.
 *
 * @param <T> the value type emitted
 * @param n the request amount, positive (not validated)
 * @param actual the target Subscriber to send events to
 * @param queue the queue to drain if in the post-complete state
 * @param state holds the request amount and the post-completed flag
 * @param isCancelled a supplier that returns true if the drain has been cancelled
 * @return true if the state indicates a completion state.
 */
public static <T> boolean postCompleteRequest(long n,
                                              Subscriber<? super T> actual,
                                              Queue<T> queue,
                                              AtomicLong state,
                                              BooleanSupplier isCancelled) {
    for (; ; ) {
        long r = state.get();

        // extract the current request amount
        long r0 = r & REQUESTED_MASK;

        // preserve COMPLETED_MASK and calculate new requested amount
        long u = (r & COMPLETED_MASK) | BackpressureHelper.addCap(r0, n);

        if (state.compareAndSet(r, u)) {
            // (complete, 0) -> (complete, n) transition then replay
            if (r == COMPLETED_MASK) {

                postCompleteDrain(n | COMPLETED_MASK, actual, queue, state, isCancelled);

                return true;
            }
            // (active, r) -> (active, r + n) transition then continue with requesting from upstream
            return false;
        }
    }

}
 
Example 11
Project: monarch   File: IndexManager.java   View Source Code Vote up 5 votes
/**
 * 
 * @param value
 * @param newValue
 */
private static boolean setNewLargestValue(AtomicLong value, long newValue) {
  boolean done = false;
  while (!done) {
    long oldValue = value.get();
    if (oldValue < newValue) {
      return value.compareAndSet(oldValue, newValue);
    } else {
      done = true;
    }
  }
  return false;
}
 
Example 12
Project: rmq4note   File: Consumer.java   View Source Code Vote up 5 votes
public static void compareAndSetMax(final AtomicLong target, final long value) {
    long prev = target.get();
    while (value > prev) {
        boolean updated = target.compareAndSet(prev, value);
        if (updated)
            break;

        prev = target.get();
    }
}
 
Example 13
Project: reading-and-annotate-rocketmq-3.4.6   File: PullAPIWrapper.java   View Source Code Vote up 5 votes
public long recalculatePullFromWhichNode(final MessageQueue mq) {
    if (this.isConnectBrokerByUser()) {
        return this.defaultBrokerId;
    }

    AtomicLong suggest = this.pullFromWhichNodeTable.get(mq);
    if (suggest != null) {
        return suggest.get();
    }

    return MixAll.MASTER_ID;
}
 
Example 14
Project: rmq4note   File: MixAll.java   View Source Code Vote up 5 votes
public static boolean compareAndIncreaseOnly(final AtomicLong target, final long value) {
    long prev = target.get();
    while (value > prev) {
        boolean updated = target.compareAndSet(prev, value);
        if (updated)
            return true;

        prev = target.get();
    }

    return false;
}
 
Example 15
Project: azeroth   File: ProducerStat.java   View Source Code Vote up 5 votes
public ProducerStat(String topic, String group, AtomicLong successNums, AtomicLong errorNums,
                    AtomicLong latestSuccessNums, AtomicLong latestErrorNums) {
    super();
    this.topic = topic;
    this.group = group;
    this.successNums = successNums.get();
    this.errorNums = errorNums.get();
    this.latestSuccessNums = latestSuccessNums.get();
    this.latestErrorNums = latestErrorNums.get();
    this.updateTime = System.currentTimeMillis();
}
 
Example 16
Project: OpenJSharp   File: ForkJoinPool.java   View Source Code Vote up 4 votes
/**
 * Returns a string identifying this pool, as well as its state,
 * including indications of run state, parallelism level, and
 * worker and task counts.
 *
 * @return a string identifying this pool, as well as its state
 */
public String toString() {
    // Use a single pass through workQueues to collect counts
    long qt = 0L, qs = 0L; int rc = 0;
    AtomicLong sc = stealCounter;
    long st = (sc == null) ? 0L : sc.get();
    long c = ctl;
    WorkQueue[] ws; WorkQueue w;
    if ((ws = workQueues) != null) {
        for (int i = 0; i < ws.length; ++i) {
            if ((w = ws[i]) != null) {
                int size = w.queueSize();
                if ((i & 1) == 0)
                    qs += size;
                else {
                    qt += size;
                    st += w.nsteals;
                    if (w.isApparentlyUnblocked())
                        ++rc;
                }
            }
        }
    }
    int pc = (config & SMASK);
    int tc = pc + (short)(c >>> TC_SHIFT);
    int ac = pc + (int)(c >> AC_SHIFT);
    if (ac < 0) // ignore transient negative
        ac = 0;
    int rs = runState;
    String level = ((rs & TERMINATED) != 0 ? "Terminated" :
                    (rs & STOP)       != 0 ? "Terminating" :
                    (rs & SHUTDOWN)   != 0 ? "Shutting down" :
                    "Running");
    return super.toString() +
        "[" + level +
        ", parallelism = " + pc +
        ", size = " + tc +
        ", active = " + ac +
        ", running = " + rc +
        ", steals = " + st +
        ", tasks = " + qt +
        ", submissions = " + qs +
        "]";
}
 
Example 17
Project: reading-and-annotate-rocketmq-3.4.6   File: SimpleConsumerProducerTest.java   View Source Code Vote up 4 votes
@Test
public void producerConsumerTest() throws MQClientException, InterruptedException {
    System.setProperty("rocketmq.namesrv.domain", "jmenv.tbsite.alipay.net");

    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("S_fundmng_demo_producer");
    DefaultMQProducer producer = new DefaultMQProducer("P_fundmng_demo_producer");

    consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
    consumer.subscribe(TOPIC_TEST, null);

    final AtomicLong lastReceivedMills = new AtomicLong(System.currentTimeMillis());

    final AtomicLong consumeTimes = new AtomicLong(0);

    consumer.registerMessageListener(new MessageListenerConcurrently() {
        public ConsumeConcurrentlyStatus consumeMessage(final List<MessageExt> msgs,
                                                        final ConsumeConcurrentlyContext context) {
            System.out.println("Received" + consumeTimes.incrementAndGet() + "messages !");

            lastReceivedMills.set(System.currentTimeMillis());

            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });

    consumer.start();
    producer.start();

    for (int i = 0; i < 100; i++) {
        try {
            Message msg = new Message(TOPIC_TEST, ("Hello RocketMQ " + i).getBytes());
            SendResult sendResult = producer.send(msg);
            System.out.println(sendResult);
        } catch (Exception e) {
            TimeUnit.SECONDS.sleep(1);
        }
    }

    // wait no messages
    while ((System.currentTimeMillis() - lastReceivedMills.get()) < 5000) {
        TimeUnit.MILLISECONDS.sleep(200);
    }

    consumer.shutdown();
    producer.shutdown();
}
 
Example 18
Project: RxJava3-preview   File: QueueDrainHelper.java   View Source Code Vote up 4 votes
/**
     * Drains the queue based on the outstanding requests in post-completed mode (only!).
     *
     * @param n the current request amount
     * @param actual the target Subscriber to send events to
     * @param queue the queue to drain if in the post-complete state
     * @param state holds the request amount and the post-completed flag
     * @param isCancelled a supplier that returns true if the drain has been cancelled
     * @return true if the queue was completely drained or the drain process was cancelled
     */
    static <T> boolean postCompleteDrain(long n,
                                         Subscriber<? super T> actual,
                                         Queue<T> queue,
                                         AtomicLong state,
                                         BooleanSupplier isCancelled) {

// TODO enable fast-path
//        if (n == -1 || n == Long.MAX_VALUE) {
//            for (;;) {
//                if (isCancelled.getAsBoolean()) {
//                    break;
//                }
//
//                T v = queue.poll();
//
//                if (v == null) {
//                    actual.onComplete();
//                    break;
//                }
//
//                actual.onNext(v);
//            }
//
//            return true;
//        }

        long e = n & COMPLETED_MASK;

        for (; ; ) {

            while (e != n) {
                if (isCancelled(isCancelled)) {
                    return true;
                }

                T t = queue.poll();

                if (t == null) {
                    actual.onComplete();
                    return true;
                }

                actual.onNext(t);
                e++;
            }

            if (isCancelled(isCancelled)) {
                return true;
            }

            if (queue.isEmpty()) {
                actual.onComplete();
                return true;
            }

            n = state.get();

            if (n == e) {

                n = state.addAndGet(-(e & REQUESTED_MASK));

                if ((n & REQUESTED_MASK) == 0L) {
                    return false;
                }

                e = n & COMPLETED_MASK;
            }
        }

    }
 
Example 19
Project: openjdk-jdk10   File: Random.java   View Source Code Vote up 3 votes
/**
 * Generates the next pseudorandom number. Subclasses should
 * override this, as this is used by all other methods.
 *
 * <p>The general contract of {@code next} is that it returns an
 * {@code int} value and if the argument {@code bits} is between
 * {@code 1} and {@code 32} (inclusive), then that many low-order
 * bits of the returned value will be (approximately) independently
 * chosen bit values, each of which is (approximately) equally
 * likely to be {@code 0} or {@code 1}. The method {@code next} is
 * implemented by class {@code Random} by atomically updating the seed to
 *  <pre>{@code (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)}</pre>
 * and returning
 *  <pre>{@code (int)(seed >>> (48 - bits))}.</pre>
 *
 * This is a linear congruential pseudorandom number generator, as
 * defined by D. H. Lehmer and described by Donald E. Knuth in
 * <i>The Art of Computer Programming,</i> Volume 2:
 * <i>Seminumerical Algorithms</i>, section 3.2.1.
 *
 * @param  bits random bits
 * @return the next pseudorandom value from this random number
 *         generator's sequence
 * @since  1.1
 */
protected int next(int bits) {
    long oldseed, nextseed;
    AtomicLong seed = this.seed;
    do {
        oldseed = seed.get();
        nextseed = (oldseed * multiplier + addend) & mask;
    } while (!seed.compareAndSet(oldseed, nextseed));
    return (int)(nextseed >>> (48 - bits));
}
 
Example 20
Project: advent-of-code-2017   File: Day11.java   View Source Code Vote up 3 votes
public static long part2(String movements) {

		AtomicLong maxDist = new AtomicLong(0); // trolling lambda's scope
		
		Arrays.stream(movements.split(",")).map(m -> hops.get(m)).reduce(new long[] { 0, 0, 0 }, (a, b) -> { // I'm using the accumulator as the current position
			long[] array = IntStream.range(0, 3).mapToLong(i -> a[i] + b[i]).toArray();
			maxDist.set(Math.max(maxDist.get(), Arrays.stream(array).max().getAsLong())); // compare max distance to current distance
			return array; // update the accumulator
		});

		return maxDist.get();
		
	}