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

The following examples show how to use java.util.concurrent.atomic.AtomicBoolean#compareAndSet() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AsynchronousFlowController.java    From nd4j with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 2
Source File: LockPerfMain.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
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.");
}
 
Example 3
Source File: LockPerfMain.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
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.");
}
 
Example 4
Source File: RxHelper.java    From vertx-rx with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
      }
    }
  };
}
 
Example 5
Source File: ParallelInference.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 6
Source File: CompletableHelper.java    From vertx-rx with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
      }
    }
  };
}
 
Example 7
Source File: AtomicBooleanTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * 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());
}
 
Example 8
Source File: SimpleKafkaConsumer.java    From twill with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
        }
      }));
    }
  };
}
 
Example 9
Source File: ItemsImpl.java    From Mycat-JCache with GNU General Public License v2.0 5 votes vote down vote up
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);
	}
}
 
Example 10
Source File: ExpandableBinaryDictionary.java    From openboard with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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);
            }
        }
    });
}
 
Example 11
Source File: PopularityWalkerTest.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 12
Source File: Base.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
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);
		}
	}
}
 
Example 13
Source File: MockRemoteTaskFactory.java    From presto with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 14
Source File: TaskInfoFetcher.java    From presto with Apache License 2.0 5 votes vote down vote up
/**
 * 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());
}
 
Example 15
Source File: OperationCancellationUnitTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void toggleRuntimeState(AtomicBoolean state) {
    boolean runtimeVal = false;
    while (!state.compareAndSet(runtimeVal, !runtimeVal)) {
        runtimeVal = !runtimeVal;
    }
}
 
Example 16
Source File: ZippingLatestOperator.java    From cyclops with Apache License 2.0 4 votes vote down vote up
private void handleComplete(AtomicBoolean completeSent,Runnable onComplete){
    if(completeSent.compareAndSet(false,true)){
        onComplete.run();
    }
}
 
Example 17
Source File: CompletableAmb.java    From RxJava3-preview with Apache License 2.0 4 votes vote down vote up
@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();
    }
}
 
Example 18
Source File: StorageStubProvider.java    From hadoop-connectors with Apache License 2.0 4 votes vote down vote up
@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);
    }
  };
}
 
Example 19
Source File: ZippingOperator.java    From cyclops with Apache License 2.0 4 votes vote down vote up
private void handleComplete(AtomicBoolean completeSent,Runnable onComplete){
    if(completeSent.compareAndSet(false,true)){
        onComplete.run();
    }
}
 
Example 20
Source File: QueueSanityTestMpscArrayExtended.java    From JCTools with Apache License 2.0 4 votes vote down vote up
@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);
}