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

The following examples show how to use java.util.concurrent.atomic.AtomicInteger#updateAndGet() . 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: Main.java    From Java-Coding-Problems with MIT License 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {

        System.out.println("updateAndGet(), accumulateAndGet():");
        AtomicIntegerArray atomicArray = new AtomicIntegerArray(new int[]{3, 4, 2, 5});
        for (int i = 0; i < atomicArray.length(); i++) {
            atomicArray.updateAndGet(i, elem -> elem * elem);
        }
        System.out.println("Result: " + atomicArray);

        AtomicInteger nr1 = new AtomicInteger(3);
        int result1 = nr1.accumulateAndGet(5, (x, y) -> x * y); // x = 3, y = 5

        AtomicInteger nr2 = new AtomicInteger(3);
        int result2 = nr2.updateAndGet(x -> 5 * x);

        System.out.println("Result (nr1): " + result1);
        System.out.println("Result (nr2): " + result2);

        System.out.println("\naddAndGet():");
        AtomicInteger nr3 = new AtomicInteger(3);
        int result3 = nr3.addAndGet(4);
        System.out.println("Result (nr3): " + result3);

        System.out.println("\ncompareAndSet():");
        AtomicInteger nr4 = new AtomicInteger(3);
        boolean wasSet = nr4.compareAndSet(3, 5);
        System.out.println("Result (nr4): " + nr4.get() + " Was set: " + wasSet);
    }
 
Example 2
Source File: DefaultUidGeneratorTest.java    From prong-uid with Apache License 2.0 5 votes vote down vote up
/**
 * Worker run
 */
private void workerRun(Set<Long> uidSet, AtomicInteger control) {
    for (;;) {
        int myPosition = control.updateAndGet(old -> (old == SIZE ? SIZE : old + 1));
        if (myPosition == SIZE) {
            return;
        }

        doGenerate(uidSet, myPosition);
    }
}
 
Example 3
Source File: CachedUidGeneratorTest.java    From prong-uid with Apache License 2.0 5 votes vote down vote up
/**
 * Woker run
 */
private void workerRun(Set<Long> uidSet, AtomicInteger control) {
    for (;;) {
        int myPosition = control.updateAndGet(old -> (old == SIZE ? SIZE : old + 1));
        if (myPosition == SIZE) {
            return;
        }

        doGenerate(uidSet, myPosition);
    }
}
 
Example 4
Source File: SnowflakeUidGeneratorTests.java    From snowflake-uid with MIT License 5 votes vote down vote up
/**
 * Worker run
 */
private void workerRun(Set<Long> uidSet, AtomicInteger control) {
    for (;;) {
        int myPosition = control.updateAndGet(old -> (old == SIZE ? SIZE : old + 1));
        if (myPosition == SIZE) {
            return;
        }

        doGenerate(uidSet, myPosition);
    }
}
 
Example 5
Source File: DefaultUidGeneratorTest.java    From uid-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Worker run
 */
private void workerRun(Set<Long> uidSet, AtomicInteger control) {
    for (;;) {
        int myPosition = control.updateAndGet(old -> (old == SIZE ? SIZE : old + 1));
        if (myPosition == SIZE) {
            return;
        }

        doGenerate(uidSet, myPosition);
    }
}
 
Example 6
Source File: CachedUidGeneratorTest.java    From uid-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Woker run
 */
private void workerRun(Set<Long> uidSet, AtomicInteger control) {
    for (;;) {
        int myPosition = control.updateAndGet(old -> (old == SIZE ? SIZE : old + 1));
        if (myPosition == SIZE) {
            return;
        }

        doGenerate(uidSet, myPosition);
    }
}
 
Example 7
Source File: Kernel.java    From OSPREY3 with GNU General Public License v2.0 5 votes vote down vote up
public int getBestBlockThreads(AtomicInteger blockThreads) {
	return blockThreads.updateAndGet((int val) -> {
		if (val == -1) {
			val = calcMaxBlockThreads();
		}
		return val;
	});
}
 
Example 8
Source File: ThriftHiveMetastore.java    From presto with Apache License 2.0 4 votes vote down vote up
@SafeVarargs
private final <T> T alternativeCall(
        ClientSupplier clientSupplier,
        Predicate<Exception> isValidExceptionalResponse,
        AtomicInteger chosenAlternative,
        Call<T>... alternatives)
        throws TException
{
    checkArgument(alternatives.length > 0, "No alternatives");
    int chosen = chosenAlternative.get();
    checkArgument(chosen == Integer.MAX_VALUE || (0 <= chosen && chosen < alternatives.length), "Bad chosen alternative value: %s", chosen);

    if (chosen != Integer.MAX_VALUE) {
        try (ThriftMetastoreClient client = clientSupplier.createMetastoreClient()) {
            return alternatives[chosen].callOn(client);
        }
    }

    Exception firstException = null;
    for (int i = 0; i < alternatives.length; i++) {
        int position = i;
        try (ThriftMetastoreClient client = clientSupplier.createMetastoreClient()) {
            T result = alternatives[i].callOn(client);
            chosenAlternative.updateAndGet(currentChosen -> Math.min(currentChosen, position));
            return result;
        }
        catch (TException | RuntimeException exception) {
            if (isValidExceptionalResponse.test(exception)) {
                // This is likely a valid response. We are not settling on an alternative yet.
                // We will do it later when we get a more obviously valid response.
                throw exception;
            }
            if (firstException == null) {
                firstException = exception;
            }
            else if (firstException != exception) {
                firstException.addSuppressed(exception);
            }
        }
    }

    verifyNotNull(firstException);
    propagateIfPossible(firstException, TException.class);
    throw propagate(firstException);
}
 
Example 9
Source File: LookAheadInfo.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected void checkConsistency(ILeafNode node, AtomicInteger currentLookAhead) {
	if (!node.isHidden()) {
		currentLookAhead.updateAndGet(old->old > 0 ? old - 1 : old);
	}
}
 
Example 10
Source File: ExtendedResolver.java    From dnsjava with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private Void handle(Message result, Throwable ex, CompletableFuture<Message> f) {
  AtomicInteger failureCounter = resolvers.get(currentResolver).failures;
  if (ex != null) {
    log.debug(
        "Failed to resolve {}/{}, id={} with resolver {} ({}) on attempt {} of {}, reason={}",
        query.getQuestion().getName(),
        Type.string(query.getQuestion().getType()),
        query.getHeader().getID(),
        currentResolver,
        resolvers.get(currentResolver).resolver,
        attempts[currentResolver],
        retriesPerResolver,
        ex.getMessage());

    failureCounter.incrementAndGet();

    if (endTime - System.nanoTime() < 0) {
      f.completeExceptionally(
          new IOException(
              "Timed out while trying to resolve "
                  + query.getQuestion().getName()
                  + "/"
                  + Type.string(query.getQuestion().type)
                  + ", id="
                  + query.getHeader().getID()));
    } else {
      // go to next resolver, until retries on all resolvers are exhausted
      currentResolver = (currentResolver + 1) % resolvers.size();
      if (attempts[currentResolver] < retriesPerResolver) {
        send().handleAsync((r, t) -> handle(r, t, f));
        return null;
      }

      f.completeExceptionally(ex);
    }
  } else {
    failureCounter.updateAndGet(i -> i > 0 ? (int) Math.log(i) : 0);
    f.complete(result);
  }

  return null;
}