com.google.common.annotations.GwtIncompatible Java Examples

The following examples show how to use com.google.common.annotations.GwtIncompatible. 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: Callables.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Wraps the given callable such that for the duration of {@link Callable#call} the thread that is
 * running will have the given name.
 *
 *
 * @param callable The callable to wrap
 * @param nameSupplier The supplier of thread names, {@link Supplier#get get} will be called once
 *     for each invocation of the wrapped callable.
 */
@GwtIncompatible // threads
static <T> Callable<T> threadRenaming(
    final Callable<T> callable, final Supplier<String> nameSupplier) {
  checkNotNull(nameSupplier);
  checkNotNull(callable);
  return new Callable<T>() {
    @Override
    public T call() throws Exception {
      Thread currentThread = Thread.currentThread();
      String oldName = currentThread.getName();
      boolean restoreName = trySetName(nameSupplier.get(), currentThread);
      try {
        return callable.call();
      } finally {
        if (restoreName) {
          boolean unused = trySetName(oldName, currentThread);
        }
      }
    }
  };
}
 
Example #2
Source File: Uninterruptibles.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Invokes {@code latch.}{@link CountDownLatch#await(long, TimeUnit) await(timeout, unit)}
 * uninterruptibly.
 */

@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
@GwtIncompatible // concurrency
public static boolean awaitUninterruptibly(CountDownLatch latch, long timeout, TimeUnit unit) {
  boolean interrupted = false;
  try {
    long remainingNanos = unit.toNanos(timeout);
    long end = System.nanoTime() + remainingNanos;
    while (true) {
      try {
        // CountDownLatch treats negative timeouts just like zero.
        return latch.await(remainingNanos, NANOSECONDS);
      } catch (InterruptedException e) {
        interrupted = true;
        remainingNanos = end - System.nanoTime();
      }
    }
  } finally {
    if (interrupted) {
      Thread.currentThread().interrupt();
    }
  }
}
 
Example #3
Source File: LongMath.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@GwtIncompatible // TODO
static int log10Floor(long x) {
  /*
   * Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation.
   *
   * The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))), we
   * can narrow the possible floor(log10(x)) values to two. For example, if floor(log2(x)) is 6,
   * then 64 <= x < 128, so floor(log10(x)) is either 1 or 2.
   */
  int y = maxLog10ForLeadingZeros[Long.numberOfLeadingZeros(x)];
  /*
   * y is the higher of the two possible values of floor(log10(x)). If x < 10^y, then we want the
   * lower of the two possible values, or y - 1, otherwise, we want y.
   */
  return y - lessThanBranchFree(x, powersOf10[y]);
}
 
Example #4
Source File: Uninterruptibles.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Invokes {@code unit.}{@link TimeUnit#timedJoin(Thread, long) timedJoin(toJoin, timeout)}
 * uninterruptibly.
 */

@GwtIncompatible // concurrency
public static void joinUninterruptibly(Thread toJoin, long timeout, TimeUnit unit) {
  Preconditions.checkNotNull(toJoin);

  boolean interrupted = false;
  try {
    long remainingNanos = unit.toNanos(timeout);
    long end = System.nanoTime() + remainingNanos;
    while (true) {
      try {
        // TimeUnit.timedJoin() treats negative timeouts just like zero.
        NANOSECONDS.timedJoin(toJoin, remainingNanos);
        return;
      } catch (InterruptedException e) {
        interrupted = true;
        remainingNanos = end - System.nanoTime();
      }
    }
  } finally {
    if (interrupted) {
      Thread.currentThread().interrupt();
    }
  }
}
 
Example #5
Source File: Maps.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Returns a view of the portion of {@code map} whose keys are contained by {@code range}.
 *
 * <p>This method delegates to the appropriate methods of {@link NavigableMap} (namely
 * {@link NavigableMap#subMap(Object, boolean, Object, boolean) subMap()},
 * {@link NavigableMap#tailMap(Object, boolean) tailMap()}, and
 * {@link NavigableMap#headMap(Object, boolean) headMap()}) to actually construct the view.
 * Consult these methods for a full description of the returned view's behavior.
 *
 * <p><b>Warning:</b> {@code Range}s always represent a range of values using the values' natural
 * ordering. {@code NavigableMap} on the other hand can specify a custom ordering via a
 * {@link Comparator}, which can violate the natural ordering. Using this method (or in general
 * using {@code Range}) with unnaturally-ordered maps can lead to unexpected and undefined
 * behavior.
 *
 * @since 20.0
 */
@Beta
@GwtIncompatible // NavigableMap
public static <K extends Comparable<? super K>, V> NavigableMap<K, V> subMap(
    NavigableMap<K, V> map, Range<K> range) {
  if (map.comparator() != null
      && map.comparator() != Ordering.natural()
      && range.hasLowerBound()
      && range.hasUpperBound()) {
    checkArgument(
        map.comparator().compare(range.lowerEndpoint(), range.upperEndpoint()) <= 0,
        "map is using a custom comparator which is inconsistent with the natural ordering.");
  }
  if (range.hasLowerBound() && range.hasUpperBound()) {
    return map.subMap(
        range.lowerEndpoint(),
        range.lowerBoundType() == BoundType.CLOSED,
        range.upperEndpoint(),
        range.upperBoundType() == BoundType.CLOSED);
  } else if (range.hasLowerBound()) {
    return map.tailMap(range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED);
  } else if (range.hasUpperBound()) {
    return map.headMap(range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED);
  }
  return checkNotNull(map);
}
 
Example #6
Source File: Uninterruptibles.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Invokes {@code latch.}{@link CountDownLatch#await(long, TimeUnit) await(timeout, unit)}
 * uninterruptibly.
 */
@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
@GwtIncompatible // concurrency
public static boolean awaitUninterruptibly(CountDownLatch latch, long timeout, TimeUnit unit) {
  boolean interrupted = false;
  try {
    long remainingNanos = unit.toNanos(timeout);
    long end = System.nanoTime() + remainingNanos;

    while (true) {
      try {
        // CountDownLatch treats negative timeouts just like zero.
        return latch.await(remainingNanos, NANOSECONDS);
      } catch (InterruptedException e) {
        interrupted = true;
        remainingNanos = end - System.nanoTime();
      }
    }
  } finally {
    if (interrupted) {
      Thread.currentThread().interrupt();
    }
  }
}
 
Example #7
Source File: Uninterruptibles.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Invokes {@code toJoin.}{@link Thread#join() join()} uninterruptibly.
 */
@GwtIncompatible // concurrency
public static void joinUninterruptibly(Thread toJoin) {
  boolean interrupted = false;
  try {
    while (true) {
      try {
        toJoin.join();
        return;
      } catch (InterruptedException e) {
        interrupted = true;
      }
    }
  } finally {
    if (interrupted) {
      Thread.currentThread().interrupt();
    }
  }
}
 
Example #8
Source File: Iterables.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns a view of {@code unfiltered} containing all elements that are of
 * the type {@code desiredType}. The returned iterable's iterator does not
 * support {@code remove()}.
 */

@GwtIncompatible // Class.isInstance
public static <T> Iterable<T> filter(
  final Iterable<?> unfiltered, final Class<T> desiredType) {
  checkNotNull(unfiltered);
  checkNotNull(desiredType);
  return new FluentIterable<T>() {
    @Override
    public Iterator<T> iterator() {
      return Iterators.filter(unfiltered.iterator(), desiredType);
    }
  };
}
 
Example #9
Source File: LinkedListMultimap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@GwtIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
  stream.defaultReadObject();
  keyToKeyList = Maps.newLinkedHashMap();
  int size = stream.readInt();
  for (int i = 0; i < size; i++) {
    @SuppressWarnings("unchecked") // reading data stored by writeObject
    K key = (K) stream.readObject();
    @SuppressWarnings("unchecked") // reading data stored by writeObject
    V value = (V) stream.readObject();
    put(key, value);
  }
}
 
Example #10
Source File: ImmutableMultiset.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@GwtIncompatible // not present in emulated superclass
@Override
int copyIntoArray(Object[] dst, int offset) {
  for (Multiset.Entry<E> entry : entrySet()) {
    Arrays.fill(dst, offset, offset + entry.getCount(), entry.getElement());
    offset += entry.getCount();
  }
  return offset;
}
 
Example #11
Source File: CharMatcher.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * This is the actual implementation of {@link #precomputed}, but we bounce calls through a method
 * on {@link Platform} so that we can have different behavior in GWT.
 *
 * <p>This implementation tries to be smart in a number of ways. It recognizes cases where the
 * negation is cheaper to precompute than the matcher itself; it tries to build small hash tables
 * for matchers that only match a few characters, and so on. In the worst-case scenario, it
 * constructs an eight-kilobyte bit array and queries that. In many situations this produces a
 * matcher which is faster to query than the original.
 */

@GwtIncompatible // java.util.BitSet
CharMatcher precomputedInternal() {
  final BitSet table = new BitSet();
  setBits(table);
  int totalCharacters = table.cardinality();
  if (totalCharacters * 2 <= DISTINCT_CHARS) {
    return precomputedPositive(totalCharacters, table, toString());
  }
  else {
    // TODO(lowasser): is it worth it to worry about the last character of large matchers?
    table.flip(Character.MIN_VALUE, Character.MAX_VALUE + 1);
    int negatedCharacters = DISTINCT_CHARS - totalCharacters;
    String suffix = ".negate()";
    final String description = toString();
    String negatedDescription =
      description.endsWith(suffix)
        ? description.substring(0, description.length() - suffix.length())
        : description + suffix;
    return new NegatedFastMatcher(precomputedPositive(negatedCharacters, table, negatedDescription)) {
      @Override
      public String toString() {
        return description;
      }
    };
  }
}
 
Example #12
Source File: ImmutableListMultimap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * @serialData number of distinct keys, and then for each distinct key: the
 *     key, the number of values for that key, and the key's values
 */

@GwtIncompatible // java.io.ObjectOutputStream
private void writeObject(ObjectOutputStream stream) throws IOException {
  stream.defaultWriteObject();
  Serialization.writeMultimap(this, stream);
}
 
Example #13
Source File: ImmutableSortedSet.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * @since 12.0
 */

@GwtIncompatible // NavigableSet
@Override
public ImmutableSortedSet<E> descendingSet() {
  // racy single-check idiom
  ImmutableSortedSet<E> result = descendingSet;
  if (result == null) {
    result = descendingSet = createDescendingSet();
    result.descendingSet = this;
  }
  return result;
}
 
Example #14
Source File: ObjectArrays.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns a new array that contains the concatenated contents of two arrays.
 *
 * @param first the first array of elements to concatenate
 * @param second the second array of elements to concatenate
 * @param type the component type of the returned array
 */

@GwtIncompatible // Array.newInstance(Class, int)
public static <T> T[] concat(T[] first, T[] second, Class<T> type) {
  T[] result = newArray(type, first.length + second.length);
  System.arraycopy(first, 0, result, 0, first.length);
  System.arraycopy(second, 0, result, first.length, second.length);
  return result;
}
 
Example #15
Source File: TrustedListenableFutureTask.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@GwtIncompatible // Interruption not supported
@Override
protected final void interruptTask() {
  TrustedFutureInterruptibleTask localTask = task;
  if (localTask != null) {
    localTask.interruptTask();
  }
}
 
Example #16
Source File: EnumBiMap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * @serialData the key class, value class, number of entries, first key, first
 *     value, second key, second value, and so on.
 */

@GwtIncompatible // java.io.ObjectOutputStream
private void writeObject(ObjectOutputStream stream) throws IOException {
  stream.defaultWriteObject();
  stream.writeObject(keyType);
  stream.writeObject(valueType);
  Serialization.writeMap(this, stream);
}
 
Example #17
Source File: Enums.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns the {@link Field} in which {@code enumValue} is defined. For example, to get the
 * {@code Description} annotation on the {@code GOLF} constant of enum {@code Sport}, use
 * {@code Enums.getField(Sport.GOLF).getAnnotation(Description.class)}.
 *
 * @since 12.0
 */

@GwtIncompatible // reflection
public static Field getField(Enum<?> enumValue) {
  Class<?> clazz = enumValue.getDeclaringClass();
  try {
    return clazz.getDeclaredField(enumValue.name());
  } catch (NoSuchFieldException impossible) {
    throw new AssertionError(impossible);
  }
}
 
Example #18
Source File: Enums.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns the {@link Field} in which {@code enumValue} is defined. For example, to get the
 * {@code Description} annotation on the {@code GOLF} constant of enum {@code Sport}, use
 * {@code Enums.getField(Sport.GOLF).getAnnotation(Description.class)}.
 *
 * @since 12.0
 */

@GwtIncompatible // reflection
public static Field getField(Enum<?> enumValue) {
  Class<?> clazz = enumValue.getDeclaringClass();
  try {
    return clazz.getDeclaredField(enumValue.name());
  } catch (NoSuchFieldException impossible) {
    throw new AssertionError(impossible);
  }
}
 
Example #19
Source File: EnumBiMap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * @serialData the key class, value class, number of entries, first key, first
 *     value, second key, second value, and so on.
 */

@GwtIncompatible // java.io.ObjectOutputStream
private void writeObject(ObjectOutputStream stream) throws IOException {
  stream.defaultWriteObject();
  stream.writeObject(keyType);
  stream.writeObject(valueType);
  Serialization.writeMap(this, stream);
}
 
Example #20
Source File: EnumHashBiMap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@SuppressWarnings("unchecked") // reading field populated by writeObject
@GwtIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
  stream.defaultReadObject();
  keyType = (Class<K>) stream.readObject();
  setDelegates(
      WellBehavedMap.wrap(new EnumMap<K, V>(keyType)),
      new HashMap<V, K>(keyType.getEnumConstants().length * 3 / 2));
  Serialization.populateMap(this, stream);
}
 
Example #21
Source File: Throwables.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns the Method that can be used to return the size of a stack, or null if that method
 * cannot be found (it is only to be found in fairly recent JDKs).
 */

@GwtIncompatible // java.lang.reflect
@Nullable
private static Method getSizeMethod() {
  return getJlaMethod("getStackTraceDepth", Throwable.class);
}
 
Example #22
Source File: IntMath.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns the square root of {@code x}, rounded with the specified rounding mode.
 *
 * @throws IllegalArgumentException if {@code x < 0}
 * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and
 *     {@code sqrt(x)} is not an integer
 */

@GwtIncompatible // need BigIntegerMath to adequately test
@SuppressWarnings("fallthrough")
public static int sqrt(int x, RoundingMode mode) {
  checkNonNegative("x", x);
  int sqrtFloor = sqrtFloor(x);
  switch (mode) {
    case UNNECESSARY:
      checkRoundingUnnecessary(sqrtFloor * sqrtFloor == x); // fall through
    case FLOOR:
    case DOWN:
      return sqrtFloor;
    case CEILING:
    case UP:
      return sqrtFloor + lessThanBranchFree(sqrtFloor * sqrtFloor, x);
    case HALF_DOWN:
    case HALF_UP:
    case HALF_EVEN:
      int halfSquare = sqrtFloor * sqrtFloor + sqrtFloor;
      /*
       * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both x
       * and halfSquare are integers, this is equivalent to testing whether or not x <=
       * halfSquare. (We have to deal with overflow, though.)
       *
       * If we treat halfSquare as an unsigned int, we know that
       *            sqrtFloor^2 <= x < (sqrtFloor + 1)^2
       * halfSquare - sqrtFloor <= x < halfSquare + sqrtFloor + 1
       * so |x - halfSquare| <= sqrtFloor.  Therefore, it's safe to treat x - halfSquare as a
       * signed int, so lessThanBranchFree is safe for use.
       */
      return sqrtFloor + lessThanBranchFree(halfSquare, x);
    default:
      throw new AssertionError();
  }
}
 
Example #23
Source File: Futures.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@GwtIncompatible // TODO
private static void wrapAndThrowUnchecked(Throwable cause) {
  if (cause instanceof Error) {
    throw new ExecutionError((Error) cause);
  }
  /*
   * It's a non-Error, non-Exception Throwable. From my survey of such classes, I believe that
   * most users intended to extend Exception, so we'll treat it like an Exception.
   */
  throw new UncheckedExecutionException(cause);
}
 
Example #24
Source File: Futures.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns a list of delegate futures that correspond to the futures received in the order that
 * they complete. Delegate futures return the same value or throw the same exception as the
 * corresponding input future returns/throws.
 *
 * <p>Cancelling a delegate future has no effect on any input future, since the delegate future
 * does not correspond to a specific input future until the appropriate number of input futures
 * have completed. At that point, it is too late to cancel the input future. The input future's
 * result, which cannot be stored into the cancelled delegate future, is ignored.
 *
 * @since 17.0
 */
@Beta
@GwtIncompatible // TODO
public static <T> ImmutableList<ListenableFuture<T>> inCompletionOrder(
    Iterable<? extends ListenableFuture<? extends T>> futures) {
  // A CLQ may be overkill here. We could save some pointers/memory by synchronizing on an
  // ArrayDeque
  final ConcurrentLinkedQueue<SettableFuture<T>> delegates = Queues.newConcurrentLinkedQueue();
  ImmutableList.Builder<ListenableFuture<T>> listBuilder = ImmutableList.builder();
  // Using SerializingExecutor here will ensure that each CompletionOrderListener executes
  // atomically and therefore that each returned future is guaranteed to be in completion order.
  // N.B. there are some cases where the use of this executor could have possibly surprising
  // effects when input futures finish at approximately the same time _and_ the output futures
  // have directExecutor listeners. In this situation, the listeners may end up running on a
  // different thread than if they were attached to the corresponding input future. We believe
  // this to be a negligible cost since:
  // 1. Using the directExecutor implies that your callback is safe to run on any thread.
  // 2. This would likely only be noticeable if you were doing something expensive or blocking on
  //    a directExecutor listener on one of the output futures which is an antipattern anyway.
  SerializingExecutor executor = new SerializingExecutor(directExecutor());
  for (final ListenableFuture<? extends T> future : futures) {
    SettableFuture<T> delegate = SettableFuture.create();
    // Must make sure to add the delegate to the queue first in case the future is already done
    delegates.add(delegate);
    future.addListener(
        new Runnable() {
          @Override
          public void run() {
            delegates.remove().setFuture(future);
          }
        },
        executor);
    listBuilder.add(delegate);
  }
  return listBuilder.build();
}
 
Example #25
Source File: ImmutableMultiset.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@GwtIncompatible // not present in emulated superclass
@Override
int copyIntoArray(Object[] dst, int offset) {
  for (Multiset.Entry<E> entry : entrySet()) {
    Arrays.fill(dst, offset, offset + entry.getCount(), entry.getElement());
    offset += entry.getCount();
  }
  return offset;
}
 
Example #26
Source File: HashBiMap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@GwtIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
  stream.defaultReadObject();
  init(16);
  int size = Serialization.readCount(stream);
  Serialization.populateMap(this, stream, size);
}
 
Example #27
Source File: Iterators.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns a view of {@code unfiltered} containing all elements that are of
 * the type {@code desiredType}.
 */

@SuppressWarnings("unchecked") // can cast to <T> because non-Ts are removed
@GwtIncompatible // Class.isInstance
public static <T> UnmodifiableIterator<T> filter(Iterator<?> unfiltered, Class<T> desiredType) {
  return (UnmodifiableIterator<T>) filter(unfiltered, instanceOf(desiredType));
}
 
Example #28
Source File: LinkedHashMultimap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * @serialData the expected values per key, the number of distinct keys,
 * the number of entries, and the entries in order
 */

@GwtIncompatible // java.io.ObjectOutputStream
private void writeObject(ObjectOutputStream stream) throws IOException {
  stream.defaultWriteObject();
  stream.writeInt(keySet().size());
  for (K key : keySet()) {
    stream.writeObject(key);
  }
  stream.writeInt(size());
  for (Map.Entry<K, V> entry : entries()) {
    stream.writeObject(entry.getKey());
    stream.writeObject(entry.getValue());
  }
}
 
Example #29
Source File: ImmutableMultimap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@GwtIncompatible // not present in emulated superclass
@Override
int copyIntoArray(Object[] dst, int offset) {
  for (ImmutableCollection<V> valueCollection : multimap.map.values()) {
    offset = valueCollection.copyIntoArray(dst, offset);
  }
  return offset;
}
 
Example #30
Source File: ImmutableMultimap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@GwtIncompatible // not present in emulated superclass
@Override
int copyIntoArray(Object[] dst, int offset) {
  for (ImmutableCollection<V> valueCollection : multimap.map.values()) {
    offset = valueCollection.copyIntoArray(dst, offset);
  }
  return offset;
}