java.util.concurrent.atomic.AtomicReference类的使用及代码示例

x33g5p2x  于2022-01-15 转载在 其他  
字(9.0k)|赞(0)|评价(0)|浏览(185)

本文整理了Java中java.util.concurrent.atomic.AtomicReference类的一些代码示例,展示了AtomicReference类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。AtomicReference类的具体详情如下:
包路径:java.util.concurrent.atomic.AtomicReference
类名称:AtomicReference

AtomicReference介绍

[英]An object reference that may be updated atomically. See the java.util.concurrent.atomic package specification for description of the properties of atomic variables.
[中]可以原子更新的对象引用。请参阅java。util。同时发生的描述原子变量属性的原子包规范。

代码示例

代码示例来源:origin: ReactiveX/RxJava

void doTerminate() {
  Runnable r = onTerminate.get();
  if (r != null && onTerminate.compareAndSet(r, null)) {
    r.run();
  }
}

代码示例来源:origin: ReactiveX/RxJava

@Override
  public void accept(Throwable e) {
    err.set(e);
  }
});

代码示例来源:origin: ReactiveX/RxJava

@SuppressWarnings("unchecked")
ReplaySubscriber(ReplayBuffer<T> buffer) {
  this.buffer = buffer;
  this.management = new AtomicInteger();
  this.subscribers = new AtomicReference<InnerSubscription<T>[]>(EMPTY);
  this.shouldConnect = new AtomicBoolean();
}

代码示例来源:origin: ReactiveX/RxJava

public static <T> Throwable terminate(AtomicReference<Throwable> field) {
  Throwable current = field.get();
  if (current != TERMINATED) {
    current = field.getAndSet(TERMINATED);
  }
  return current;
}

代码示例来源:origin: ReactiveX/RxJava

@Override
public void dispose() {
  if (subscribers.get() != TERMINATED) {
    @SuppressWarnings("unchecked")
    InnerSubscriber[] ps = subscribers.getAndSet(TERMINATED);
    if (ps != TERMINATED) {
      current.compareAndSet(PublishSubscriber.this, null);
      SubscriptionHelper.cancel(upstream);
    }
  }
}

代码示例来源:origin: apache/incubator-druid

startLatch.await();
failureHappened.set(true);
reason.set("interrupt.");
stopLatch.countDown();
return;
  final float indexedVal = indexed.get(j);
  if (Floats.compare(val, indexedVal) != 0) {
   failureHappened.set(true);
   reason.set(StringUtils.format("Thread1[%d]: %f != %f", j, val, indexedVal));
   stopLatch.countDown();
   return;
failureHappened.set(true);
reason.set(e.getMessage());

代码示例来源:origin: google/guava

private static void verifyOccupiedMethodsInAnotherThread(
   final Monitor monitor,
   boolean expectedIsOccupied,
   boolean expectedIsOccupiedByCurrentThread,
   int expectedOccupiedDepth) {
  final AtomicBoolean actualIsOccupied = new AtomicBoolean();
  final AtomicBoolean actualIsOccupiedByCurrentThread = new AtomicBoolean();
  final AtomicInteger actualOccupiedDepth = new AtomicInteger();
  final AtomicReference<Throwable> thrown = new AtomicReference<>();
  joinUninterruptibly(
    startThread(
      new Runnable() {
       @Override
       public void run() {
        try {
         actualIsOccupied.set(monitor.isOccupied());
         actualIsOccupiedByCurrentThread.set(monitor.isOccupiedByCurrentThread());
         actualOccupiedDepth.set(monitor.getOccupiedDepth());
        } catch (Throwable t) {
         thrown.set(t);
        }
       }
      }));
  assertNull(thrown.get());
  assertEquals(expectedIsOccupied, actualIsOccupied.get());
  assertEquals(expectedIsOccupiedByCurrentThread, actualIsOccupiedByCurrentThread.get());
  assertEquals(expectedOccupiedDepth, actualOccupiedDepth.get());
 }
}

代码示例来源:origin: ReactiveX/RxJava

WindowBoundaryMainSubscriber(Subscriber<? super Flowable<T>> downstream, int capacityHint, Callable<? extends Publisher<B>> other) {
  this.downstream = downstream;
  this.capacityHint = capacityHint;
  this.boundarySubscriber = new AtomicReference<WindowBoundaryInnerSubscriber<T, B>>();
  this.windows = new AtomicInteger(1);
  this.queue = new MpscLinkedQueue<Object>();
  this.errors = new AtomicThrowable();
  this.stopWindows = new AtomicBoolean();
  this.other = other;
  this.requested = new AtomicLong();
}

代码示例来源:origin: neo4j/neo4j

@Test
public void tryToReproduceTheIssue() throws Exception
{
  // GIVEN
  GraphDatabaseService db = dbRule.getGraphDatabaseAPI();
  CountDownLatch startSignal = new CountDownLatch( 1 );
  AtomicBoolean stopSignal = new AtomicBoolean();
  AtomicReference<Exception> failure = new AtomicReference<>();
  Node parentNode = createNode( db );
  Collection<Worker> workers = createWorkers( db, startSignal, stopSignal, failure, parentNode );
  // WHEN
  startSignal.countDown();
  sleep( 500 );
  stopSignal.set( true );
  awaitWorkersToEnd( workers );
  // THEN
  if ( failure.get() != null )
  {
    throw new Exception( "A worker failed", failure.get() );
  }
}

代码示例来源:origin: apache/avro

@Test
public void ack() throws Exception {
 simpleClient.ack();
 ackLatch.get().await(2, TimeUnit.SECONDS);
 Assert.assertTrue("Expected ack flag to be set", ackFlag.get());
 ackLatch.set(new CountDownLatch(1));
 simpleClient.ack();
 ackLatch.get().await(2, TimeUnit.SECONDS);
 Assert.assertFalse("Expected ack flag to be cleared", ackFlag.get());
}

代码示例来源:origin: ReactiveX/RxJava

public StrictSubscriber(Subscriber<? super T> downstream) {
  this.downstream = downstream;
  this.error = new AtomicThrowable();
  this.requested = new AtomicLong();
  this.upstream = new AtomicReference<Subscription>();
  this.once = new AtomicBoolean();
}

代码示例来源:origin: apache/avro

@Override
 synchronized public void ack() {
  ackFlag.set(!ackFlag.get());
  ackLatch.get().countDown();
 }
}

代码示例来源:origin: eclipse-vertx/vert.x

private void testHttpConnect(String host, Consumer<SocketMetric> checker) {
 server = vertx.createHttpServer();
 AtomicReference<HttpClientMetric> clientMetric = new AtomicReference<>();
 server.requestHandler(req -> {
  FakeHttpServerMetrics metrics = FakeMetricsBase.getMetrics(server);
  so.closeHandler(v -> {
   assertNull(metrics.getMetric(req));
   assertFalse(serverMetric.socket.connected.get());
   assertEquals(5, serverMetric.socket.bytesRead.get());
   assertEquals(5, serverMetric.socket.bytesWritten.get());
   assertEquals(serverMetric.socket.remoteAddress.host(), serverMetric.socket.remoteName);
   assertFalse(clientMetric.get().socket.connected.get());
   assertEquals(5, clientMetric.get().socket.bytesRead.get());
   assertEquals(5, clientMetric.get().socket.bytesWritten.get());
   checker.accept(clientMetric.get().socket);
   testComplete();
  });
  request.handler(onSuccess(resp -> {
   assertEquals(200, resp.statusCode());
   clientMetric.set(metrics.getMetric(request));
   assertNotNull(clientMetric.get());
   NetSocket socket = resp.netSocket();
   socket.write(Buffer.buffer("hello"));

代码示例来源:origin: ReactiveX/RxJava

if (windows.get() == 0) {
  queue.clear();
  window = null;
if (!stopWindows.get()) {
  if (emitted != requested.get()) {
    w = UnicastProcessor.create(capacityHint, this);
    window = w;
    windows.getAndIncrement();
    if (boundarySubscriber.compareAndSet(null, bo)) {
      otherSource.subscribe(bo);

代码示例来源:origin: twitter/distributedlog

@Override
public void onSuccess(DLSN value) {
  if(value.getLogSegmentSequenceNo() != currentLogSegmentSeqNo) {
    LOG.debug("LogSegmentSequenceNumber: {}, Expected {}", value.getLogSegmentSequenceNo(), currentLogSegmentSeqNo);
    errorsFound.set(true);
  }
  if(value.getEntryId() != currentEntryId) {
    LOG.debug("EntryId: {}, Expected {}", value.getEntryId(), currentEntryId);
    errorsFound.set(true);
  }
  if (value.compareTo(maxDLSN.get()) > 0) {
    maxDLSN.set(value);
  }
  syncLatch.countDown();
  LOG.debug("SyncLatch: {}", syncLatch.getCount());
}
@Override

代码示例来源:origin: spring-projects/spring-framework

@Override
public void completed(Integer written, ByteBuffer byteBuffer) {
  long pos = this.position.addAndGet(written);
  if (byteBuffer.hasRemaining()) {
    this.channel.write(byteBuffer, pos, byteBuffer, this);
    return;
  }
  sinkDataBuffer();
  Throwable throwable = this.error.get();
  if (throwable != null) {
    this.sink.error(throwable);
  }
  else if (this.completed.get()) {
    this.sink.complete();
  }
  else {
    request(1);
  }
}

代码示例来源:origin: google/guava

@Override
 public void run() {
  try {
   actualIsOccupied.set(monitor.isOccupied());
   actualIsOccupiedByCurrentThread.set(monitor.isOccupiedByCurrentThread());
   actualOccupiedDepth.set(monitor.getOccupiedDepth());
  } catch (Throwable t) {
   thrown.set(t);
  }
 }
}));

代码示例来源:origin: prestodb/presto

ListenableFuture<?> addToQueue(InternalHiveSplit split)
{
  if (stateReference.get().getKind() != INITIAL) {
    return immediateFuture(null);
  }
  if (estimatedSplitSizeInBytes.addAndGet(split.getEstimatedSizeInBytes()) > maxOutstandingSplitsBytes) {
    // TODO: investigate alternative split discovery strategies when this error is hit.
    // This limit should never be hit given there is a limit of maxOutstandingSplits.
    // If it's hit, it means individual splits are huge.
    if (loggedHighMemoryWarning.compareAndSet(false, true)) {
      highMemorySplitSourceCounter.update(1);
      log.warn("Split buffering for %s.%s in query %s exceeded memory limit (%s). %s splits are buffered.",
          databaseName, tableName, queryId, succinctBytes(maxOutstandingSplitsBytes), getBufferedInternalSplitCount());
    }
    throw new PrestoException(HIVE_EXCEEDED_SPLIT_BUFFERING_LIMIT, format(
        "Split buffering for %s.%s exceeded memory limit (%s). %s splits are buffered.",
        databaseName, tableName, succinctBytes(maxOutstandingSplitsBytes), getBufferedInternalSplitCount()));
  }
  bufferedInternalSplitCount.incrementAndGet();
  OptionalInt bucketNumber = split.getBucketNumber();
  return queues.offer(bucketNumber, split);
}

代码示例来源:origin: ReactiveX/RxJava

@Test
public void testDoOnEach() {
  final AtomicReference<String> r = new AtomicReference<String>();
  String output = Observable.just("one").doOnNext(new Consumer<String>() {
    @Override
    public void accept(String v) {
      r.set(v);
    }
  }).blockingSingle();
  assertEquals("one", output);
  assertEquals("one", r.get());
}

代码示例来源:origin: qunarcorp/qmq

ClusterFuture(BrokerClusterInfo cluster) {
  latch = new CountDownLatch(0);
  this.cluster = new AtomicReference<>(cluster);
  inRequest = new AtomicBoolean(false);
}

相关文章