List of usage examples for java.util.concurrent.atomic AtomicReference compareAndSet
public final boolean compareAndSet(V expectedValue, V newValue)
From source file:com.netflix.genie.agent.execution.ExecutionContextImpl.java
private static <T> void setIfNullOrThrow(final T value, final AtomicReference<T> reference) { if (!reference.compareAndSet(null, value)) { throw new RuntimeException("Trying to update context object that already has a value"); }//from www . java 2 s .c o m }
From source file:Main.java
public static <T> boolean ThrsafeCompareExchangePointer(AtomicReference<T> papDestination, T apComparand, T apExchange) {/*from w ww.ja va2s . c o m*/ //return (*papDestination == apComparand) ? ((*papDestination = apExchange), true) : false; //return (papDestination == apComparand) ? ((papDestination = apExchange), true) : false; return papDestination.compareAndSet(apComparand, apExchange); }
From source file:Main.java
/** * Runs arbitrary code in the Event Dispatch Thread. * <p>/* ww w. j a va 2 s. c om*/ * The first operation performed by this method is fetching the {@code Object} to return. If {@code supplier} is not {@code null}, its {@code get()} method will be called to fetch the {@code Object}. But if {@code supplier} is {@code null}, or it * produces a {@code null} "value" from its {@code get()} method, then {@code defaultObject}, which may also be {@code null}, will be used instead. * <p> * The second operation performed by this method is handling the {@code Object} to return. So if neither {@code consumer} nor the fetched {@code Object} are {@code null}, the fetched {@code Object} will be handed to {@code consumer}. * <p> * Returns the fetched {@code Object}, which may be {@code null}. * * @param <T> the type of the returned result * @param supplier the {@code Supplier}, which may be {@code null} * @param consumer the {@code Consumer}, which may be {@code null} * @param defaultObject the default {@code Object}, which may be {@code null} * @return the fetched {@code Object}, which may be {@code null} */ public static <T> T runInEDT(final Supplier<T> supplier, final Consumer<T> consumer, final T defaultObject) { final AtomicReference<T> atomicReference = new AtomicReference<>(); if (supplier != null) { runInEDT(() -> atomicReference.set(supplier.get())); } if (defaultObject != null) { atomicReference.compareAndSet(null, defaultObject); } if (atomicReference.get() != null && consumer != null) { runInEDT(() -> consumer.accept(atomicReference.get())); } return atomicReference.get(); }
From source file:com.bfd.harpc.monitor.RpcMonitor.java
/** * ???/*from ww w . ja va 2s.c o m*/ * <p> */ protected void send() { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Start send statistics to zookeeper!"); } // for (Map.Entry<ServerNode, AtomicReference<StatisticsInfo>> entry : statisticsMap.entrySet()) { // ?? ServerNode serverNode = entry.getKey(); AtomicReference<StatisticsInfo> reference = entry.getValue(); StatisticsInfo numbers; do { numbers = reference.get(); } while (!reference.compareAndSet(numbers, null)); // ? StatisticsInfo info = new StatisticsInfo(); if (numbers != null) { info.setSuccess(numbers.getSuccess()); info.setFailure(numbers.getFailure()); info.setMaxtime(numbers.getMaxtime()); info.setMintime(numbers.getMintime()); info.setAvgtime(numbers.getAvgtime()); startTimeMap.putIfAbsent(serverNode, startTime); long useTime = System.currentTimeMillis() - startTimeMap.get(serverNode); startTimeMap.put(serverNode, System.currentTimeMillis()); // ? info.setQps(1000 / (useTime / (float) (numbers.getSuccess() + numbers.getFailure()))); } // ??? sendToZookeeper(serverNode, info, false); } // ??clientservernode???? startTime = System.currentTimeMillis(); // for (Map.Entry<ServerNode, AtomicReference<StatisticsInfo>> entry : totalStatisticsMap.entrySet()) { // ?? ServerNode serverNode = entry.getKey(); AtomicReference<StatisticsInfo> reference = entry.getValue(); StatisticsInfo numbers = reference.get(); StatisticsInfo info = new StatisticsInfo(); if (numbers != null) { info.setSuccess(numbers.getSuccess()); info.setFailure(numbers.getFailure()); info.setMaxtime(numbers.getMaxtime()); info.setMintime(numbers.getMintime()); info.setAvgtime(numbers.getAvgtime()); long useTime = System.currentTimeMillis() - beginTime; info.setQps(1000 / (useTime / (float) (numbers.getSuccess() + numbers.getFailure()))); } // ??? sendToZookeeper(serverNode, info, true); } }
From source file:com.chiorichan.scheduler.ChioriScheduler.java
private void addTask(final ChioriTask task) { final AtomicReference<ChioriTask> tail = this.tail; ChioriTask tailTask = tail.get();/*from w ww . jav a 2s. c o m*/ while (!tail.compareAndSet(tailTask, task)) { tailTask = tail.get(); } tailTask.setNext(task); }
From source file:com.android.ide.common.process.MtlProcessExecutor.java
private static ListenableFuture<Integer> grabProcessOutput(@NonNull final Process process, @NonNull final ProcessOutput output) { final SettableFuture<Integer> result = SettableFuture.create(); final AtomicReference<Exception> exceptionHolder = new AtomicReference<Exception>(); /*/*from w ww .j av a2 s.com*/ * It looks like on windows process#waitFor() can return before the thread have filled the * arrays, so we wait for both threads and the process itself. * * To make sure everything is complete before setting the future, the thread handling * "out" will wait for all its input to be read, will wait for the "err" thread to finish * and will wait for the process to finish. Only after all three are done will it set * the future and terminate. * * This means that the future will be set while the "out" thread is still running, but * no output is pending and the process has already finished. */ final Thread threadErr = new Thread("stderr") { @Override public void run() { InputStream stderr = process.getErrorStream(); OutputStream stream = output.getErrorOutput(); try { ByteStreams.copy(stderr, stream); stream.flush(); } catch (IOException e) { exceptionHolder.compareAndSet(null, e); } } }; Thread threadOut = new Thread("stdout") { @Override public void run() { InputStream stdout = process.getInputStream(); OutputStream stream = output.getStandardOutput(); try { ByteStreams.copy(stdout, stream); stream.flush(); } catch (Exception e) { exceptionHolder.compareAndSet(null, e); } try { threadErr.join(); int processResult = process.waitFor(); if (exceptionHolder.get() != null) { result.setException(exceptionHolder.get()); } result.set(processResult); output.close(); } catch (Exception e) { result.setException(e); } } }; threadErr.start(); threadOut.start(); return result; }
From source file:info.archinnov.achilles.test.integration.tests.LWTOperationsIT.java
@Test public void should_notify_listener_when_trying_to_insert_with_LWT_because_already_exist() throws Exception { //Given// ww w. j a v a2 s . co m final AtomicReference<LWTResultListener.LWTResult> atomicLWTResult = new AtomicReference(null); LWTResultListener listener = new LWTResultListener() { @Override public void onSuccess() { } @Override public void onError(LWTResult lwtResult) { atomicLWTResult.compareAndSet(null, lwtResult); } }; final EntityWithEnum entityWithEnum = new EntityWithEnum(10L, "name", EACH_QUORUM); Map<String, Object> expectedCurrentValues = ImmutableMap.<String, Object>of("id", 10L, "[applied]", false, "consistency_level", EACH_QUORUM.name(), "name", "name"); manager.insert(entityWithEnum); manager.insert(entityWithEnum, OptionsBuilder.ifNotExists().lwtResultListener(listener)); final LWTResultListener.LWTResult lwtResult = atomicLWTResult.get(); assertThat(lwtResult.operation()).isEqualTo(INSERT); assertThat(lwtResult.currentValues()).isEqualTo(expectedCurrentValues); assertThat(lwtResult.toString()).isEqualTo( "CAS operation INSERT cannot be applied. Current values are: {[applied]=false, consistency_level=EACH_QUORUM, id=10, name=name}"); }
From source file:info.archinnov.achilles.test.integration.tests.LWTOperationsIT.java
@Test public void should_notify_listener_when_trying_to_insert_with_lwt_and_ttl_because_already_exist() throws Exception { //Given/*w w w . j av a 2 s . c o m*/ final AtomicReference<LWTResultListener.LWTResult> atomicLWTResult = new AtomicReference(null); LWTResultListener listener = new LWTResultListener() { @Override public void onSuccess() { } @Override public void onError(LWTResult lwtResult) { atomicLWTResult.compareAndSet(null, lwtResult); } }; final EntityWithEnum entityWithEnum = new EntityWithEnum(10L, "name", EACH_QUORUM); Map<String, Object> expectedCurrentValues = ImmutableMap.<String, Object>of("id", 10L, "[applied]", false, "consistency_level", EACH_QUORUM.name(), "name", "name"); manager.insert(entityWithEnum); manager.insert(entityWithEnum, OptionsBuilder.ifNotExists().withTtl(100).lwtResultListener(listener)); final LWTResultListener.LWTResult LWTResult = atomicLWTResult.get(); assertThat(LWTResult.operation()).isEqualTo(INSERT); assertThat(LWTResult.currentValues()).isEqualTo(expectedCurrentValues); assertThat(LWTResult.toString()).isEqualTo( "CAS operation INSERT cannot be applied. Current values are: {[applied]=false, consistency_level=EACH_QUORUM, id=10, name=name}"); }
From source file:info.archinnov.achilles.test.integration.tests.LWTOperationsIT.java
@Test public void should_notify_listener_on_LWT_update_failure() throws Exception { //Given/* w w w. j a va 2s. co m*/ final AtomicReference<LWTResultListener.LWTResult> atomicLWTResult = new AtomicReference(null); LWTResultListener listener = new LWTResultListener() { @Override public void onSuccess() { } @Override public void onError(LWTResult lwtResult) { atomicLWTResult.compareAndSet(null, lwtResult); } }; Map<String, Object> expectedCurrentValues = ImmutableMap.<String, Object>of("[applied]", false, "name", "John"); CompleteBean entity = builder().randomId().name("John").addFollowers("Paul", "Andrew").buid(); final CompleteBean managed = manager.insert(entity); managed.getFollowers().add("Helen"); //When manager.update(managed, ifEqualCondition("name", "Helen").lwtResultListener(listener)); //Then final LWTResultListener.LWTResult LWTResult = atomicLWTResult.get(); assertThat(LWTResult).isNotNull(); assertThat(LWTResult.operation()).isEqualTo(UPDATE); assertThat(LWTResult.currentValues()).isEqualTo(expectedCurrentValues); }
From source file:info.archinnov.achilles.test.integration.tests.LWTOperationsIT.java
@Test public void should_notify_listener_when_failing_cas_update() throws Exception { //Given/*from w w w . jav a 2 s . com*/ final AtomicReference<LWTResultListener.LWTResult> atomicCASResult = new AtomicReference(null); LWTResultListener listener = new LWTResultListener() { @Override public void onSuccess() { } @Override public void onError(LWTResult lwtResult) { atomicCASResult.compareAndSet(null, lwtResult); } }; final EntityWithEnum entityWithEnum = new EntityWithEnum(10L, "John", EACH_QUORUM); final EntityWithEnum managed = manager.insert(entityWithEnum); Map<String, Object> expectedCurrentValues = ImmutableMap.<String, Object>of("[applied]", false, "consistency_level", EACH_QUORUM.name(), "name", "John"); managed.setName("Helen"); //When manager.update(managed, ifEqualCondition("name", "name").ifEqualCondition("consistency_level", EACH_QUORUM) .lwtResultListener(listener)); final LWTResultListener.LWTResult LWTResult = atomicCASResult.get(); assertThat(LWTResult).isNotNull(); assertThat(LWTResult.operation()).isEqualTo(UPDATE); assertThat(LWTResult.currentValues()).isEqualTo(expectedCurrentValues); assertThat(LWTResult.toString()).isEqualTo( "CAS operation UPDATE cannot be applied. Current values are: {[applied]=false, consistency_level=EACH_QUORUM, name=John}"); }