Exemplo n.º 1
0
 /** getAndAdd returns previous value and adds given value */
 public void testGetAndAdd() {
   AtomicInteger ai = new AtomicInteger(1);
   assertEquals(1, ai.getAndAdd(2));
   assertEquals(3, ai.get());
   assertEquals(3, ai.getAndAdd(-4));
   assertEquals(-1, ai.get());
 }
Exemplo n.º 2
0
  void foo() {
    i.getAndAdd(2);
    i.getAndAdd(-5);
    if (i.get() == 0) {
      i.set(9);
    }

    System.out.println(i.addAndGet(9));
    System.out.println(i.addAndGet(-(9)));
  }
Exemplo n.º 3
0
 @Override
 public void ping(PingInfo pingInfo, Promise<PingResultInfo> promise) {
   int pingId = pingIds.getAndAdd(2);
   PingInfoCallback pingInfoCallback = new PingInfoCallback(pingId, promise);
   PingFrame frame = new PingFrame(version, pingId);
   control(null, frame, pingInfo.getTimeout(), pingInfo.getUnit(), pingInfoCallback);
 }
Exemplo n.º 4
0
 /** Notifies all waiting threads */
 private final void atomicNotify() {
   if (waiting.getAndAdd(0) > 0) {
     synchronized (this) {
       notifyAll();
     }
   }
 }
 public Thread newThread(final Runnable r) {
   final Thread t = new Thread(r);
   t.setName("Golden-Sample: " + getClass().getName() + "-" + threadNumber.getAndAdd(1));
   t.setDaemon(true);
   t.setPriority(3);
   return t;
 }
Exemplo n.º 6
0
  @Override
  public void newStream(HeadersFrame frame, Promise<Stream> promise, Stream.Listener listener) {
    // Synchronization is necessary to atomically create
    // the stream id and enqueue the frame to be sent.
    boolean queued;
    synchronized (this) {
      int streamId = frame.getStreamId();
      if (streamId <= 0) {
        streamId = streamIds.getAndAdd(2);
        PriorityFrame priority = frame.getPriority();
        priority =
            priority == null
                ? null
                : new PriorityFrame(
                    streamId,
                    priority.getParentStreamId(),
                    priority.getWeight(),
                    priority.isExclusive());
        frame = new HeadersFrame(streamId, frame.getMetaData(), priority, frame.isEndStream());
      }
      final IStream stream = createLocalStream(streamId, promise);
      if (stream == null) return;
      stream.setListener(listener);

      ControlEntry entry = new ControlEntry(frame, stream, new PromiseCallback<>(promise, stream));
      queued = flusher.append(entry);
    }
    // Iterate outside the synchronized block.
    if (queued) flusher.iterate();
  }
Exemplo n.º 7
0
  @Override
  public void syn(SynInfo synInfo, StreamFrameListener listener, Promise<Stream> promise) {
    // Synchronization is necessary.
    // SPEC v3, 2.3.1 requires that the stream creation be monotonically crescent
    // so we cannot allow thread1 to create stream1 and thread2 create stream3 and
    // have stream3 hit the network before stream1, not only to comply with the spec
    // but also because the compression context for the headers would be wrong, as the
    // frame with a compression history will come before the first compressed frame.
    int associatedStreamId = 0;
    if (synInfo instanceof PushSynInfo)
      associatedStreamId = ((PushSynInfo) synInfo).getAssociatedStreamId();

    synchronized (this) {
      int streamId = streamIds.getAndAdd(2);
      // TODO: for SPDYv3 we need to support the "slot" argument
      SynStreamFrame synStream =
          new SynStreamFrame(
              version,
              synInfo.getFlags(),
              streamId,
              associatedStreamId,
              synInfo.getPriority(),
              (short) 0,
              synInfo.getHeaders());
      IStream stream = createStream(synStream, listener, true, promise);
      if (stream == null) return;
      generateAndEnqueueControlFrame(
          stream, synStream, synInfo.getTimeout(), synInfo.getUnit(), stream);
    }
    flush();
  }
  private void whatOption() {
    what.incrementAndGet();
    if (what.get() > mVpList.size() - 1) {
      what.getAndAdd(-mVpList.size());
    }
    try {
      Thread.sleep(5000);
    } catch (InterruptedException e) {

    }
  }
Exemplo n.º 9
0
  private void whatOptionMall() {
    whatMall.incrementAndGet();
    if (whatMall.get() > imageViewsMall.length - 1) {
      whatMall.getAndAdd(-4);
    }
    try {
      Thread.sleep(2500);
    } catch (InterruptedException e) {

    }
  }
 // returns old value
 private int incVisitorUsageCount(int delta) {
   AtomicInteger count = myProject.getUserData(HIGHLIGHT_VISITOR_INSTANCE_COUNT);
   if (count == null) {
     count =
         ((UserDataHolderEx) myProject)
             .putUserDataIfAbsent(HIGHLIGHT_VISITOR_INSTANCE_COUNT, new AtomicInteger(0));
   }
   int old = count.getAndAdd(delta);
   assert old + delta >= 0 : old + ";" + delta;
   return old;
 }
Exemplo n.º 11
0
 @Override
 public void onFailure(Throwable t) {
   flumeFailureLogCount.getAndAdd(size);
   LOG.warn("Failed to store record", t);
   if (t instanceof IOException) {
     callback.onConnectionError();
   } else if (t instanceof EventDeliveryException) {
     callback.onRemoteError();
   } else {
     callback.onInternalError();
   }
 }
Exemplo n.º 12
0
  private void whatOpition() {
    what.incrementAndGet();
    if (what.get() > dotImageViews.length - 1) {
      what.getAndAdd(-3);
    }

    try {
      Thread.sleep(8000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 13
0
 @Override
 public int priority(PriorityFrame frame, Callback callback) {
   int streamId = frame.getStreamId();
   IStream stream = streams.get(streamId);
   if (stream == null) {
     streamId = streamIds.getAndAdd(2);
     frame =
         new PriorityFrame(
             streamId, frame.getParentStreamId(), frame.getWeight(), frame.isExclusive());
   }
   control(stream, callback, frame);
   return streamId;
 }
Exemplo n.º 14
0
 /** consume returns a CompletableFuture that is done when publisher completes */
 public void testConsume() {
   AtomicInteger sum = new AtomicInteger();
   SubmissionPublisher<Integer> p = basicPublisher();
   CompletableFuture<Void> f =
       p.consume(
           (Integer x) -> {
             sum.getAndAdd(x.intValue());
           });
   int n = 20;
   for (int i = 1; i <= n; ++i) p.submit(i);
   p.close();
   f.join();
   assertEquals((n * (n + 1)) / 2, sum.get());
 }
Exemplo n.º 15
0
 @Override
 public void clear() {
   for (int i = 0; i < size(); i++) {
     // It is likely that we have at most one violation pass this check each time around.
     if (Math.random() < UPLOAD_PROBABILITY) {
       // Ensure that we do not upload too many StrictMode violations in any single
       // session. To prevent races, we allow sNumUploads to increase beyond the
       // limit, but just skip actually uploading the stack trace then.
       if (sNumUploads.getAndAdd(1) >= MAX_UPLOADS_PER_SESSION) {
         break;
       }
       sCachedStackTraces.add(get(i));
     }
   }
   super.clear();
 }
Exemplo n.º 16
0
  @Override
  public void push(
      IStream stream, Promise<Stream> promise, PushPromiseFrame frame, Stream.Listener listener) {
    // Synchronization is necessary to atomically create
    // the stream id and enqueue the frame to be sent.
    boolean queued;
    synchronized (this) {
      int streamId = streamIds.getAndAdd(2);
      frame = new PushPromiseFrame(frame.getStreamId(), streamId, frame.getMetaData());

      final IStream pushStream = createLocalStream(streamId, promise);
      if (pushStream == null) return;
      pushStream.setListener(listener);

      ControlEntry entry =
          new ControlEntry(frame, pushStream, new PromiseCallback<>(promise, pushStream));
      queued = flusher.append(entry);
    }
    // Iterate outside the synchronized block.
    if (queued) flusher.iterate();
  }
Exemplo n.º 17
0
  public void receiveCredits(final int credits) throws Exception {
    if (credits == -1) {
      if (HornetQServerLogger.LOGGER.isDebugEnabled()) {
        HornetQServerLogger.LOGGER.debug(
            this + ":: FlowControl::Received disable flow control message");
      }
      // No flow control
      availableCredits = null;

      // There may be messages already in the queue
      promptDelivery();
    } else if (credits == 0) {
      // reset, used on slow consumers
      HornetQServerLogger.LOGGER.debug(
          this + ":: FlowControl::Received reset flow control message");
      availableCredits.set(0);
    } else {
      int previous = availableCredits.getAndAdd(credits);

      if (HornetQServerLogger.LOGGER.isDebugEnabled()) {
        HornetQServerLogger.LOGGER.debug(
            this
                + "::FlowControl::Received "
                + credits
                + " credits, previous value = "
                + previous
                + " currentValue = "
                + availableCredits.get());
      }

      if (previous <= 0 && previous + credits > 0) {
        if (HornetQServerLogger.LOGGER.isTraceEnabled()) {
          HornetQServerLogger.LOGGER.trace(
              this + "::calling promptDelivery from receiving credits");
        }
        promptDelivery();
      }
    }
  }
Exemplo n.º 18
0
 @Override
 public int updateSendWindow(int delta) {
   return sendWindow.getAndAdd(delta);
 }
Exemplo n.º 19
0
 /** Sets an artificial document from which term vectors are requested for. */
 public TermVectorRequest doc(XContentBuilder documentBuilder) {
   // assign a random id to this artificial document, for routing
   this.id(String.valueOf(randomInt.getAndAdd(1)));
   this.doc = documentBuilder.bytes();
   return this;
 }
Exemplo n.º 20
0
 /**
  * Add the given value to this reduction variable and return the previous value.
  *
  * @param value Value to add.
  * @return Previous value.
  */
 public int getAndAdd(int value) {
   return myValue.getAndAdd(value);
 }
Exemplo n.º 21
0
 public Tuple map(Object... args) {
   return PrototypedTuple.singleton(count.getAndAdd(1));
 }
Exemplo n.º 22
0
 public void run(int gid) {
   outArray[gid] = atomicInt.getAndAdd(0x7);
 }
Exemplo n.º 23
0
 @Override
 public int updateRecvWindow(int delta) {
   return recvWindow.getAndAdd(delta);
 }
Exemplo n.º 24
0
 public int generate() {
   return idGenerator.getAndAdd(gap);
 }
Exemplo n.º 25
0
 /** 1. 将AtomicInteger中维护的int值加上一个给定的值, 并且返回原来的int值 */
 public void testGetAndAdd() {
   AtomicInteger ai = new AtomicInteger(9);
   System.out.println(ai.getAndAdd(10)); // 9
 }
Exemplo n.º 26
0
 @Override
 public void onSuccess(AppendBatchAsyncResultPojo result) {
   flumeSuccessLogCount.getAndAdd(size);
   callback.onSuccess();
 }
Exemplo n.º 27
0
  public PrimitiveBench(String[] args) {
    int runs = 100000000;
    int cur = 0;
    if (args.length != 1) {
      System.out.println("usage: java " + getClass().getSimpleName() + " CASE_NUMBER");
      System.out.println("\twhere CASE_NUMBER is in {1,2,..,5}");
      System.exit(-1);
    }
    int caseno = Integer.parseInt(args[0]);
    boolean result1 = false, result2 = false;

    switch (caseno) {
        // case 1: break;
        // case 2: break;
        // case 3: break;
      case 4:
        {
          System.out.println("fetch and add");
          AtomicInteger addr = new AtomicInteger(0);
          for (int i = 0; i < runs; i++) {
            cur = addr.getAndAdd(1);
            cur = addr.getAndAdd(-1);
          }
          if (cur != 1) throw new RuntimeException("cur = " + cur);
          if (addr.get() != 0) throw new RuntimeException("addr.get() = " + addr.get());
        }
        break;
      case 5:
        {
          System.out.println("compare and swap");
          AtomicInteger addr = new AtomicInteger(0);
          for (int i = 0; i < runs; i++) {
            result1 = addr.compareAndSet(cur, cur + 1);
            result2 = addr.compareAndSet(cur + 1, cur);
          }
          if (!result1 || !result2)
            throw new RuntimeException("result1 = " + result1 + " result2 = " + result2);
          if (addr.get() != 0) throw new RuntimeException("addr.get() = " + addr.get());
        }
        break;
      case 6:
        {
          System.out.println("atomic updater cas");
          IntHolder addr = new IntHolder(0);
          AtomicIntegerFieldUpdater<IntHolder> updater =
              AtomicIntegerFieldUpdater.newUpdater(IntHolder.class, "v");
          for (int i = 0; i < runs; i++) {
            result1 = updater.compareAndSet(addr, cur, cur + 1);
            result2 = updater.compareAndSet(addr, cur + 1, cur);
          }
          if (!result1 || !result2)
            throw new RuntimeException("result1 = " + result1 + " result2 = " + result2);
          if (addr.v != 0) throw new RuntimeException("addr.v = " + addr.v);
        }
        break;
      default:
        {
          System.out.println("bad case number specified: " + caseno);
        }
        break;
    }
  }
Exemplo n.º 28
0
 @Override
 protected Integer initialValue() {
   return uniqueAddr.getAndAdd(TCP_PORT_RANGE_PER_THREAD);
 }
Exemplo n.º 29
0
 private void addBuildFilesToProcess(Set<Path> buildFiles) {
   Preconditions.checkArgument(buildFiles.size() > 0);
   Preconditions.checkState(pendingBuildTargets.size() == 0);
   pendingWorkQueueCount.getAndAdd(buildFiles.size());
   Preconditions.checkState(pendingBuildFiles.addAll(buildFiles));
 }
Exemplo n.º 30
0
 /** Constructor. */
 @SuppressWarnings("deprecation")
 protected ProcessStarter() {
   iProcessListener = new LinkedList<ProcessListener>();
   iProcessEventListener = new LinkedList<ProcessEventListener>();
   iPID = iPIDCounter.getAndAdd(1);
 }