java.util.concurrent.atomic.AtomicBoolean#compareAndSet()源码实例Demo

下面列出了java.util.concurrent.atomic.AtomicBoolean#compareAndSet() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: vertx-rx   文件: CompletableHelper.java
/**
 * Adapts an Vert.x {@code Handler<AsyncResult<T>>} to an RxJava2 {@link SingleObserver}.
 * <p>
 * The returned observer can be subscribed to an {@link Single#subscribe(SingleObserver)}.
 *
 * @param handler the handler to adapt
 * @return the observer
 */
public static <T> CompletableObserver toObserver(Handler<AsyncResult<T>> handler) {
  AtomicBoolean completed = new AtomicBoolean();
  return new CompletableObserver() {
    @Override
    public void onSubscribe(@NonNull Disposable d) {
    }
    @Override
    public void onComplete() {
      if (completed.compareAndSet(false, true)) {
        handler.handle(io.vertx.core.Future.succeededFuture());
      }
    }
    public void onSuccess() {
      if (completed.compareAndSet(false, true)) {
        handler.handle(io.vertx.core.Future.succeededFuture());
      }
    }
    @Override
    public void onError(Throwable error) {
      if (completed.compareAndSet(false, true)) {
        handler.handle(io.vertx.core.Future.failedFuture(error));
      }
    }
  };
}
 
源代码2 项目: nd4j   文件: AsynchronousFlowController.java
protected boolean hasActiveReads(AllocationPoint point) {
    Queue<cudaEvent_t> events = point.getReadLane();

    if (events.size() == 0)
        return false;

    AtomicBoolean result = new AtomicBoolean(false);
    List<cudaEvent_t> asList = new ArrayList<>(events);
    for (cudaEvent_t event : asList) {
        if (event == null)
            continue;

        // we mark this AllocationPoint is pending read, if at least one event isn't destroyed yet
        result.compareAndSet(false, !event.isDestroyed());
    }

    return result.get();
}
 
源代码3 项目: vertx-rx   文件: RxHelper.java
/**
 * Adapts a Vert.x {@code Handler<AsyncResult<T>>} to an RxJava {@link Subscriber}.
 * <p>
 * The returned subscriber can be subscribed to an {@link Observable#subscribe(Subscriber)} or
 * {@link rx.Single#subscribe(Subscriber)}.
 *
 * @param handler the handler to adapt
 * @return the subscriber
 */
public static <T> Subscriber<T> toSubscriber(Handler<AsyncResult<T>> handler) {
  AtomicBoolean completed = new AtomicBoolean();
  return new Subscriber<T>() {
    @Override
    public void onCompleted() {
      if (completed.compareAndSet(false, true)) {
        handler.handle(Future.succeededFuture());
      }
    }
    @Override
    public void onError(Throwable error) {
      if (completed.compareAndSet(false, true)) {
        handler.handle(Future.failedFuture(error));
      }
    }
    @Override
    public void onNext(T item) {
      if (completed.compareAndSet(false, true)) {
        handler.handle(Future.succeededFuture(item));
      }
    }
  };
}
 
源代码4 项目: deeplearning4j   文件: ParallelInference.java
protected void init() {
    observables = new LinkedBlockingQueue<>(queueLimit);

    int numDevices = Nd4j.getAffinityManager().getNumberOfDevices();
    int currentDevice = Nd4j.getAffinityManager().getDeviceForCurrentThread();
    AtomicBoolean assignedRoot = new AtomicBoolean(false);

    zoo = new InferenceWorker[workers];
    for (int i = 0; i < workers; i++) {
        int cDevice = i % numDevices;
        boolean cRoot = !assignedRoot.get() && cDevice == currentDevice;
        assignedRoot.compareAndSet(false, cRoot);

        zoo[i] = new InferenceWorker(i, model, observables, cRoot, cDevice);

        zoo[i].setDaemon(true);
        zoo[i].start();
    }


    if (inferenceMode == InferenceMode.BATCHED) {
        log.info("Initializing ObservablesProvider...");
        provider = new ObservablesProvider(nanos, batchLimit, observables);
    }
}
 
源代码5 项目: tddl5   文件: LockPerfMain.java
public void tAtomicBoolean() {
    System.currentTimeMillis();
    AtomicBoolean atomic = new AtomicBoolean();

    long t1 = System.currentTimeMillis();
    for (int i = 0; i < 10000000; i++) {
        if (atomic.compareAndSet(false, true)) {
            try {
                // ...
            } finally {
                atomic.set(false);
            }
        }
    }
    long t2 = System.currentTimeMillis();

    System.out.println("take time:" + (t2 - t1) + " ms.");
}
 
源代码6 项目: dble   文件: LockPerfMain.java
public void tAtomicBoolean() {
    System.currentTimeMillis();
    AtomicBoolean atomic = new AtomicBoolean();

    long t1 = System.currentTimeMillis();
    for (int i = 0; i < 10000000; i++) {
        if (atomic.compareAndSet(false, true)) {
            try {
                // ...
            } finally {
                atomic.set(false);
            }
        }
    }
    long t2 = System.currentTimeMillis();

    System.out.println("take time:" + (t2 - t1) + " ms.");
}
 
源代码7 项目: presto   文件: TaskInfoFetcher.java
/**
 * Add a listener for the final task info.  This notification is guaranteed to be fired only once.
 * Listener is always notified asynchronously using a dedicated notification thread pool so, care should
 * be taken to avoid leaking {@code this} when adding a listener in a constructor. Additionally, it is
 * possible notifications are observed out of order due to the asynchronous execution.
 */
public void addFinalTaskInfoListener(StateChangeListener<TaskInfo> stateChangeListener)
{
    AtomicBoolean done = new AtomicBoolean();
    StateChangeListener<Optional<TaskInfo>> fireOnceStateChangeListener = finalTaskInfo -> {
        if (finalTaskInfo.isPresent() && done.compareAndSet(false, true)) {
            stateChangeListener.stateChanged(finalTaskInfo.get());
        }
    };
    finalTaskInfo.addStateChangeListener(fireOnceStateChangeListener);
    fireOnceStateChangeListener.stateChanged(finalTaskInfo.get());
}
 
源代码8 项目: presto   文件: MockRemoteTaskFactory.java
@Override
public void addFinalTaskInfoListener(StateChangeListener<TaskInfo> stateChangeListener)
{
    AtomicBoolean done = new AtomicBoolean();
    StateChangeListener<TaskState> fireOnceStateChangeListener = state -> {
        if (state.isDone() && done.compareAndSet(false, true)) {
            stateChangeListener.stateChanged(getTaskInfo());
        }
    };
    taskStateMachine.addStateChangeListener(fireOnceStateChangeListener);
    fireOnceStateChangeListener.stateChanged(taskStateMachine.getState());
}
 
源代码9 项目: aion-germany   文件: Base.java
protected void chooseAttackersRace() {
	AtomicBoolean next = new AtomicBoolean(Math.random() < 0.5);
	for (Race race : list) {
		if (race == null) {
			throw new NullPointerException("Base:" + race + " race is null chooseAttackersRace!");
		}
		else if (!race.equals(getRace())) {
			if (next.compareAndSet(true, false)) {
				continue;
			}
			spawnAttackers(race);
		}
	}
}
 
源代码10 项目: deeplearning4j   文件: PopularityWalkerTest.java
@Test
public void testPopularityWalker4() throws Exception {
    GraphWalker<VocabWord> walker =
                    new PopularityWalker.Builder<>(graph).setWalkDirection(WalkDirection.FORWARD_ONLY)
                                    .setNoEdgeHandling(NoEdgeHandling.CUTOFF_ON_DISCONNECTED).setWalkLength(10)
                                    .setPopularityMode(PopularityMode.MINIMUM).setPopularitySpread(3)
                                    .setSpreadSpectrum(SpreadSpectrum.PROPORTIONAL).build();

    System.out.println("Connected [3] size: " + graph.getConnectedVertices(3).size());
    System.out.println("Connected [4] size: " + graph.getConnectedVertices(4).size());

    AtomicBoolean got3 = new AtomicBoolean(false);
    AtomicBoolean got8 = new AtomicBoolean(false);
    AtomicBoolean got9 = new AtomicBoolean(false);

    for (int i = 0; i < 50; i++) {
        Sequence<VocabWord> sequence = walker.next();
        assertEquals("0", sequence.getElements().get(0).getLabel());
        System.out.println("Position at 1: [" + sequence.getElements().get(1).getLabel() + "]");

        got3.compareAndSet(false, sequence.getElements().get(1).getLabel().equals("3"));
        got8.compareAndSet(false, sequence.getElements().get(1).getLabel().equals("8"));
        got9.compareAndSet(false, sequence.getElements().get(1).getLabel().equals("9"));

        assertTrue(sequence.getElements().get(1).getLabel().equals("8")
                        || sequence.getElements().get(1).getLabel().equals("3")
                        || sequence.getElements().get(1).getLabel().equals("9"));

        walker.reset(false);
    }

    assertTrue(got3.get());
    assertTrue(got8.get());
    assertTrue(got9.get());
}
 
源代码11 项目: openboard   文件: ExpandableBinaryDictionary.java
/**
 * Reloads the dictionary. Access is controlled on a per dictionary file basis.
 */
private void asyncReloadDictionary() {
    final AtomicBoolean isReloading = mIsReloading;
    if (!isReloading.compareAndSet(false, true)) {
        return;
    }
    final File dictFile = mDictFile;
    asyncExecuteTaskWithWriteLock(new Runnable() {
        @Override
        public void run() {
            try {
                if (!dictFile.exists() || isNeededToRecreate()) {
                    // If the dictionary file does not exist or contents have been updated,
                    // generate a new one.
                    createNewDictionaryLocked();
                } else if (getBinaryDictionary() == null) {
                    // Otherwise, load the existing dictionary.
                    loadBinaryDictionaryLocked();
                    final BinaryDictionary binaryDictionary = getBinaryDictionary();
                    if (binaryDictionary != null && !(isValidDictionaryLocked()
                            // TODO: remove the check below
                            && matchesExpectedBinaryDictFormatVersionForThisType(
                                    binaryDictionary.getFormatVersion()))) {
                        // Binary dictionary or its format version is not valid. Regenerate
                        // the dictionary file. createNewDictionaryLocked will remove the
                        // existing files if appropriate.
                        createNewDictionaryLocked();
                    }
                }
                clearNeedsToRecreate();
            } finally {
                isReloading.set(false);
            }
        }
    });
}
 
源代码12 项目: j2objc   文件: AtomicBooleanTest.java
/**
 * compareAndSet in one thread enables another waiting for value
 * to succeed
 */
public void testCompareAndSetInMultipleThreads() throws Exception {
    final AtomicBoolean ai = new AtomicBoolean(true);
    Thread t = new Thread(new CheckedRunnable() {
        public void realRun() {
            while (!ai.compareAndSet(false, true)) Thread.yield();
        }});

    t.start();
    assertTrue(ai.compareAndSet(true, false));
    t.join(LONG_DELAY_MS);
    assertFalse(t.isAlive());
}
 
源代码13 项目: Mycat-JCache   文件: ItemsImpl.java
private void item_unlink_q(long addr) {
	int clsid = ItemUtil.getSlabsClsid(addr);
	AtomicBoolean lru_locks = JcacheContext.getLRU_Lock(clsid);
	while(!lru_locks.compareAndSet(false, true)){}
	try {
		do_item_unlink_q(addr);
	} finally {
		lru_locks.lazySet(false);
	}
}
 
源代码14 项目: twill   文件: SimpleKafkaConsumer.java
/**
 * Wrap a given MessageCallback by a executor so that calls are executed in the given executor.
 * By running the calls through the executor, it also block and wait for the task being completed so that
 * it can block the poller thread depending on the rate of processing that the callback can handle.
 */
private MessageCallback wrapCallback(final MessageCallback callback,
                                     final ExecutorService executor, final Cancellable cancellable) {
  final AtomicBoolean stopped = new AtomicBoolean();
  return new MessageCallback() {
    @Override
    public long onReceived(final Iterator<FetchedMessage> messages) {
      if (stopped.get()) {
        return -1L;
      }
      return Futures.getUnchecked(executor.submit(new Callable<Long>() {
        @Override
        public Long call() {
          if (stopped.get()) {
            return -1L;
          }
          return callback.onReceived(messages);
        }
      }));
    }

    @Override
    public void finished() {
      // Make sure finished only get called once.
      if (!stopped.compareAndSet(false, true)) {
        return;
      }
      Futures.getUnchecked(executor.submit(new Runnable() {
        @Override
        public void run() {
          // When finished is called, also cancel the consumption from all polling thread.
          callback.finished();
          cancellable.cancel();
        }
      }));
    }
  };
}
 
源代码15 项目: hadoop-connectors   文件: StorageStubProvider.java
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
    MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions, Channel channel) {
  ClientCall<ReqT, RespT> newCall = channel.newCall(methodDescriptor, callOptions);
  final AtomicBoolean countedCancel = new AtomicBoolean(false);

  // A streaming call might be terminated in one of several possible ways:
  // * The call completes normally -> onClose() will be invoked.
  // * The context is cancelled -> CancellationListener.cancelled() will be called.
  // * The call itself is cancelled (doesn't currently happen) -> ClientCall.cancel() called.
  //
  // It's possible more than one of these could happen, so we use countedCancel to make sure we
  // don't double count a decrement.
  Context.current()
      .addListener(
          context -> {
            if (countedCancel.compareAndSet(false, true)) {
              ongoingRequestCount.decrementAndGet();
            }
          },
          backgroundTasksThreadPool);

  return new SimpleForwardingClientCall(newCall) {
    @Override
    public void cancel(@Nullable String message, @Nullable Throwable cause) {
      if (countedCancel.compareAndSet(false, true)) {
        ongoingRequestCount.decrementAndGet();
      }
      super.cancel(message, cause);
    }

    @Override
    public void start(Listener responseListener, Metadata headers) {
      ongoingRequestCount.incrementAndGet();
      this.delegate()
          .start(
              new SimpleForwardingClientCallListener(responseListener) {
                @Override
                public void onClose(Status status, Metadata trailers) {
                  if (countedCancel.compareAndSet(false, true)) {
                    ongoingRequestCount.decrementAndGet();
                  }
                  super.onClose(status, trailers);
                }
              },
              headers);
    }
  };
}
 
源代码16 项目: cyclops   文件: ZippingLatestOperator.java
private void handleComplete(AtomicBoolean completeSent,Runnable onComplete){
    if(completeSent.compareAndSet(false,true)){
        onComplete.run();
    }
}
 
public static void toggleRuntimeState(AtomicBoolean state) {
    boolean runtimeVal = false;
    while (!state.compareAndSet(runtimeVal, !runtimeVal)) {
        runtimeVal = !runtimeVal;
    }
}
 
源代码18 项目: RxJava3-preview   文件: CompletableAmb.java
@Override
public void subscribeActual(final CompletableObserver s) {
    CompletableSource[] sources = this.sources;
    int count = 0;
    if (sources == null) {
        sources = new CompletableSource[8];
        try {
            for (CompletableSource element : sourcesIterable) {
                if (element == null) {
                    EmptyDisposable.error(new NullPointerException("One of the sources is null"), s);
                    return;
                }
                if (count == sources.length) {
                    CompletableSource[] b = new CompletableSource[count + (count >> 2)];
                    System.arraycopy(sources, 0, b, 0, count);
                    sources = b;
                }
                sources[count++] = element;
            }
        } catch (Throwable e) {
            Exceptions.throwIfFatal(e);
            EmptyDisposable.error(e, s);
            return;
        }
    } else {
        count = sources.length;
    }

    final CompositeDisposable set = new CompositeDisposable();
    s.onSubscribe(set);

    final AtomicBoolean once = new AtomicBoolean();

    CompletableObserver inner = new Amb(once, set, s);

    for (int i = 0; i < count; i++) {
        CompletableSource c = sources[i];
        if (set.isDisposed()) {
            return;
        }
        if (c == null) {
            NullPointerException npe = new NullPointerException("One of the sources is null");
            if (once.compareAndSet(false, true)) {
                set.dispose();
                s.onError(npe);
            } else {
                RxJavaCommonPlugins.onError(npe);
            }
            return;
        }

        // no need to have separate observers because inner is stateless
        c.subscribe(inner);
    }

    if (count == 0) {
        s.onComplete();
    }
}
 
源代码19 项目: cyclops   文件: ZippingOperator.java
private void handleComplete(AtomicBoolean completeSent,Runnable onComplete){
    if(completeSent.compareAndSet(false,true)){
        onComplete.run();
    }
}
 
源代码20 项目: JCTools   文件: QueueSanityTestMpscArrayExtended.java
@Test
public void testOfferPollSemantics() throws Exception
{
    final AtomicBoolean stop = new AtomicBoolean();
    final AtomicBoolean consumerLock = new AtomicBoolean(true);
    final Queue<Integer> q = new MpscArrayQueue<Integer>(2);
    // fill up the queue
    while (q.offer(1))
    {
        ;
    }
    // queue has 2 empty slots
    q.poll();
    q.poll();

    final Val fail = new Val();
    final Runnable runnable = new Runnable()
    {
        @Override
        public void run()
        {
            while (!stop.get())
            {
                if (!q.offer(1))
                {
                    fail.value++;
                }

                while (!consumerLock.compareAndSet(true, false))
                {
                    ;
                }
                if (q.poll() == null)
                {
                    fail.value++;
                }
                consumerLock.lazySet(true);
            }
        }
    };
    Thread t1 = new Thread(runnable);
    Thread t2 = new Thread(runnable);

    t1.start();
    t2.start();
    Thread.sleep(1000);
    stop.set(true);
    t1.join();
    t2.join();
    assertEquals("Unexpected offer/poll observed", 0, fail.value);
}