Java Code Examples for java.util.concurrent.atomic.AtomicReference.compareAndSet()

The following are Jave code examples for showing how to use compareAndSet() of the java.util.concurrent.atomic.AtomicReference class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: util   File: ConcurrentHashMapV8.java   Source Code and License Vote up 6 votes
public final void compute() {
	final Fun<? super K, ? extends U> searchFunction;
	final AtomicReference<U> result;
	if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {
		for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i;) {
			if (result.get() != null)
				return;
			addToPendingCount(1);
			new SearchKeysTask<K, V, U>(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result)
					.fork();
		}
		while (result.get() == null) {
			U u;
			Node<K, V> p;
			if ((p = advance()) == null) {
				propagateCompletion();
				break;
			}
			if ((u = searchFunction.apply(p.key)) != null) {
				if (result.compareAndSet(null, u))
					quietlyCompleteRoot();
				break;
			}
		}
	}
}
 
Example 2
Project: monarch   File: StatsAggregator.java   Source Code and License Vote up 6 votes
public void decFloat(String attributeName, Float oldVal) {
  if (oldVal == 0) {
    return;
  }
  AtomicReference<Number> ar = aggregateMap.get(attributeName);
  Number curVal;
  for (;;) {
    Number expectedVal = ar.get();
    if (expectedVal.floatValue() != 0) {
      curVal = expectedVal.floatValue() - oldVal;
    } else {
      return;
    }
    if (ar.compareAndSet(expectedVal, curVal)) {
      return;
    }
  }
}
 
Example 3
Project: monarch   File: StatsAggregator.java   Source Code and License Vote up 6 votes
public void decLong(String attributeName, Long oldVal) {
  if (oldVal == 0) {
    return;
  }
  AtomicReference<Number> ar = aggregateMap.get(attributeName);
  Number curVal;
  for (;;) {
    Number expectedVal = ar.get();
    if (expectedVal.longValue() != 0) {
      curVal = expectedVal.longValue() - oldVal;
    } else {
      return;
    }
    if (ar.compareAndSet(expectedVal, curVal)) {
      return;
    }
  }
}
 
Example 4
Project: boohee_v5.6   File: OperatorPublish.java   Source Code and License Vote up 6 votes
public static <T> ConnectableObservable<T> create(Observable<? extends T> source) {
    final AtomicReference<PublishSubscriber<T>> curr = new AtomicReference();
    return new OperatorPublish(new Observable$OnSubscribe<T>() {
        public void call(Subscriber<? super T> child) {
            while (true) {
                PublishSubscriber<T> r = (PublishSubscriber) curr.get();
                if (r == null || r.isUnsubscribed()) {
                    PublishSubscriber<T> u = new PublishSubscriber(curr);
                    u.init();
                    if (curr.compareAndSet(r, u)) {
                        r = u;
                    } else {
                        continue;
                    }
                }
                InnerProducer<T> inner = new InnerProducer(r, child);
                if (r.add(inner)) {
                    child.add(inner);
                    child.setProducer(inner);
                    return;
                }
            }
        }
    }, source, curr);
}
 
Example 5
Project: Uranium   File: CraftScheduler.java   Source Code and License Vote up 5 votes
private void addTask(final CraftTask task) {
    final AtomicReference<CraftTask> tail = this.tail;
    CraftTask tailTask = tail.get();
    while (!tail.compareAndSet(tailTask, task)) {
        tailTask = tail.get();
    }
    tailTask.setNext(task);
}
 
Example 6
Project: elasticsearch_my   File: DynamicMappingIT.java   Source Code and License Vote up 5 votes
public void testConcurrentDynamicUpdates() throws Throwable {
    createIndex("index");
    final Thread[] indexThreads = new Thread[32];
    final CountDownLatch startLatch = new CountDownLatch(1);
    final AtomicReference<Throwable> error = new AtomicReference<>();
    for (int i = 0; i < indexThreads.length; ++i) {
        final String id = Integer.toString(i);
        indexThreads[i] = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    startLatch.await();
                    assertEquals(DocWriteResponse.Result.CREATED, client().prepareIndex("index", "type", id)
                        .setSource("field" + id, "bar").get().getResult());
                } catch (Exception e) {
                    error.compareAndSet(null, e);
                }
            }
        });
        indexThreads[i].start();
    }
    startLatch.countDown();
    for (Thread thread : indexThreads) {
        thread.join();
    }
    if (error.get() != null) {
        throw error.get();
    }
    Thread.sleep(2000);
    GetMappingsResponse mappings = client().admin().indices().prepareGetMappings("index").setTypes("type").get();
    for (int i = 0; i < indexThreads.length; ++i) {
        assertMappingsHaveField(mappings, "index", "type", "field" + i);
    }
    for (int i = 0; i < indexThreads.length; ++i) {
        assertTrue(client().prepareGet("index", "type", Integer.toString(i)).get().isExists());
    }
}
 
Example 7
Project: openjdk-jdk10   File: Phaser.java   Source Code and License Vote up 5 votes
/**
 * Variant of releaseWaiters that additionally tries to remove any
 * nodes no longer waiting for advance due to timeout or
 * interrupt. Currently, nodes are removed only if they are at
 * head of queue, which suffices to reduce memory footprint in
 * most usages.
 *
 * @return current phase on exit
 */
private int abortWait(int phase) {
    AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
    for (;;) {
        Thread t;
        QNode q = head.get();
        int p = (int)(root.state >>> PHASE_SHIFT);
        if (q == null || ((t = q.thread) != null && q.phase == p))
            return p;
        if (head.compareAndSet(q, q.next) && t != null) {
            q.thread = null;
            LockSupport.unpark(t);
        }
    }
}
 
Example 8
Project: boohee_v5.6   File: SerialSubscription.java   Source Code and License Vote up 5 votes
public void set(Subscription s) {
    if (s == null) {
        throw new IllegalArgumentException("Subscription can not be null");
    }
    State oldState;
    AtomicReference<State> localState = this.state;
    do {
        oldState = (State) localState.get();
        if (oldState.isUnsubscribed) {
            s.unsubscribe();
            return;
        }
    } while (!localState.compareAndSet(oldState, oldState.set(s)));
    oldState.subscription.unsubscribe();
}
 
Example 9
Project: jdk8u-jdk   File: Phaser.java   Source Code and License Vote up 5 votes
/**
 * Variant of releaseWaiters that additionally tries to remove any
 * nodes no longer waiting for advance due to timeout or
 * interrupt. Currently, nodes are removed only if they are at
 * head of queue, which suffices to reduce memory footprint in
 * most usages.
 *
 * @return current phase on exit
 */
private int abortWait(int phase) {
    AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
    for (;;) {
        Thread t;
        QNode q = head.get();
        int p = (int)(root.state >>> PHASE_SHIFT);
        if (q == null || ((t = q.thread) != null && q.phase == p))
            return p;
        if (head.compareAndSet(q, q.next) && t != null) {
            q.thread = null;
            LockSupport.unpark(t);
        }
    }
}
 
Example 10
Project: openjdk-jdk10   File: ConcurrentHashMap.java   Source Code and License Vote up 5 votes
public final void compute() {
    final Function<? super V, ? extends U> searchFunction;
    final AtomicReference<U> result;
    if ((searchFunction = this.searchFunction) != null &&
        (result = this.result) != null) {
        for (int i = baseIndex, f, h; batch > 0 &&
                 (h = ((f = baseLimit) + i) >>> 1) > i;) {
            if (result.get() != null)
                return;
            addToPendingCount(1);
            new SearchValuesTask<K,V,U>
                (this, batch >>>= 1, baseLimit = h, f, tab,
                 searchFunction, result).fork();
        }
        while (result.get() == null) {
            U u;
            Node<K,V> p;
            if ((p = advance()) == null) {
                propagateCompletion();
                break;
            }
            if ((u = searchFunction.apply(p.val)) != null) {
                if (result.compareAndSet(null, u))
                    quietlyCompleteRoot();
                break;
            }
        }
    }
}
 
Example 11
Project: boohee_v5.6   File: RefCountSubscription.java   Source Code and License Vote up 5 votes
public void unsubscribe() {
    State newState;
    AtomicReference<State> localState = this.state;
    State oldState;
    do {
        oldState = (State) localState.get();
        if (!oldState.isUnsubscribed) {
            newState = oldState.unsubscribe();
        } else {
            return;
        }
    } while (!localState.compareAndSet(oldState, newState));
    unsubscribeActualIfApplicable(newState);
}
 
Example 12
Project: RxJava3-preview   File: EndObserverHelper.java   Source Code and License Vote up 5 votes
/**
 * Atomically updates the target upstream AtomicReference from null to the non-null
 * next Disposable, otherwise disposes next and reports a ProtocolViolationException
 * if the AtomicReference doesn't contain the shared disposed indicator.
 * @param upstream the target AtomicReference to update
 * @param next the Disposable to set on it atomically
 * @param observer the class of the consumer to have a personalized
 * error message if the upstream already contains a non-cancelled Disposable.
 * @return true if successful, false if the content of the AtomicReference was non null
 */
public static boolean setOnce(AtomicReference<Disposable> upstream, Disposable next, Class<?> observer) {
    ObjectHelper.requireNonNull(next, "next is null");
    if (!upstream.compareAndSet(null, next)) {
        next.dispose();
        if (upstream.get() != DisposableHelper.DISPOSED) {
            reportDoubleSubscription(observer);
        }
        return false;
    }
    return true;
}
 
Example 13
Project: RxJava3-preview   File: EndSubscriberHelper.java   Source Code and License Vote up 5 votes
/**
 * Atomically updates the target upstream AtomicReference from null to the non-null
 * next Subscription, otherwise cancels next and reports a ProtocolViolationException
 * if the AtomicReference doesn't contain the shared cancelled indicator.
 * @param upstream the target AtomicReference to update
 * @param next the Subscription to set on it atomically
 * @param subscriber the class of the consumer to have a personalized
 * error message if the upstream already contains a non-cancelled Subscription.
 * @return true if successful, false if the content of the AtomicReference was non null
 */
public static boolean setOnce(AtomicReference<Subscription> upstream, Subscription next, Class<?> subscriber) {
    ObjectHelper.requireNonNull(next, "next is null");
    if (!upstream.compareAndSet(null, next)) {
        next.cancel();
        if (upstream.get() != SubscriptionHelper.CANCELLED) {
            reportDoubleSubscription(subscriber);
        }
        return false;
    }
    return true;
}
 
Example 14
Project: monarch   File: StatsAggregator.java   Source Code and License Vote up 5 votes
public void incInt(String attributeName, Integer newVal, Integer oldVal) {
  if (newVal.equals(oldVal)) {
    return;
  }
  AtomicReference<Number> ar = aggregateMap.get(attributeName);
  for (;;) {
    Number expectedVal = ar.get();
    Number curVal = expectedVal.intValue() + (newVal - oldVal);
    if (ar.compareAndSet(expectedVal, curVal)) {
      return;
    }
  }
}
 
Example 15
Project: io-comparison   File: MultiTestRule.java   Source Code and License Vote up 4 votes
@Override
public void evaluate() throws Throwable {
    long start = System.currentTimeMillis();
    if (parallel) {
        final CountDownLatch done = new CountDownLatch(times);
        final ExecutorService es = Executors.newCachedThreadPool();
        final AtomicReference<Throwable> anyError = new AtomicReference<>(null);
        try {
            for (int i = 1; i <= times; i++) {
                final int idx = i;
                es.submit(() -> {
                            try {
                                if (anyError.compareAndSet(null, null)) {
                                    if (printStep) {
                                        System.out.println("Repeat(Parallel) " + methodName + ": " + idx + "/" + times);
                                    }
                                    statement.evaluate();
                                }
                            } catch (Throwable throwable) {
                                anyError.compareAndSet(null, throwable);
                            } finally {
                                done.countDown();
                            }
                        }
                );
            }
            done.await();
            if (!anyError.compareAndSet(null, null)) {
                throw anyError.get();
            }
        } finally {
            es.shutdown();
        }
    } else {
        for (int i = 1; i <= times; i++) {
            long lapsed = System.currentTimeMillis() - start;
            long each = (i == 1 ? 0 : lapsed / (i - 1));
            if (printStep) {
                System.out.println("Repeat " + methodName + ": " + i + "/" + times + " elapsed(ms):" + lapsed + " each(ms):" + each);
            }
            statement.evaluate();
        }
    }
}
 
Example 16
Project: elasticsearch_my   File: ParentChildFieldDataTests.java   Source Code and License Vote up 4 votes
public void testThreads() throws Exception {
    final ParentChildIndexFieldData indexFieldData = getForField(childType);
    final DirectoryReader reader = ElasticsearchDirectoryReader.wrap(
            DirectoryReader.open(writer), new ShardId(new Index("test", ""), 0));
    final IndexParentChildFieldData global = indexFieldData.loadGlobal(reader);
    final AtomicReference<Exception> error = new AtomicReference<>();
    final int numThreads = scaledRandomIntBetween(3, 8);
    final Thread[] threads = new Thread[numThreads];
    final CountDownLatch latch = new CountDownLatch(1);

    final Map<Object, BytesRef[]> expected = new HashMap<>();
    for (LeafReaderContext context : reader.leaves()) {
        AtomicParentChildFieldData leafData = global.load(context);
        SortedDocValues parentIds = leafData.getOrdinalsValues(parentType);
        final BytesRef[] ids = new BytesRef[parentIds.getValueCount()];
        for (int j = 0; j < parentIds.getValueCount(); ++j) {
            final BytesRef id = parentIds.lookupOrd(j);
            if (id != null) {
                ids[j] = BytesRef.deepCopyOf(id);
            }
        }
        expected.put(context.reader().getCoreCacheKey(), ids);
    }

    for (int i = 0; i < numThreads; ++i) {
        threads[i] = new Thread() {
            @Override
            public void run() {
                try {
                    latch.await();
                    for (int i = 0; i < 100000; ++i) {
                        for (LeafReaderContext context : reader.leaves()) {
                            AtomicParentChildFieldData leafData = global.load(context);
                            SortedDocValues parentIds = leafData.getOrdinalsValues(parentType);
                            final BytesRef[] expectedIds = expected.get(context.reader().getCoreCacheKey());
                            for (int j = 0; j < parentIds.getValueCount(); ++j) {
                                final BytesRef id = parentIds.lookupOrd(j);
                                assertEquals(expectedIds[j], id);
                            }
                        }
                    }
                } catch (Exception e) {
                    error.compareAndSet(null, e);
                }
            }
        };
        threads[i].start();
    }
    latch.countDown();
    for (Thread thread : threads) {
        thread.join();
    }
    if (error.get() != null) {
        throw error.get();
    }
}
 
Example 17
Project: dubbocloud   File: DubboMonitor.java   Source Code and License Vote up 4 votes
public void send() {
    if (logger.isInfoEnabled()) {
        logger.info("Send statistics to monitor " + getUrl());
    }
    String timestamp = String.valueOf(System.currentTimeMillis());
    for (Map.Entry<Statistics, AtomicReference<long[]>> entry : statisticsMap.entrySet()) {
        // 获取已统计数据
        Statistics statistics = entry.getKey();
        AtomicReference<long[]> reference = entry.getValue();
        long[] numbers = reference.get();
        long success = numbers[0];
        long failure = numbers[1];
        long input = numbers[2];
        long output = numbers[3];
        long elapsed = numbers[4];
        long concurrent = numbers[5];
        long maxInput = numbers[6];
        long maxOutput = numbers[7];
        long maxElapsed = numbers[8];
        long maxConcurrent = numbers[9];
         
        // 发送汇总信息
        URL url = statistics.getUrl()
                .addParameters(MonitorService.TIMESTAMP, timestamp,
                        MonitorService.SUCCESS, String.valueOf(success),
                        MonitorService.FAILURE, String.valueOf(failure), 
                        MonitorService.INPUT, String.valueOf(input), 
                        MonitorService.OUTPUT, String.valueOf(output),
                        MonitorService.ELAPSED, String.valueOf(elapsed),
                        MonitorService.CONCURRENT, String.valueOf(concurrent),
                        MonitorService.MAX_INPUT, String.valueOf(maxInput),
                        MonitorService.MAX_OUTPUT, String.valueOf(maxOutput),
                        MonitorService.MAX_ELAPSED, String.valueOf(maxElapsed),
                        MonitorService.MAX_CONCURRENT, String.valueOf(maxConcurrent)
                        );
        monitorService.collect(url);
        
        // 减掉已统计数据
        long[] current;
        long[] update = new long[LENGTH];
        do {
            current = reference.get();
            if (current == null) {
                update[0] = 0;
                update[1] = 0;
                update[2] = 0;
                update[3] = 0;
                update[4] = 0;
                update[5] = 0;
            } else {
                update[0] = current[0] - success;
                update[1] = current[1] - failure;
                update[2] = current[2] - input;
                update[3] = current[3] - output;
                update[4] = current[4] - elapsed;
                update[5] = current[5] - concurrent;
            }
        } while (! reference.compareAndSet(current, update));
    }
}
 
Example 18
Project: saluki   File: ClientServerMonitor.java   Source Code and License Vote up 4 votes
public void send() {
  String timestamp = String.valueOf(System.currentTimeMillis());
  for (Map.Entry<Statistics, AtomicReference<long[]>> entry : statisticsMap.entrySet()) {
    // 获取已统计数据
    Statistics statistics = entry.getKey();
    AtomicReference<long[]> reference = entry.getValue();
    long[] numbers = reference.get();
    // 如果是0,需要等下次的数据
    if (!isZero(numbers)) {
      long success = numbers[0];
      long failure = numbers[1];
      long input = numbers[2];
      long output = numbers[3];
      long elapsed = numbers[4];
      long concurrent = numbers[5];
      long maxInput = numbers[6];
      long maxOutput = numbers[7];
      long maxElapsed = numbers[8];
      long maxConcurrent = numbers[9];
      // 发送汇总信息
      GrpcURL url = statistics.getUrl().addParameters(MonitorService.TIMESTAMP,
          String.valueOf(timestamp), MonitorService.SUCCESS, String.valueOf(success),
          MonitorService.FAILURE, String.valueOf(failure), MonitorService.INPUT,
          String.valueOf(input), MonitorService.OUTPUT, String.valueOf(output),
          MonitorService.ELAPSED, String.valueOf(elapsed), MonitorService.CONCURRENT,
          String.valueOf(concurrent / (success + failure)), MonitorService.MAX_INPUT,
          String.valueOf(maxInput), MonitorService.MAX_OUTPUT, String.valueOf(maxOutput),
          MonitorService.MAX_ELAPSED, String.valueOf(maxElapsed), MonitorService.MAX_CONCURRENT,
          String.valueOf(maxConcurrent));
      for (MonitorService monitor : monitorServices) {
        monitor.collect(url);
      }
      // 减掉已统计数据
      long[] current;
      long[] update = new long[LENGTH];
      do {
        current = reference.get();
        if (current == null) {
          update[0] = 0;
          update[1] = 0;
          update[2] = 0;
          update[3] = 0;
          update[4] = 0;
          update[5] = 0;
        } else {
          update[0] = current[0] - success;
          update[1] = current[1] - failure;
          update[2] = current[2] - input;
          update[3] = current[3] - output;
          update[4] = current[4] - elapsed;
          update[5] = current[5] - concurrent;
        }
      } while (!reference.compareAndSet(current, update));
    }
  }
}
 
Example 19
Project: dubbox-hystrix   File: DubboMonitor.java   Source Code and License Vote up 4 votes
public void collect(URL url) {
    // 读写统计变量
    int success = url.getParameter(MonitorService.SUCCESS, 0);
    int failure = url.getParameter(MonitorService.FAILURE, 0);
    int input = url.getParameter(MonitorService.INPUT, 0);
    int output = url.getParameter(MonitorService.OUTPUT, 0);
    int elapsed = url.getParameter(MonitorService.ELAPSED, 0);
    int concurrent = url.getParameter(MonitorService.CONCURRENT, 0);
    // 初始化原子引用
    Statistics statistics = new Statistics(url);
    AtomicReference<long[]> reference = statisticsMap.get(statistics);
    if (reference == null) {
        statisticsMap.putIfAbsent(statistics, new AtomicReference<long[]>());
        reference = statisticsMap.get(statistics);
    }
    // CompareAndSet并发加入统计数据
    long[] current;
    long[] update = new long[LENGTH];
    do {
        current = reference.get();
        if (current == null) {
            update[0] = success;
            update[1] = failure;
            update[2] = input;
            update[3] = output;
            update[4] = elapsed;
            update[5] = concurrent;
            update[6] = input;
            update[7] = output;
            update[8] = elapsed;
            update[9] = concurrent;
        } else {
            update[0] = current[0] + success;
            update[1] = current[1] + failure;
            update[2] = current[2] + input;
            update[3] = current[3] + output;
            update[4] = current[4] + elapsed;
            update[5] = (current[5] + concurrent) / 2;
            update[6] = current[6] > input ? current[6] : input;
            update[7] = current[7] > output ? current[7] : output;
            update[8] = current[8] > elapsed ? current[8] : elapsed;
            update[9] = current[9] > concurrent ? current[9] : concurrent;
        }
    } while (! reference.compareAndSet(current, update));
}
 
Example 20
Project: OpenJSharp   File: Phaser.java   Source Code and License Vote up 4 votes
/**
 * Possibly blocks and waits for phase to advance unless aborted.
 * Call only on root phaser.
 *
 * @param phase current phase
 * @param node if non-null, the wait node to track interrupt and timeout;
 * if null, denotes noninterruptible wait
 * @return current phase
 */
private int internalAwaitAdvance(int phase, QNode node) {
    // assert root == this;
    releaseWaiters(phase-1);          // ensure old queue clean
    boolean queued = false;           // true when node is enqueued
    int lastUnarrived = 0;            // to increase spins upon change
    int spins = SPINS_PER_ARRIVAL;
    long s;
    int p;
    while ((p = (int)((s = state) >>> PHASE_SHIFT)) == phase) {
        if (node == null) {           // spinning in noninterruptible mode
            int unarrived = (int)s & UNARRIVED_MASK;
            if (unarrived != lastUnarrived &&
                (lastUnarrived = unarrived) < NCPU)
                spins += SPINS_PER_ARRIVAL;
            boolean interrupted = Thread.interrupted();
            if (interrupted || --spins < 0) { // need node to record intr
                node = new QNode(this, phase, false, false, 0L);
                node.wasInterrupted = interrupted;
            }
        }
        else if (node.isReleasable()) // done or aborted
            break;
        else if (!queued) {           // push onto queue
            AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
            QNode q = node.next = head.get();
            if ((q == null || q.phase == phase) &&
                (int)(state >>> PHASE_SHIFT) == phase) // avoid stale enq
                queued = head.compareAndSet(q, node);
        }
        else {
            try {
                ForkJoinPool.managedBlock(node);
            } catch (InterruptedException ie) {
                node.wasInterrupted = true;
            }
        }
    }

    if (node != null) {
        if (node.thread != null)
            node.thread = null;       // avoid need for unpark()
        if (node.wasInterrupted && !node.interruptible)
            Thread.currentThread().interrupt();
        if (p == phase && (p = (int)(state >>> PHASE_SHIFT)) == phase)
            return abortWait(phase); // possibly clean up on abort
    }
    releaseWaiters(phase);
    return p;
}