当前位置: 首页>>代码示例>>Java>>正文


Java AtomicReference.compareAndSet方法代码示例

本文整理汇总了Java中java.util.concurrent.atomic.AtomicReference.compareAndSet方法的典型用法代码示例。如果您正苦于以下问题:Java AtomicReference.compareAndSet方法的具体用法?Java AtomicReference.compareAndSet怎么用?Java AtomicReference.compareAndSet使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.concurrent.atomic.AtomicReference的用法示例。


在下文中一共展示了AtomicReference.compareAndSet方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: compute

import java.util.concurrent.atomic.AtomicReference; //导入方法依赖的package包/类
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;
			}
		}
	}
}
 
开发者ID:zhangjunfang,项目名称:util,代码行数:27,代码来源:ConcurrentHashMapV8.java

示例2: decFloat

import java.util.concurrent.atomic.AtomicReference; //导入方法依赖的package包/类
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;
    }
  }
}
 
开发者ID:ampool,项目名称:monarch,代码行数:19,代码来源:StatsAggregator.java

示例3: decLong

import java.util.concurrent.atomic.AtomicReference; //导入方法依赖的package包/类
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;
    }
  }
}
 
开发者ID:ampool,项目名称:monarch,代码行数:19,代码来源:StatsAggregator.java

示例4: create

import java.util.concurrent.atomic.AtomicReference; //导入方法依赖的package包/类
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);
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:26,代码来源:OperatorPublish.java

示例5: addTask

import java.util.concurrent.atomic.AtomicReference; //导入方法依赖的package包/类
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);
}
 
开发者ID:UraniumMC,项目名称:Uranium,代码行数:9,代码来源:CraftScheduler.java

示例6: testConcurrentDynamicUpdates

import java.util.concurrent.atomic.AtomicReference; //导入方法依赖的package包/类
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());
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:38,代码来源:DynamicMappingIT.java

示例7: abortWait

import java.util.concurrent.atomic.AtomicReference; //导入方法依赖的package包/类
/**
 * 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);
        }
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:24,代码来源:Phaser.java

示例8: set

import java.util.concurrent.atomic.AtomicReference; //导入方法依赖的package包/类
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();
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:16,代码来源:SerialSubscription.java

示例9: compute

import java.util.concurrent.atomic.AtomicReference; //导入方法依赖的package包/类
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;
            }
        }
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:30,代码来源:ConcurrentHashMap.java

示例10: unsubscribe

import java.util.concurrent.atomic.AtomicReference; //导入方法依赖的package包/类
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);
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:15,代码来源:RefCountSubscription.java

示例11: setOnce

import java.util.concurrent.atomic.AtomicReference; //导入方法依赖的package包/类
/**
 * 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;
}
 
开发者ID:akarnokd,项目名称:RxJava3-preview,代码行数:22,代码来源:EndObserverHelper.java

示例12: setOnce

import java.util.concurrent.atomic.AtomicReference; //导入方法依赖的package包/类
/**
 * 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;
}
 
开发者ID:akarnokd,项目名称:RxJava3-preview,代码行数:22,代码来源:EndSubscriberHelper.java

示例13: incInt

import java.util.concurrent.atomic.AtomicReference; //导入方法依赖的package包/类
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;
    }
  }
}
 
开发者ID:ampool,项目名称:monarch,代码行数:14,代码来源:StatsAggregator.java

示例14: evaluate

import java.util.concurrent.atomic.AtomicReference; //导入方法依赖的package包/类
@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();
        }
    }
}
 
开发者ID:altiplanogao,项目名称:io-comparison,代码行数:45,代码来源:MultiTestRule.java

示例15: testThreads

import java.util.concurrent.atomic.AtomicReference; //导入方法依赖的package包/类
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();
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:57,代码来源:ParentChildFieldDataTests.java


注:本文中的java.util.concurrent.atomic.AtomicReference.compareAndSet方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。