Java Code Examples for java.util.concurrent.atomic.AtomicInteger#getAndIncrement()

The following examples show how to use java.util.concurrent.atomic.AtomicInteger#getAndIncrement() . These examples are extracted from open source projects. 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
/**
 * Inserts the specified element at the tail of this queue if it is
 * possible to do so immediately without exceeding the queue's capacity,
 * returning {@code true} upon success and {@code false} if this queue
 * is full.
 * When using a capacity-restricted queue, this method is generally
 * preferable to method {@link BlockingQueue#add add}, which can fail to
 * insert an element only by throwing an exception.
 *
 * @throws NullPointerException if the specified element is null
 */
public boolean offer(E e) {
    if (e == null) throw new NullPointerException();
    final AtomicInteger count = this.count;
    if (count.get() == capacity)
        return false;
    int c = -1;
    Node<E> node = new Node<E>(e);
    final ReentrantLock putLock = this.putLock;
    putLock.lock();
    try {
        if (count.get() < capacity) {
            enqueue(node);
            c = count.getAndIncrement();
            if (c + 1 < capacity)
                notFull.signal();
        }
    } finally {
        putLock.unlock();
    }
    if (c == 0)
        signalNotEmpty();
    return c >= 0;
}
 
Example 2
@Group("g5")
@GroupThreads(3)
@Benchmark
public void queueDrainAtomic5() {
    AtomicInteger w = wip;
    if (w.compareAndSet(0, 1) || w.getAndIncrement() == 0) {
        int missed = 1;

        for (;;) {
            counter++;

            if (w.compareAndSet(missed, 0)) {
                break;
            }
            missed = w.get();
        }
    }
}
 
Example 3
/**
 * Inserts the specified element at the tail of this queue if it is
 * possible to do so immediately without exceeding the queue's capacity,
 * returning {@code true} upon success and {@code false} if this queue
 * is full.
 * When using a capacity-restricted queue, this method is generally
 * preferable to method {@link BlockingQueue#add add}, which can fail to
 * insert an element only by throwing an exception.
 *
 * @throws NullPointerException if the specified element is null
 */
public boolean offer(E e) {
    if (e == null) throw new NullPointerException();
    final AtomicInteger count = this.count;
    if (count.get() == capacity)
        return false;
    int c = -1;
    Node<E> node = new Node<E>(e);
    final ReentrantLock putLock = this.putLock;
    putLock.lock();
    try {
        if (count.get() < capacity) {
            enqueue(node);
            c = count.getAndIncrement();
            if (c + 1 < capacity)
                notFull.signal();
        }
    } finally {
        putLock.unlock();
    }
    if (c == 0)
        signalNotEmpty();
    return c >= 0;
}
 
Example 4
/**
 * Inserts the specified element at the tail of this queue even
 * if the queue is currently at its capacity.
 // GEMFIRE addition
 */
public void forcePut(E e) throws InterruptedException {
    if (e == null) throw new NullPointerException();
    // Note: convention in all put/take/etc is to preset local var
    // holding count negative to indicate failure unless set.
    int c = -1;
    final ReentrantLock putLock = this.putLock;
    final AtomicInteger count = this.count;
    putLock.lockInterruptibly();
    try {
        enqueue(e);
        c = count.getAndIncrement();
        if (c + 1 < capacity)
            notFull.signal();
    } finally {
        putLock.unlock();
    }
    if (c == 0)
        signalNotEmpty();
}
 
Example 5
@Test
public void normal() {
    final AtomicInteger count = new AtomicInteger();

    Cancellable c = new Cancellable() {
        @Override
        public void cancel() throws Exception {
            count.getAndIncrement();
        }
    };

    CancellableDisposable cd = new CancellableDisposable(c);

    assertFalse(cd.isDisposed());

    cd.dispose();
    cd.dispose();

    assertTrue(cd.isDisposed());

    assertEquals(1, count.get());
}
 
Example 6
protected Optional<InstanceInfo> roundRobinInstanceList(String vipName, List<InstanceInfo> instanceList) {
    // Found at least one "up" instance at this VIP. Grab the AtomicInteger associated with this VIP
    //      (map a new one if necessary).
    AtomicInteger roundRobinCounter = vipRoundRobinCounterMap.computeIfAbsent(vipName, vip -> new AtomicInteger(0));

    // Atomically get-and-increment the atomic int associated with this VIP, then mod it against the number of
    //      instances available. This effectively round robins the use of all the instances associated with the VIP.
    int instanceIndexToUse = roundRobinCounter.getAndIncrement() % instanceList.size();

    if (instanceIndexToUse < 0) {
        // The counter went high enough to do an integer overflow. Fix the index so we don't blow up this call,
        //      and reset the counter to 0.
        instanceIndexToUse = Math.abs(instanceIndexToUse);
        roundRobinCounter.set(0);
    }

    return Optional.of(instanceList.get(instanceIndexToUse));
}
 
Example 7
/** Creates a new unsused attribute name with a given prefix. */
public static String createName(String prefix) {
	AtomicInteger counter = nameCounters.get(prefix);
	if (counter == null) {
		nameCounters.put(prefix, new AtomicInteger(1));
		return prefix;
	} else {
		return prefix + counter.getAndIncrement();
	}
}
 
Example 8
@Test
public void testSyncIndexCleared() throws Exception {
   System.out.println("================================= test testSyncIndexCleared ===========");
   final AtomicInteger beforeEndCountA = new AtomicInteger(0);
   final AtomicInteger rollbackCountA = new AtomicInteger(0);
   Synchronization sync = new Synchronization() {
      @Override
      public void beforeEnd() throws Exception {
         beforeEndCountA.getAndIncrement();
      }

      @Override
      public void afterCommit() throws Exception {
         fail("expected rollback exception");
      }

      @Override
      public void afterRollback() throws Exception {
         rollbackCountA.incrementAndGet();
      }
   };

   underTest.begin();
   underTest.addSynchronization(sync);
   underTest.rollback();

   assertEquals("beforeEnd", 1, beforeEndCountA.get());
   assertEquals("rollback", 1, rollbackCountA.get());

   // do it again
   underTest.begin();
   underTest.addSynchronization(sync);
   underTest.rollback();

   assertEquals("beforeEnd", 2, beforeEndCountA.get());
   assertEquals("rollback", 2, rollbackCountA.get());
}
 
Example 9
Source Project: jkube   File: AnsiLoggerFacade.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void updateNonAnsiProgress(String imageId) {
    AtomicInteger count = updateCount.get();
    int nr = count.getAndIncrement();
    if (nr % NON_ANSI_UPDATE_PERIOD == 0) {
        print("#");
    }
    if (nr > 0 && nr % (80 * NON_ANSI_UPDATE_PERIOD) == 0) {
        print("\n");
    }
}
 
Example 10
Source Project: jkube   File: AnsiLogger.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void updateNonAnsiProgress() {
    AtomicInteger count = updateCount.get();
    int nr = count.getAndIncrement();
    if (nr % NON_ANSI_UPDATE_PERIOD == 0) {
        print("#");
    }
    if (nr > 0 && nr % (80 * NON_ANSI_UPDATE_PERIOD) == 0) {
        print("\n");
    }
}
 
Example 11
/**
 * Inserts the specified element at the tail of this queue, waiting if
 * necessary for space to become available.
 *
 * @throws InterruptedException {@inheritDoc}
 * @throws NullPointerException {@inheritDoc}
 */
public void put(E e) throws InterruptedException {
    if (e == null) throw new NullPointerException();
    // Note: convention in all put/take/etc is to preset local var
    // holding count negative to indicate failure unless set.
    int c = -1;
    Node<E> node = new Node<E>(e);
    final ReentrantLock putLock = this.putLock;
    final AtomicInteger count = this.count;
    putLock.lockInterruptibly();
    try {
        /*
         * Note that count is used in wait guard even though it is
         * not protected by lock. This works because count can
         * only decrease at this point (all other puts are shut
         * out by lock), and we (or some other waiting put) are
         * signalled if it ever changes from capacity. Similarly
         * for all other uses of count in other wait guards.
         */
        while (count.get() == capacity) {
            notFull.await();
        }
        enqueue(node);
        c = count.getAndIncrement();
        if (c + 1 < capacity)
            notFull.signal();
    } finally {
        putLock.unlock();
    }
    if (c == 0)
        signalNotEmpty();
}
 
Example 12
/**
 * Tests the AsyncReadResultProcessor on catch-up reads (that are already available in memory).
 */
@Test
public void testCatchUpReads() throws Exception {
    // Pre-generate some entries.
    ArrayList<byte[]> entries = new ArrayList<>();
    int totalLength = generateEntries(entries);

    // Setup an entry provider supplier.
    AtomicInteger currentIndex = new AtomicInteger();
    StreamSegmentReadResult.NextEntrySupplier supplier = (offset, length) -> {
        int idx = currentIndex.getAndIncrement();
        if (idx >= entries.size()) {
            return null;
        }

        return new CacheReadResultEntry(offset, entries.get(idx), 0, entries.get(idx).length);
    };

    // Start an AsyncReadResultProcessor.
    @Cleanup
    StreamSegmentReadResult rr = new StreamSegmentReadResult(0, totalLength, supplier, "");
    TestReadResultHandler testReadResultHandler = new TestReadResultHandler(entries);
    try (AsyncReadResultProcessor rp = AsyncReadResultProcessor.process(rr, testReadResultHandler, executorService())) {
        // Wait for it to complete, and then verify that no errors have been recorded via the callbacks.
        testReadResultHandler.completed.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);

        if (testReadResultHandler.error.get() != null) {
            Assert.fail("Read failure: " + testReadResultHandler.error.get().toString());
        }

        Assert.assertEquals("Unexpected number of reads processed.", entries.size(), testReadResultHandler.readCount.get());
    }

    Assert.assertTrue("ReadResult was not closed when the AsyncReadResultProcessor was closed.", rr.isClosed());
}
 
Example 13
Source Project: fresco   File: DraweeMocks.java    License: MIT License 5 votes vote down vote up
/**
 * Creates a supplier of T.
 *
 * @param values values to return on {@code get()}
 * @return supplier of T
 */
public static <T> Supplier<T> supplierOf(final T... values) {
  final AtomicInteger index = new AtomicInteger(0);
  return new Supplier<T>() {
    @Override
    public T get() {
      if (index.get() < values.length) {
        return values[index.getAndIncrement()];
      } else {
        return values[values.length - 1];
      }
    }
  };
}
 
Example 14
/**
 * Inserts the specified element at the tail of this queue, waiting if
 * necessary up to the specified wait time for space to become available.
 *
 * @return {@code true} if successful, or {@code false} if
 *         the specified waiting time elapses before space is available.
 * @throws InterruptedException {@inheritDoc}
 * @throws NullPointerException {@inheritDoc}
 */
public boolean offer(E e, long timeout, TimeUnit unit)
    throws InterruptedException {

    if (e == null) throw new NullPointerException();
    long nanos = unit.toNanos(timeout);
    int c = -1;
    final ReentrantLock putLock = this.putLock;
    final AtomicInteger count = this.count;
    putLock.lockInterruptibly();
    try {
        while (count.get() >= capacity) { // GEMFIRE changed == to >=
            if (nanos <= 0)
                return false;
            nanos = notFull.awaitNanos(nanos);
        }
        enqueue(e);
        c = count.getAndIncrement();
        if (c + 1 < capacity)
            notFull.signal();
    } finally {
        putLock.unlock();
    }
    if (c == 0)
        signalNotEmpty();
    return true;
}
 
Example 15
@Before
public void setup() {
  this.newList = new ArrayList<>();
  // Used to uniquely identify sub-codecs.
  final AtomicInteger subCodecIdentifier = new AtomicInteger(0);

  final Supplier<ArrayList> listSupplier = () -> new ArrayList<>(5);
  final Supplier<AsnSequenceCodec<Integer>> subCodecSupplier
      = () -> new TestSubCodec(subCodecIdentifier.getAndIncrement());

  codec = new AsnSequenceOfSequenceCodec(listSupplier, subCodecSupplier);
}
 
Example 16
Source Project: Paguro   File: Fn3Test.java    License: Apache License 2.0 5 votes vote down vote up
@Test public void memoize() {
    AtomicInteger counter = new AtomicInteger(0);
    Fn3<Boolean,Integer,Double,String> f = (b, l, d) -> {
        counter.getAndIncrement();
        return (b ? "+" : "-") + String.valueOf(l) + "~" + String.valueOf(d);
    };
    Fn3<Boolean,Integer,Double,String> g = Fn3.memoize(f);
    assertEquals("+3~2.5", g.apply(true, 3, 2.5));
    assertEquals(1, counter.get());
    assertEquals("+3~2.5", g.apply(true, 3, 2.5));
    assertEquals(1, counter.get());

    assertEquals("+3~2.5", f.apply(true, 3, 2.5));
    assertEquals(2, counter.get());

    assertEquals("+3~2.5", g.apply(true, 3, 2.5));
    assertEquals(2, counter.get());

    assertEquals("-5~4.3", g.apply(false, 5, 4.3));
    assertEquals(3, counter.get());
    assertEquals("+3~2.5", g.apply(true, 3, 2.5));
    assertEquals(3, counter.get());
    assertEquals("-5~4.3", g.apply(false, 5, 4.3));
    assertEquals(3, counter.get());
    assertEquals("+3~2.5", g.apply(true, 3, 2.5));
    assertEquals(3, counter.get());
}
 
Example 17
Source Project: FirefoxReality   File: Session.java    License: Mozilla Public License 2.0 4 votes vote down vote up
@Override
public @Nullable GeckoResult<AllowOrDeny> onLoadRequest(@NonNull GeckoSession aSession, @NonNull LoadRequest aRequest) {
    String uri = aRequest.uri;

    Log.d(LOGTAG, "onLoadRequest: " + uri);

    if (aSession == mState.mSession) {
        Log.d(LOGTAG, "Testing for UA override");

        final String userAgentOverride = sUserAgentOverride.lookupOverride(uri);
        aSession.getSettings().setUserAgentOverride(userAgentOverride);
        if (mState.mSettings != null) {
            mState.mSettings.setUserAgentOverride(userAgentOverride);
        }
    }

    if (mContext.getString(R.string.about_private_browsing).equalsIgnoreCase(uri)) {
        return GeckoResult.DENY;
    }

    if (mNavigationListeners.size() == 0) {
        return GeckoResult.ALLOW;
    }

    final GeckoResult<AllowOrDeny> result = new GeckoResult<>();
    AtomicInteger count = new AtomicInteger(0);
    AtomicBoolean allowed = new AtomicBoolean(true);
    final int listenerCount = mNavigationListeners.size() - 1;
    for (GeckoSession.NavigationDelegate listener: mNavigationListeners) {
        GeckoResult<AllowOrDeny> listenerResult = listener.onLoadRequest(aSession, aRequest);
        if (listenerResult != null) {
            listenerResult.then(value -> {
                if (AllowOrDeny.DENY.equals(value)) {
                    allowed.set(false);
                }
                if (count.getAndIncrement() == listenerCount) {
                    result.complete(allowed.get() ? AllowOrDeny.ALLOW : AllowOrDeny.DENY);
                }

                return null;
            });

        } else {
            allowed.set(true);
            if (count.getAndIncrement() == listenerCount) {
                result.complete(allowed.get() ? AllowOrDeny.ALLOW : AllowOrDeny.DENY);
            }
        }
    }

    if (UrlUtils.isAboutPage(aRequest.uri)) {
        return GeckoResult.DENY;
    }

    return result;
}
 
Example 18
void test(String[] args) {
    final String name = "myLogger";
    final String message = "myMessage";
    final AtomicInteger getHandlerCount = new AtomicInteger(0);
    final AtomicLong lastSequenceNumber = new AtomicLong(-1L);
    final AtomicInteger lastThreadID = new AtomicInteger(-1);
    final Logger logger = new Logger(name, null) {
        public Handler[] getHandlers() {
            getHandlerCount.getAndIncrement();
            return super.getHandlers();
        }};
    equal(logger.getName(), name);
    equal(logger.getResourceBundle(), null);
    equal(logger.getFilter(), null);
    equal(logger.getLevel(), null);
    check(logger.isLoggable(Level.WARNING));
    logger.addHandler(new Handler() {
        public void close() {}
        public void flush() {}
        public void publish(LogRecord l) {
            equal(l.getLoggerName(), name);
            equal(l.getMessage(), message);
            equal(l.getResourceBundle(), null);
            equal(l.getSourceClassName(), "LoggerSubclass");
            equal(l.getSourceMethodName(), "test");
            equal(l.getThrown(), null);
            equal(l.getLevel(), Level.WARNING);

            if (lastSequenceNumber.get() != -1) {
                equal(lastSequenceNumber.get() + 1,
                      l.getSequenceNumber());
                equal(lastThreadID.get(),
                      l.getThreadID());
                equal((int) Thread.currentThread().getId(),
                      l.getThreadID());
            }
            lastSequenceNumber.set(l.getSequenceNumber());
            lastThreadID.set(l.getThreadID());
        }});
    for (int i = 1; i < 4; i++) {
        logger.warning(message); // Should invoke getHandlers()
        equal(i, getHandlerCount.get());
    }
}
 
Example 19
Source Project: aion   File: BlockPropagationTest.java    License: MIT License 4 votes vote down vote up
@Test
public void testIgnoreSameBlock() {
    List<ECKey> accounts = generateDefaultAccounts();

    StandaloneBlockchain.Bundle bundle =
            new StandaloneBlockchain.Builder()
                    .withValidatorConfiguration("simple")
                    .withDefaultAccounts(accounts)
                    .build();

    MiningBlock block =
            bundle.bc.createNewMiningBlock(bundle.bc.getGenesis(), Collections.EMPTY_LIST, true);
    assertThat(block.getNumber()).isEqualTo(1);

    byte[] sender = HashUtil.h256("node1".getBytes());
    byte[] receiver = HashUtil.h256("receiver".getBytes());

    NodeMock senderMock = new NodeMock(sender, 1);
    NodeMock receiverMock = new NodeMock(receiver, 0);

    Map<Integer, INode> node = new HashMap<>();
    node.put(1, senderMock);
    node.put(2, receiverMock);

    AtomicInteger times = new AtomicInteger();
    P2pMock p2pMock =
            new P2pMock(node) {
                @Override
                public void send(int _nodeId, String s, Msg _msg) {
                    if (_nodeId != receiverMock.getIdHash()) {
                        throw new RuntimeException("should only send to receiver");
                    }
                    times.getAndIncrement();
                }
            };

    StandaloneBlockchain.Bundle anotherBundle =
            new StandaloneBlockchain.Builder()
                    .withValidatorConfiguration("simple")
                    .withDefaultAccounts(accounts)
                    .withEventManger(this.loadEventMgr())
                    .build();
    assertThat(bundle.bc.genesis.getHash()).isEqualTo(anotherBundle.bc.genesis.getHash());

    SyncStats syncStats = new SyncStats(bundle.bc.getBestBlock().getNumber(), true);
    BlockPropagationHandler handler =
            new BlockPropagationHandler(
                    1024,
                    anotherBundle.bc, // NOTE: not the same blockchain that generated the block
                    syncStats,
                    p2pMock,
                    anotherBundle.bc.getBlockHeaderValidator(),
                    false,
                    (byte) 2,
                    new AionPendingStateImpl(
                            anotherBundle.bc,
                            blockEnergyUpperBound,
                            pendingTransactionTimeout,
                            enablePoolBackup,
                            enableSeedMode,
                            enablePoolDump,
                            new PendingTxCallback(new ArrayList<>()),
                            new NetworkBestBlockCallback(AionImpl.inst()),
                            new TransactionBroadcastCallback(AionImpl.inst()),
                            true));
    // block is processed
    assertThat(handler.processIncomingBlock(senderMock.getIdHash(), "test", block))
            .isEqualTo(BlockPropagationHandler.PropStatus.PROP_CONNECTED);
    assertThat(handler.processIncomingBlock(senderMock.getIdHash(), "test", block))
            .isEqualTo(BlockPropagationHandler.PropStatus.DROPPED);
    assertThat(times.get()).isEqualTo(1);
}
 
Example 20
final public static void mean( final Image< LongType> integralImg, final Image< FloatType > domImg, final int sx, final int sy, final int sz )
{
	final float sumPixels = sx * sy * sz;
	
	final int sxHalf = sx / 2;
	final int syHalf = sy / 2;
	final int szHalf = sz / 2;

	final int w = domImg.getDimension( 0 ) - ( sx / 2 ) * 2; // this makes sense as sx is odd
	final int h = domImg.getDimension( 1 ) - ( sy / 2 ) * 2;
	final int d = domImg.getDimension( 2 ) - ( sz / 2 ) * 2;

	final AtomicInteger ai = new AtomicInteger(0);					
       final Thread[] threads = SimpleMultiThreading.newThreads();
	final int numThreads = threads.length;
       
       for (int ithread = 0; ithread < threads.length; ++ithread)
           threads[ithread] = new Thread(new Runnable()
           {
               public void run()
               {
               	// Thread ID
               	final int myNumber = ai.getAndIncrement();

           		// for each computation we need 8 randomaccesses, so 16 all together
           		final LocalizableByDimCursor< LongType > r1 = integralImg.createLocalizableByDimCursor();
           		final LocalizableByDimCursor< LongType > r2 = integralImg.createLocalizableByDimCursor();
           		final LocalizableByDimCursor< LongType > r3 = integralImg.createLocalizableByDimCursor();
           		final LocalizableByDimCursor< LongType > r4 = integralImg.createLocalizableByDimCursor();
           		final LocalizableByDimCursor< LongType > r5 = integralImg.createLocalizableByDimCursor();
           		final LocalizableByDimCursor< LongType > r6 = integralImg.createLocalizableByDimCursor();
           		final LocalizableByDimCursor< LongType > r7 = integralImg.createLocalizableByDimCursor();
           		final LocalizableByDimCursor< LongType > r8 = integralImg.createLocalizableByDimCursor();
           		
           		final LocalizableByDimCursor< FloatType > result = domImg.createLocalizableByDimCursor();
           		
           		final int[] p = new int[ 3 ];

           		for ( int z = 0; z < d; ++z )
           		{
           			if ( z % numThreads == myNumber )
           			{
            			for ( int y = 0; y < h; ++y )
            			{
            				// set the result randomaccess
            				p[ 0 ] = sxHalf; p[ 1 ] = y + syHalf; p[ 2 ] = z + szHalf;
            				result.setPosition( p );
            				
            				// set all randomaccess for the first box accordingly
            				p[ 0 ] = 0; p[ 1 ] = y; p[ 2 ] = z;
            				r1.setPosition( p ); // negative

            				p[ 0 ] += sx;
            				r2.setPosition( p ); // positive
            				
            				p[ 1 ] += sy;
            				r3.setPosition( p ); // negative
            				
            				p[ 0 ] -= sx;
            				r4.setPosition( p ); // positive

            				p[ 2 ] += sz;
            				r5.setPosition( p ); // negative

            				p[ 0 ] += sx;
            				r6.setPosition( p ); // positive

            				p[ 1 ] -= sy;
            				r7.setPosition( p ); // negative

            				p[ 0 ] -= sx;
            				r8.setPosition( p ); // positive

            				for ( int x = 0; x < w; ++x )
            				{
            					final long s = -r1.getType().get() + r2.getType().get() - r3.getType().get() + r4.getType().get() - r5.getType().get() + r6.getType().get() - r7.getType().get() + r8.getType().get();

            					result.getType().set( (float)s/sumPixels );
            					
            					r1.fwd( 0 ); r2.fwd( 0 ); r3.fwd( 0 ); r4.fwd( 0 ); r5.fwd( 0 ); r6.fwd( 0 ); r7.fwd( 0 ); r8.fwd( 0 );
            					result.fwd( 0 );
            				}
            			}
           			}
           		}            		
               }
           });

       SimpleMultiThreading.startAndJoin( threads );
	}