Search in sources :

Example 16 with CanIgnoreReturnValue

use of com.google.errorprone.annotations.CanIgnoreReturnValue in project guava by google.

the class ConcurrentHashMultiset method setCount.

/**
   * Adds or removes occurrences of {@code element} such that the {@link #count} of the
   * element becomes {@code count}.
   *
   * @return the count of {@code element} in the multiset before this call
   * @throws IllegalArgumentException if {@code count} is negative
   */
@CanIgnoreReturnValue
@Override
public int setCount(E element, int count) {
    checkNotNull(element);
    checkNonnegative(count, "count");
    while (true) {
        AtomicInteger existingCounter = Maps.safeGet(countMap, element);
        if (existingCounter == null) {
            if (count == 0) {
                return 0;
            } else {
                existingCounter = countMap.putIfAbsent(element, new AtomicInteger(count));
                if (existingCounter == null) {
                    return 0;
                }
            // existingCounter != null: fall through
            }
        }
        while (true) {
            int oldValue = existingCounter.get();
            if (oldValue == 0) {
                if (count == 0) {
                    return 0;
                } else {
                    AtomicInteger newCounter = new AtomicInteger(count);
                    if ((countMap.putIfAbsent(element, newCounter) == null) || countMap.replace(element, existingCounter, newCounter)) {
                        return 0;
                    }
                }
                break;
            } else {
                if (existingCounter.compareAndSet(oldValue, count)) {
                    if (count == 0) {
                        // Just CASed to 0; remove the entry to clean up the map. If the removal fails,
                        // another thread has already replaced it with a new counter, which is fine.
                        countMap.remove(element, existingCounter);
                    }
                    return oldValue;
                }
            }
        }
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CanIgnoreReturnValue(com.google.errorprone.annotations.CanIgnoreReturnValue)

Example 17 with CanIgnoreReturnValue

use of com.google.errorprone.annotations.CanIgnoreReturnValue in project guava by google.

the class FuturesTest method pseudoTimedGetUninterruptibly.

/**
   * Very rough equivalent of a timed get, produced by calling the no-arg get method in another
   * thread and waiting a short time for it.
   *
   * <p>We need this to test the behavior of no-arg get methods without hanging the main test thread
   * forever in the case of failure.
   */
@CanIgnoreReturnValue
// threads
@GwtIncompatible
static <V> V pseudoTimedGetUninterruptibly(final Future<V> input, long timeout, TimeUnit unit) throws ExecutionException, TimeoutException {
    ExecutorService executor = newSingleThreadExecutor();
    Future<V> waiter = executor.submit(new Callable<V>() {

        @Override
        public V call() throws Exception {
            return input.get();
        }
    });
    try {
        return getUninterruptibly(waiter, timeout, unit);
    } catch (ExecutionException e) {
        propagateIfInstanceOf(e.getCause(), ExecutionException.class);
        propagateIfInstanceOf(e.getCause(), CancellationException.class);
        throw failureWithCause(e, "Unexpected exception");
    } finally {
        executor.shutdownNow();
    // TODO(cpovirk: assertTrue(awaitTerminationUninterruptibly(executor, 10, SECONDS));
    }
}
Also used : CancellationException(java.util.concurrent.CancellationException) ExecutorService(java.util.concurrent.ExecutorService) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) CancellationException(java.util.concurrent.CancellationException) FileNotFoundException(java.io.FileNotFoundException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) GwtIncompatible(com.google.common.annotations.GwtIncompatible) CanIgnoreReturnValue(com.google.errorprone.annotations.CanIgnoreReturnValue)

Example 18 with CanIgnoreReturnValue

use of com.google.errorprone.annotations.CanIgnoreReturnValue in project guava by google.

the class AbstractFuture method cancel.

/**
   * {@inheritDoc}
   *
   * <p>If a cancellation attempt succeeds on a {@code Future} that had previously been {@linkplain
   * #setFuture set asynchronously}, then the cancellation will also be propagated to the delegate
   * {@code Future} that was supplied in the {@code setFuture} call.
   */
@CanIgnoreReturnValue
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
    Object localValue = value;
    boolean rValue = false;
    if (localValue == null | localValue instanceof SetFuture) {
        // Try to delay allocating the exception. At this point we may still lose the CAS, but it is
        // certainly less likely.
        Throwable cause = GENERATE_CANCELLATION_CAUSES ? new CancellationException("Future.cancel() was called.") : null;
        Object valueToSet = new Cancellation(mayInterruptIfRunning, cause);
        AbstractFuture<?> abstractFuture = this;
        while (true) {
            if (ATOMIC_HELPER.casValue(abstractFuture, localValue, valueToSet)) {
                rValue = true;
                // FutureTask
                if (mayInterruptIfRunning) {
                    abstractFuture.interruptTask();
                }
                complete(abstractFuture);
                if (localValue instanceof SetFuture) {
                    // propagate cancellation to the future set in setfuture, this is racy, and we don't
                    // care if we are successful or not.
                    ListenableFuture<?> futureToPropagateTo = ((SetFuture) localValue).future;
                    if (futureToPropagateTo instanceof TrustedFuture) {
                        // If the future is a TrustedFuture then we specifically avoid calling cancel()
                        // this has 2 benefits
                        // 1. for long chains of futures strung together with setFuture we consume less stack
                        // 2. we avoid allocating Cancellation objects at every level of the cancellation
                        //    chain
                        // We can only do this for TrustedFuture, because TrustedFuture.cancel is final and
                        // does nothing but delegate to this method.
                        AbstractFuture<?> trusted = (AbstractFuture<?>) futureToPropagateTo;
                        localValue = trusted.value;
                        if (localValue == null | localValue instanceof SetFuture) {
                            abstractFuture = trusted;
                            // loop back up and try to complete the new future
                            continue;
                        }
                    } else {
                        // not a TrustedFuture, call cancel directly.
                        futureToPropagateTo.cancel(mayInterruptIfRunning);
                    }
                }
                break;
            }
            // obj changed, reread
            localValue = abstractFuture.value;
            if (!(localValue instanceof SetFuture)) {
                // since it isn't a SetFuture, then the future must be done and we should exit the loop
                break;
            }
        }
    }
    return rValue;
}
Also used : CancellationException(java.util.concurrent.CancellationException) CanIgnoreReturnValue(com.google.errorprone.annotations.CanIgnoreReturnValue)

Example 19 with CanIgnoreReturnValue

use of com.google.errorprone.annotations.CanIgnoreReturnValue in project guava by google.

the class AbstractService method stopAsync.

@CanIgnoreReturnValue
@Override
public final Service stopAsync() {
    if (monitor.enterIf(isStoppable)) {
        try {
            State previous = state();
            switch(previous) {
                case NEW:
                    snapshot = new StateSnapshot(TERMINATED);
                    enqueueTerminatedEvent(NEW);
                    break;
                case STARTING:
                    snapshot = new StateSnapshot(STARTING, true, null);
                    enqueueStoppingEvent(STARTING);
                    break;
                case RUNNING:
                    snapshot = new StateSnapshot(STOPPING);
                    enqueueStoppingEvent(RUNNING);
                    doStop();
                    break;
                case STOPPING:
                case TERMINATED:
                case FAILED:
                    // These cases are impossible due to the if statement above.
                    throw new AssertionError("isStoppable is incorrectly implemented, saw: " + previous);
                default:
                    throw new AssertionError("Unexpected state: " + previous);
            }
        } catch (Throwable shutdownFailure) {
            notifyFailed(shutdownFailure);
        } finally {
            monitor.leave();
            dispatchListenerEvents();
        }
    }
    return this;
}
Also used : Preconditions.checkState(com.google.common.base.Preconditions.checkState) State(com.google.common.util.concurrent.Service.State) CanIgnoreReturnValue(com.google.errorprone.annotations.CanIgnoreReturnValue)

Example 20 with CanIgnoreReturnValue

use of com.google.errorprone.annotations.CanIgnoreReturnValue in project guava by google.

the class AtomicLongMap method getAndUpdate.

/**
   * Updates the value currently associated with {@code key} with the specified function,
   * and returns the old value.  If there is not currently a value associated with {@code key},
   * the function is applied to {@code 0L}.
   *
   * @since 21.0
   */
@CanIgnoreReturnValue
public long getAndUpdate(K key, LongUnaryOperator updaterFunction) {
    checkNotNull(updaterFunction);
    AtomicLong holder = new AtomicLong();
    map.compute(key, (k, value) -> {
        long oldValue = (value == null) ? 0L : value.longValue();
        holder.set(oldValue);
        return updaterFunction.applyAsLong(oldValue);
    });
    return holder.get();
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) CanIgnoreReturnValue(com.google.errorprone.annotations.CanIgnoreReturnValue)

Aggregations

CanIgnoreReturnValue (com.google.errorprone.annotations.CanIgnoreReturnValue)25 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 BufferedInputStream (java.io.BufferedInputStream)3 BufferedReader (java.io.BufferedReader)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 InputStream (java.io.InputStream)3 Reader (java.io.Reader)3 Beta (com.google.common.annotations.Beta)2 Preconditions.checkState (com.google.common.base.Preconditions.checkState)2 State (com.google.common.util.concurrent.Service.State)2 OutputStream (java.io.OutputStream)2 Writer (java.io.Writer)2 CharBuffer (java.nio.CharBuffer)2 CancellationException (java.util.concurrent.CancellationException)2 GwtIncompatible (com.google.common.annotations.GwtIncompatible)1 REUSING_EDGE (com.google.common.graph.GraphConstants.REUSING_EDGE)1 Any (com.google.protobuf.Any)1 ChannelFuture (io.netty.channel.ChannelFuture)1 Query (io.spine.client.Query)1 Subscription (io.spine.client.Subscription)1