com.google.common.annotations.Beta Java Examples
The following examples show how to use
com.google.common.annotations.Beta.
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: Doubles.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * Parses the specified string as a double-precision floating point value. The ASCII character * {@code '-'} (<code>'\u002D'</code>) is recognized as the minus sign. * * <p>Unlike {@link Double#parseDouble(String)}, this method returns {@code null} instead of * throwing an exception if parsing fails. Valid inputs are exactly those accepted by * {@link Double#valueOf(String)}, except that leading and trailing whitespace is not permitted. * * <p>This implementation is likely to be faster than {@code * Double.parseDouble} if many failures are expected. * * @param string the string representation of a {@code double} value * @return the floating point value represented by {@code string}, or {@code null} if * {@code string} has a length of zero or cannot be parsed as a {@code double} value * @since 14.0 */ @Beta @Nullable @CheckForNull @GwtIncompatible // regular expressions public static Double tryParse(String string) { if (FLOATING_POINT_PATTERN.matcher(string).matches()) { // TODO(lowasser): could be potentially optimized, but only with // extensive testing try { return Double.parseDouble(string); } catch (NumberFormatException e) { // Double.parseDouble has changed specs several times, so fall through // gracefully } } return null; }
Example #2
Source File: MoreExecutors.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * Shuts down the given executor service gradually, first disabling new submissions and later, if * necessary, cancelling remaining tasks. * * <p>The method takes the following steps: * <ol> * <li>calls {@link ExecutorService#shutdown()}, disabling acceptance of new submitted tasks. * <li>awaits executor service termination for half of the specified timeout. * <li>if the timeout expires, it calls {@link ExecutorService#shutdownNow()}, cancelling pending * tasks and interrupting running tasks. * <li>awaits executor service termination for the other half of the specified timeout. * </ol> * * <p>If, at any step of the process, the calling thread is interrupted, the method calls * {@link ExecutorService#shutdownNow()} and returns. * * @param service the {@code ExecutorService} to shut down * @param timeout the maximum time to wait for the {@code ExecutorService} to terminate * @param unit the time unit of the timeout argument * @return {@code true} if the {@code ExecutorService} was terminated successfully, {@code false} * if the call timed out or was interrupted * @since 17.0 */ @Beta @CanIgnoreReturnValue @GwtIncompatible // concurrency public static boolean shutdownAndAwaitTermination(ExecutorService service, long timeout, TimeUnit unit) { long halfTimeoutNanos = unit.toNanos(timeout) / 2; // Disable new tasks from being submitted service.shutdown(); try { // Wait for half the duration of the timeout for existing tasks to terminate if (!service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS)) { // Cancel currently executing tasks service.shutdownNow(); // Wait the other half of the timeout for tasks to respond to being cancelled service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS); } } catch (InterruptedException ie) { // Preserve interrupt status Thread.currentThread().interrupt(); // (Re-)Cancel if current thread also interrupted service.shutdownNow(); } return service.isTerminated(); }
Example #3
Source File: MoreExecutors.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * Shuts down the given executor service gradually, first disabling new submissions and later, if * necessary, cancelling remaining tasks. * * <p>The method takes the following steps: * <ol> * <li>calls {@link ExecutorService#shutdown()}, disabling acceptance of new submitted tasks. * <li>awaits executor service termination for half of the specified timeout. * <li>if the timeout expires, it calls {@link ExecutorService#shutdownNow()}, cancelling pending * tasks and interrupting running tasks. * <li>awaits executor service termination for the other half of the specified timeout. * </ol> * * <p>If, at any step of the process, the calling thread is interrupted, the method calls * {@link ExecutorService#shutdownNow()} and returns. * * @param service the {@code ExecutorService} to shut down * @param timeout the maximum time to wait for the {@code ExecutorService} to terminate * @param unit the time unit of the timeout argument * @return {@code true} if the {@code ExecutorService} was terminated successfully, {@code false} * if the call timed out or was interrupted * @since 17.0 */ @Beta @CanIgnoreReturnValue @GwtIncompatible // concurrency public static boolean shutdownAndAwaitTermination( ExecutorService service, long timeout, TimeUnit unit) { long halfTimeoutNanos = unit.toNanos(timeout) / 2; // Disable new tasks from being submitted service.shutdown(); try { // Wait for half the duration of the timeout for existing tasks to terminate if (!service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS)) { // Cancel currently executing tasks service.shutdownNow(); // Wait the other half of the timeout for tasks to respond to being cancelled service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS); } } catch (InterruptedException ie) { // Preserve interrupt status Thread.currentThread().interrupt(); // (Re-)Cancel if current thread also interrupted service.shutdownNow(); } return service.isTerminated(); }
Example #4
Source File: LongMath.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * Returns the product of {@code a} and {@code b} unless it would overflow or underflow in which * case {@code Long.MAX_VALUE} or {@code Long.MIN_VALUE} is returned, respectively. * * @since 20.0 */ @Beta public static long saturatedMultiply(long a, long b) { // see checkedMultiply for explanation int leadingZeros = Long.numberOfLeadingZeros(a) + Long.numberOfLeadingZeros(~a) + Long.numberOfLeadingZeros(b) + Long.numberOfLeadingZeros(~b); if (leadingZeros > Long.SIZE + 1) { return a * b; } // the return value if we will overflow (which we calculate by overflowing a long :) ) long limit = Long.MAX_VALUE + ((a ^ b) >>> (Long.SIZE - 1)); if (leadingZeros < Long.SIZE | (a < 0 & b == Long.MIN_VALUE)) { // overflow return limit; } long result = a * b; if (a == 0 || result / a == b) { return result; } return limit; }
Example #5
Source File: Maps.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * Returns an immutable map instance containing the given entries. * Internally, the returned map will be backed by an {@link EnumMap}. * * <p>The iteration order of the returned map follows the enum's iteration * order, not the order in which the elements appear in the given map. * * @param map the map to make an immutable copy of * @return an immutable map containing those entries * @since 14.0 */ @GwtCompatible(serializable = true) @Beta public static <K extends Enum<K>, V> ImmutableMap<K, V> immutableEnumMap( Map<K, ? extends V> map) { if (map instanceof ImmutableEnumMap) { @SuppressWarnings("unchecked") // safe covariant cast ImmutableEnumMap<K, V> result = (ImmutableEnumMap<K, V>) map; return result; } else if (map.isEmpty()) { return ImmutableMap.of(); } else { for (Map.Entry<K, ? extends V> entry : map.entrySet()) { checkNotNull(entry.getKey()); checkNotNull(entry.getValue()); } return ImmutableEnumMap.asImmutable(new EnumMap<K, V>(map)); } }
Example #6
Source File: ImmutableBiMap.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * Returns an immutable bimap containing the given entries. * * @throws IllegalArgumentException if two keys have the same value or two * values have the same key * @throws NullPointerException if any key, value, or entry is null * @since 19.0 */ @Beta public static <K, V> ImmutableBiMap<K, V> copyOf(Iterable<? extends Entry<? extends K, ? extends V>> entries) { @SuppressWarnings("unchecked") // we'll only be using getKey and getValue, which are covariant Entry<K, V>[] entryArray = (Entry<K, V>[]) Iterables.toArray(entries, EMPTY_ENTRY_ARRAY); switch (entryArray.length) { case 0: return of(); case 1: Entry<K, V> entry = entryArray[0]; return of(entry.getKey(), entry.getValue()); default: /* * The current implementation will end up using entryArray directly, though it will write * over the (arbitrary, potentially mutable) Entry objects actually stored in entryArray. */ return RegularImmutableBiMap.fromEntries(entryArray); } }
Example #7
Source File: ForwardingMultiset.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * A sensible, albeit inefficient, definition of {@link #count} in terms of * {@link #entrySet}. If you override {@link #entrySet}, you may wish to * override {@link #count} to forward to this implementation. * * @since 7.0 */ @Beta protected int standardCount(@Nullable Object object) { for (Entry<?> entry : this.entrySet()) { if (Objects.equal(entry.getElement(), object)) { return entry.getCount(); } } return 0; }
Example #8
Source File: IntMath.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Returns the smallest power of two greater than or equal to {@code x}. This is equivalent to * {@code checkedPow(2, log2(x, CEILING))}. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException of the next-higher power of two is not representable as an * {@code int}, i.e. when {@code x > 2^30} * @since 20.0 */ @Beta public static int ceilingPowerOfTwo(int x) { checkPositive("x", x); if (x > MAX_SIGNED_POWER_OF_TWO) { throw new ArithmeticException("ceilingPowerOfTwo(" + x + ") not representable as an int"); } return 1 << -Integer.numberOfLeadingZeros(x - 1); }
Example #9
Source File: Splitter.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Splits {@code sequence} into string components and returns them as an immutable list. If you * want an {@link Iterable} which may be lazily evaluated, use {@link #split(CharSequence)}. * * @param sequence the sequence of characters to split * @return an immutable list of the segments split from the parameter * @since 15.0 */ @Beta public List<String> splitToList(CharSequence sequence) { checkNotNull(sequence); Iterator<String> iterator = splittingIterator(sequence); List<String> result = new ArrayList<String>(); while (iterator.hasNext()) { result.add(iterator.next()); } return Collections.unmodifiableList(result); }
Example #10
Source File: Multimaps.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Returns {@link SetMultimap#asMap multimap.asMap()}, with its type corrected * from {@code Map<K, Collection<V>>} to {@code Map<K, Set<V>>}. * * @since 15.0 */ @Beta @SuppressWarnings("unchecked") // safe by specification of SetMultimap.asMap() public static <K, V> Map<K, Set<V>> asMap(SetMultimap<K, V> multimap) { return (Map<K, Set<V>>) (Map<K, ?>) multimap.asMap(); }
Example #11
Source File: ImmutableMultimap.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Adds entries to the built multimap. * * @since 19.0 */ @CanIgnoreReturnValue @Beta public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) { for (Entry<? extends K, ? extends V> entry : entries) { put(entry); } return this; }
Example #12
Source File: ImmutableSetMultimap.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * {@inheritDoc} * * @since 19.0 */ @CanIgnoreReturnValue @Beta @Override public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) { super.putAll(entries); return this; }
Example #13
Source File: Joiner.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Appends the string representation of each entry in {@code entries}, using the previously * configured separator and key-value separator, to {@code builder}. Identical to * {@link #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}. * * @since 11.0 */ @Beta @CanIgnoreReturnValue public StringBuilder appendTo(StringBuilder builder, Iterator<? extends Entry<?, ?>> entries) { try { appendTo((Appendable) builder, entries); } catch (IOException impossible) { throw new AssertionError(impossible); } return builder; }
Example #14
Source File: ForwardingMultiset.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * A sensible, albeit inefficient, definition of {@link #count} in terms of * {@link #entrySet}. If you override {@link #entrySet}, you may wish to * override {@link #count} to forward to this implementation. * * @since 7.0 */ @Beta protected int standardCount(@Nullable Object object) { for (Entry<?> entry : this.entrySet()) { if (Objects.equal(entry.getElement(), object)) { return entry.getCount(); } } return 0; }
Example #15
Source File: ImmutableSortedMap.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Throws an {@code UnsupportedOperationException}. * * @since 19.0 * @deprecated Unsupported by ImmutableSortedMap.Builder. */ @CanIgnoreReturnValue @Beta @Override @Deprecated public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) { throw new UnsupportedOperationException("Not available on ImmutableSortedMap.Builder"); }
Example #16
Source File: Suppliers.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Returns a function that accepts a supplier and returns the result of invoking * {@link Supplier#get} on that supplier. * * @since 8.0 */ @Beta public static <T> Function<Supplier<T>, T> supplierFunction() { @SuppressWarnings("unchecked") // implementation is "fully variant" SupplierFunction<T> sf = (SupplierFunction<T>) SupplierFunctionImpl.INSTANCE; return sf; }
Example #17
Source File: Multimaps.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Returns {@link ListMultimap#asMap multimap.asMap()}, with its type * corrected from {@code Map<K, Collection<V>>} to {@code Map<K, List<V>>}. * * @since 15.0 */ @Beta @SuppressWarnings("unchecked") // safe by specification of ListMultimap.asMap() public static <K, V> Map<K, List<V>> asMap(ListMultimap<K, V> multimap) { return (Map<K, List<V>>) (Map<K, ?>) multimap.asMap(); }
Example #18
Source File: LongMath.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Returns the sum of {@code a} and {@code b} unless it would overflow or underflow in which case * {@code Long.MAX_VALUE} or {@code Long.MIN_VALUE} is returned, respectively. * * @since 20.0 */ @Beta public static long saturatedAdd(long a, long b) { long naiveSum = a + b; if ((a ^ b) < 0 | (a ^ naiveSum) >= 0) { // If a and b have different signs or a has the same sign as the result then there was no // overflow, return. return naiveSum; } // we did over/under flow, if the sign is negative we should return MAX otherwise MIN return Long.MAX_VALUE + ((naiveSum >>> (Long.SIZE - 1)) ^ 1); }
Example #19
Source File: Multisets.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Returns a copy of {@code multiset} as an {@link ImmutableMultiset} whose iteration order is * highest count first, with ties broken by the iteration order of the original multiset. * * @since 11.0 */ @Beta public static <E> ImmutableMultiset<E> copyHighestCountFirst(Multiset<E> multiset) { List<Entry<E>> sortedEntries = Multisets.DECREASING_COUNT_ORDERING.immutableSortedCopy(multiset.entrySet()); return ImmutableMultiset.copyFromEntries(sortedEntries); }
Example #20
Source File: FluentIterable.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Returns a fluent iterable that combines several iterables. The returned iterable has an * iterator that traverses the elements of each iterable in {@code inputs}. The input iterators * are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input * iterator supports it. The methods of the returned iterable may throw * {@code NullPointerException} if any of the input iterators is {@code null}. * * @since 20.0 */ @Beta public static <T> FluentIterable<T> concat(final Iterable<? extends Iterable<? extends T>> inputs) { checkNotNull(inputs); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.concat(Iterables.transform(inputs, Iterables.<T>toIterator()).iterator()); } }; }
Example #21
Source File: ImmutableSetMultimap.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * {@inheritDoc} * * @since 19.0 */ @CanIgnoreReturnValue @Beta @Override public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) { super.putAll(entries); return this; }
Example #22
Source File: Multimaps.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Returns {@link SetMultimap#asMap multimap.asMap()}, with its type corrected * from {@code Map<K, Collection<V>>} to {@code Map<K, Set<V>>}. * * @since 15.0 */ @Beta @SuppressWarnings("unchecked") // safe by specification of SetMultimap.asMap() public static <K, V> Map<K, Set<V>> asMap(SetMultimap<K, V> multimap) { return (Map<K, Set<V>>) (Map<K, ?>) multimap.asMap(); }
Example #23
Source File: LongMath.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Returns the sum of {@code a} and {@code b} unless it would overflow or underflow in which case * {@code Long.MAX_VALUE} or {@code Long.MIN_VALUE} is returned, respectively. * * @since 20.0 */ @Beta public static long saturatedAdd(long a, long b) { long naiveSum = a + b; if ((a ^ b) < 0 | (a ^ naiveSum) >= 0) { // If a and b have different signs or a has the same sign as the result then there was no // overflow, return. return naiveSum; } // we did over/under flow, if the sign is negative we should return MAX otherwise MIN return Long.MAX_VALUE + ((naiveSum >>> (Long.SIZE - 1)) ^ 1); }
Example #24
Source File: Callables.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Creates an {@link AsyncCallable} from a {@link Callable}. * * <p>The {@link AsyncCallable} returns the {@link ListenableFuture} resulting from * {@link ListeningExecutorService#submit(Callable)}. * * @since 20.0 */ @Beta @GwtIncompatible public static <T> AsyncCallable<T> asAsyncCallable(final Callable<T> callable, final ListeningExecutorService listeningExecutorService) { checkNotNull(callable); checkNotNull(listeningExecutorService); return new AsyncCallable<T>() { @Override public ListenableFuture<T> call() throws Exception { return listeningExecutorService.submit(callable); } }; }
Example #25
Source File: LongMath.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Returns the smallest power of two greater than or equal to {@code x}. This is equivalent to * {@code checkedPow(2, log2(x, CEILING))}. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException of the next-higher power of two is not representable as a * {@code long}, i.e. when {@code x > 2^62} * @since 20.0 */ @Beta public static long ceilingPowerOfTwo(long x) { checkPositive("x", x); if (x > MAX_SIGNED_POWER_OF_TWO) { throw new ArithmeticException("ceilingPowerOfTwo(" + x + ") is not representable as a long"); } return 1L << -Long.numberOfLeadingZeros(x - 1); }
Example #26
Source File: Splitter.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Splits {@code sequence} into string components and returns them as an immutable list. If you * want an {@link Iterable} which may be lazily evaluated, use {@link #split(CharSequence)}. * * @param sequence the sequence of characters to split * @return an immutable list of the segments split from the parameter * @since 15.0 */ @Beta public List<String> splitToList(CharSequence sequence) { checkNotNull(sequence); Iterator<String> iterator = splittingIterator(sequence); List<String> result = new ArrayList<String>(); while (iterator.hasNext()) { result.add(iterator.next()); } return Collections.unmodifiableList(result); }
Example #27
Source File: ImmutableListMultimap.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * {@inheritDoc} * * @since 19.0 */ @CanIgnoreReturnValue @Beta @Override public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) { super.putAll(entries); return this; }
Example #28
Source File: Ascii.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Indicates whether the contents of the given character sequences {@code s1} and {@code s2} are * equal, ignoring the case of any ASCII alphabetic characters between {@code 'a'} and {@code 'z'} * or {@code 'A'} and {@code 'Z'} inclusive. * * <p>This method is significantly faster than {@link String#equalsIgnoreCase} and should be used * in preference if at least one of the parameters is known to contain only ASCII characters. * * <p>Note however that this method does not always behave identically to expressions such as: * <ul> * <li>{@code string.toUpperCase().equals("UPPER CASE ASCII")} * <li>{@code string.toLowerCase().equals("lower case ascii")} * </ul> * <p>due to case-folding of some non-ASCII characters (which does not occur in * {@link String#equalsIgnoreCase}). However in almost all cases that ASCII strings are used, the * author probably wanted the behavior provided by this method rather than the subtle and * sometimes surprising behavior of {@code toUpperCase()} and {@code toLowerCase()}. * * @since 16.0 */ @Beta public static boolean equalsIgnoreCase(CharSequence s1, CharSequence s2) { // Calling length() is the null pointer check (so do it before we can exit early). int length = s1.length(); if (s1 == s2) { return true; } if (length != s2.length()) { return false; } for (int i = 0; i < length; i++) { char c1 = s1.charAt(i); char c2 = s2.charAt(i); if (c1 == c2) { continue; } int alphaIndex = getAlphaIndex(c1); // This was also benchmarked using '&' to avoid branching (but always evaluate the rhs), // however this showed no obvious improvement. if (alphaIndex < 26 && alphaIndex == getAlphaIndex(c2)) { continue; } return false; } return true; }
Example #29
Source File: ApplicationFacade.java From vespa with Apache License 2.0 | 4 votes |
/** * @param componentId name of the component (usually YourClass.class.getName()) * @return the client object, or null if not found */ @Beta public ServerProvider getServerById(String componentId) { return Container.get().getServerProviderRegistry().getComponent(new ComponentId(componentId)); }
Example #30
Source File: SortedChildrenTesterTest.java From fastods with GNU General Public License v3.0 | 4 votes |
@Beta private Node getNode(final String s) throws SAXException, IOException { final Document document = this.builder.parse(new ByteArrayInputStream(s.getBytes(Charsets.UTF_8))); return document.getFirstChild(); }