@CanIgnoreReturnValue
  public long copyTo(CharSink sink) throws IOException {
    checkNotNull(sink);

    Closer closer = Closer.create();
    try {
      Reader reader = closer.register(openStream());
      Writer writer = closer.register(sink.openStream());
      return CharStreams.copy(reader, writer);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

@ CanIgnoreReturnValue public long copyTo ( CharSink sink ) throws IOException { checkNotNull ( sink ) ; Closer closer = Closer . create ( ) ; try { Reader reader = closer . register ( openStream ( ) ) ; Writer writer = closer . register ( sink . openStream ( ) ) ; return CharStreams . copy ( reader , writer ) ; } catch ( Throwable e ) { throw closer . rethrow ( e ) ; } finally { closer . close ( ) ; } }

Copies the contents of this source to the given sink.

@return the number of characters copied
@throws IOException if an I/O error occurs while reading from this source or writing to {@code
sink}

Copies the contents of this source to the given sink .


public String read() throws IOException {
    Closer closer = Closer.create();
    try {
      Reader reader = closer.register(openStream());
      return CharStreams.toString(reader);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

public String read ( ) throws IOException { Closer closer = Closer . create ( ) ; try { Reader reader = closer . register ( openStream ( ) ) ; return CharStreams . toString ( reader ) ; } catch ( Throwable e ) { throw closer . rethrow ( e ) ; } finally { closer . close ( ) ; } }

Reads the contents of this source as a string.

@throws IOException if an I/O error occurs while reading from this source

Reads the contents of this source as a string .


public ImmutableList<String> readLines() throws IOException {
    Closer closer = Closer.create();
    try {
      BufferedReader reader = closer.register(openBufferedStream());
      List<String> result = Lists.newArrayList();
      String line;
      while ((line = reader.readLine()) != null) {
        result.add(line);
      }
      return ImmutableList.copyOf(result);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

public ImmutableList < String > readLines ( ) throws IOException { Closer closer = Closer . create ( ) ; try { BufferedReader reader = closer . register ( openBufferedStream ( ) ) ; List < String > result = Lists . newArrayList ( ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { result . add ( line ) ; } return ImmutableList . copyOf ( result ) ; } catch ( Throwable e ) { throw closer . rethrow ( e ) ; } finally { closer . close ( ) ; } }

Reads all the lines of this source as a list of strings. The returned list will be empty if
this source is empty.

<p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of
text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code
\n}. If the source's content does not end in a line termination sequence, it is treated as if
it does.

@throws IOException if an I/O error occurs while reading from this source

Reads all the lines of this source as a list of strings . The returned list will be empty if this source is empty .


@Override
  public int read(byte[] b, int off, int len) throws IOException {
    // Obey InputStream contract.
    checkPositionIndexes(off, off + len, b.length);
    if (len == 0) {
      return 0;
    }

    // The rest of this method implements the process described by the CharsetEncoder javadoc.
    int totalBytesRead = 0;
    boolean doneEncoding = endOfInput;

    DRAINING:
    while (true) {
      // We stay in draining mode until there are no bytes left in the output buffer. Then we go
      // back to encoding/flushing.
      if (draining) {
        totalBytesRead += drain(b, off + totalBytesRead, len - totalBytesRead);
        if (totalBytesRead == len || doneFlushing) {
          return (totalBytesRead > 0) ? totalBytesRead : -1;
        }
        draining = false;
        byteBuffer.clear();
      }

      while (true) {
        // We call encode until there is no more input. The last call to encode will have endOfInput
        // == true. Then there is a final call to flush.
        CoderResult result;
        if (doneFlushing) {
          result = CoderResult.UNDERFLOW;
        } else if (doneEncoding) {
          result = encoder.flush(byteBuffer);
        } else {
          result = encoder.encode(charBuffer, byteBuffer, endOfInput);
        }

        if (result.isOverflow()) {
          // Not enough room in output buffer--drain it, creating a bigger buffer if necessary.
          startDraining(true);
          continue DRAINING;
        } else if (result.isUnderflow()) {
          // If encoder underflows, it means either:
          // a) the final flush() succeeded; next drain (then done)
          // b) we encoded all of the input; next flush
          // c) we ran of out input to encode; next read more input
          if (doneEncoding) { // (a)
            doneFlushing = true;
            startDraining(false);
            continue DRAINING;
          } else if (endOfInput) { // (b)
            doneEncoding = true;
          } else { // (c)
            readMoreChars();
          }
        } else if (result.isError()) {
          // Only reach here if a CharsetEncoder with non-REPLACE settings is used.
          result.throwException();
          return 0; // Not called.
        }
      }
    }
  }


private static CharBuffer grow(CharBuffer buf) {
    char[] copy = Arrays.copyOf(buf.array(), buf.capacity() * 2);
    CharBuffer bigger = CharBuffer.wrap(copy);
    bigger.position(buf.position());
    bigger.limit(buf.limit());
    return bigger;
  }

private static CharBuffer grow ( CharBuffer buf ) { char [ ] copy = Arrays . copyOf ( buf . array ( ) , buf . capacity ( ) * 2 ) ; CharBuffer bigger = CharBuffer . wrap ( copy ) ; bigger . position ( buf . position ( ) ) ; bigger . limit ( buf . limit ( ) ) ; return bigger ; }

Returns a new CharBuffer identical to buf, except twice the capacity.

Returns a new CharBuffer identical to buf except twice the capacity .


private void readMoreChars() throws IOException {
    // Possibilities:
    // 1) array has space available on right hand side (between limit and capacity)
    // 2) array has space available on left hand side (before position)
    // 3) array has no space available
    //
    // In case 2 we shift the existing chars to the left, and in case 3 we create a bigger
    // array, then they both become case 1.

    if (availableCapacity(charBuffer) == 0) {
      if (charBuffer.position() > 0) {
        // (2) There is room in the buffer. Move existing bytes to the beginning.
        charBuffer.compact().flip();
      } else {
        // (3) Entire buffer is full, need bigger buffer.
        charBuffer = grow(charBuffer);
      }
    }

    // (1) Read more characters into free space at end of array.
    int limit = charBuffer.limit();
    int numChars = reader.read(charBuffer.array(), limit, availableCapacity(charBuffer));
    if (numChars == -1) {
      endOfInput = true;
    } else {
      charBuffer.limit(limit + numChars);
    }
  }

Handle the case of underflow caused by needing more input characters.

Handle the case of underflow caused by needing more input characters .


private void startDraining(boolean overflow) {
    byteBuffer.flip();
    if (overflow && byteBuffer.remaining() == 0) {
      byteBuffer = ByteBuffer.allocate(byteBuffer.capacity() * 2);
    } else {
      draining = true;
    }
  }

private void startDraining ( boolean overflow ) { byteBuffer . flip ( ) ; if ( overflow && byteBuffer . remaining ( ) == 0 ) { byteBuffer = ByteBuffer . allocate ( byteBuffer . capacity ( ) * 2 ) ; } else { draining = true ; } }

Flips the buffer output buffer so we can start reading bytes from it. If we are starting to
drain because there was overflow, and there aren't actually any characters to drain, then the
overflow must be due to a small output buffer.

Flips the buffer output buffer so we can start reading bytes from it . If we are starting to drain because there was overflow and there aren t actually any characters to drain then the overflow must be due to a small output buffer .


@GwtIncompatible // Array.newInstance(Class, int)
  public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type) {
    return toArray(iterable, ObjectArrays.newArray(type, 0));
  }

@
GwtIncompatible
// Array.newInstance(Class, int)
public
static
<
T
>
T
[
]
toArray
(
Iterable
<
extends
T
>
iterable
,
Class
<
T
>
type
)
{
return
toArray
(
iterable
,
ObjectArrays
.
newArray
(
type
,
0
)
)
;
}

Copies an iterable's elements into an array.

@param iterable the iterable to copy
@param type the type of the elements
@return a newly-allocated array into which all the elements of the iterable have been copied

Copies an iterable s elements into an array .


public static boolean isEmpty(Iterable<?> iterable) {
    if (iterable instanceof Collection) {
      return ((Collection<?>) iterable).isEmpty();
    }
    return !iterable.iterator().hasNext();
  }

public static boolean isEmpty ( Iterable < ? > iterable ) { if ( iterable instanceof Collection ) { return ( ( Collection < ? > ) iterable ) . isEmpty ( ) ; } return ! iterable . iterator ( ) . hasNext ( ) ; }

Determines if the given iterable contains no elements.

There is no precise {@link Iterator} equivalent to this method, since one can only ask an
iterator whether it has any elements remaining (which one does using {@link
Iterator#hasNext}).

{@code Stream} equivalent: {@code !stream.findAny().isPresent()}

@return {@code true} if the iterable contains no elements

Determines if the given iterable contains no elements .


static <T> Function<Iterable<? extends T>, Iterator<? extends T>> toIterator() {
    return new Function<Iterable<? extends T>, Iterator<? extends T>>() {
      @Override
      public Iterator<? extends T> apply(Iterable<? extends T> iterable) {
        return iterable.iterator();
      }
    };
  }

static < T > Function < Iterable < ? extends T > , Iterator < ? extends T > > toIterator ( ) { return new Function < Iterable < ? extends T > , Iterator < ? extends T > > ( ) { @ Override public Iterator < ? extends T > apply ( Iterable < ? extends T > iterable ) { return iterable . iterator ( ) ; } } ; }


private static <T> Iterator<T> consumingForArray(final T... elements) {
    return new UnmodifiableIterator<T>() {
      int index = 0;

      @Override
      public boolean hasNext() {
        return index < elements.length;
      }

      @Override
      public T next() {
        if (!hasNext()) {
          throw new NoSuchElementException();
        }
        T result = elements[index];
        elements[index] = null;
        index++;
        return result;
      }
    };
  }

private static < T > Iterator < T > consumingForArray ( final T ... elements ) { return new UnmodifiableIterator < T > ( ) { int index = 0 ; @ Override public boolean hasNext ( ) { return index < elements . length ; } @ Override public T next ( ) { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( ) ; } T result = elements [ index ] ; elements [ index ] = null ; index ++ ; return result ; } } ; }

Returns an Iterator that walks the specified array, nulling out elements behind it. This can
avoid memory leaks when an element is no longer necessary.

<p>This is mainly just to avoid the intermediate ArrayDeque in ConsumingQueueIterator.

Returns an Iterator that walks the specified array nulling out elements behind it . This can avoid memory leaks when an element is no longer necessary .


static <T> Iterator<T> concatNoDefensiveCopy(Iterator<? extends T>... inputs) {
    for (Iterator<? extends T> input : checkNotNull(inputs)) {
      checkNotNull(input);
    }
    return concat(consumingForArray(inputs));
  }

static < T > Iterator < T > concatNoDefensiveCopy ( Iterator < ? extends T > ... inputs ) { for ( Iterator < ? extends T > input : checkNotNull ( inputs ) ) { checkNotNull ( input ) ; } return concat ( consumingForArray ( inputs ) ) ; }

Concats a varargs array of iterators without making a defensive copy of the array.

Concats a varargs array of iterators without making a defensive copy of the array .


static void clear(Iterator<?> iterator) {
    checkNotNull(iterator);
    while (iterator.hasNext()) {
      iterator.next();
      iterator.remove();
    }
  }

static void clear ( Iterator < ? > iterator ) { checkNotNull ( iterator ) ; while ( iterator . hasNext ( ) ) { iterator . next ( ) ; iterator . remove ( ) ; } }

Clears the iterator using its remove method.

Clears the iterator using its remove method .


public void write(byte[] bytes) throws IOException {
    checkNotNull(bytes);

    Closer closer = Closer.create();
    try {
      OutputStream out = closer.register(openStream());
      out.write(bytes);
      out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

Writes all the given bytes to this sink.

@throws IOException if an I/O occurs while writing to this sink

Writes all the given bytes to this sink .


public static CacheBuilderSpec parse(String cacheBuilderSpecification) {
    CacheBuilderSpec spec = new CacheBuilderSpec(cacheBuilderSpecification);
    if (!cacheBuilderSpecification.isEmpty()) {
      for (String keyValuePair : KEYS_SPLITTER.split(cacheBuilderSpecification)) {
        List<String> keyAndValue = ImmutableList.copyOf(KEY_VALUE_SPLITTER.split(keyValuePair));
        checkArgument(!keyAndValue.isEmpty(), "blank key-value pair");
        checkArgument(
            keyAndValue.size() <= 2,
            "key-value pair %s with more than one equals sign",
            keyValuePair);

        // Find the ValueParser for the current key.
        String key = keyAndValue.get(0);
        ValueParser valueParser = VALUE_PARSERS.get(key);
        checkArgument(valueParser != null, "unknown key %s", key);

        String value = keyAndValue.size() == 1 ? null : keyAndValue.get(1);
        valueParser.parse(spec, key, value);
      }
    }

    return spec;
  }

Creates a CacheBuilderSpec from a string.

@param cacheBuilderSpecification the string form

Creates a CacheBuilderSpec from a string .


CacheBuilder<Object, Object> toCacheBuilder() {
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    if (initialCapacity != null) {
      builder.initialCapacity(initialCapacity);
    }
    if (maximumSize != null) {
      builder.maximumSize(maximumSize);
    }
    if (maximumWeight != null) {
      builder.maximumWeight(maximumWeight);
    }
    if (concurrencyLevel != null) {
      builder.concurrencyLevel(concurrencyLevel);
    }
    if (keyStrength != null) {
      switch (keyStrength) {
        case WEAK:
          builder.weakKeys();
          break;
        default:
          throw new AssertionError();
      }
    }
    if (valueStrength != null) {
      switch (valueStrength) {
        case SOFT:
          builder.softValues();
          break;
        case WEAK:
          builder.weakValues();
          break;
        default:
          throw new AssertionError();
      }
    }
    if (recordStats != null && recordStats) {
      builder.recordStats();
    }
    if (writeExpirationTimeUnit != null) {
      builder.expireAfterWrite(writeExpirationDuration, writeExpirationTimeUnit);
    }
    if (accessExpirationTimeUnit != null) {
      builder.expireAfterAccess(accessExpirationDuration, accessExpirationTimeUnit);
    }
    if (refreshTimeUnit != null) {
      builder.refreshAfterWrite(refreshDuration, refreshTimeUnit);
    }

    return builder;
  }

CacheBuilder < Object , Object > toCacheBuilder ( ) { CacheBuilder < Object , Object > builder = CacheBuilder . newBuilder ( ) ; if ( initialCapacity != null ) { builder . initialCapacity ( initialCapacity ) ; } if ( maximumSize != null ) { builder . maximumSize ( maximumSize ) ; } if ( maximumWeight != null ) { builder . maximumWeight ( maximumWeight ) ; } if ( concurrencyLevel != null ) { builder . concurrencyLevel ( concurrencyLevel ) ; } if ( keyStrength != null ) { switch ( keyStrength ) { case WEAK : builder . weakKeys ( ) ; break ; default : throw new AssertionError ( ) ; } } if ( valueStrength != null ) { switch ( valueStrength ) { case SOFT : builder . softValues ( ) ; break ; case WEAK : builder . weakValues ( ) ; break ; default : throw new AssertionError ( ) ; } } if ( recordStats != null && recordStats ) { builder . recordStats ( ) ; } if ( writeExpirationTimeUnit != null ) { builder . expireAfterWrite ( writeExpirationDuration , writeExpirationTimeUnit ) ; } if ( accessExpirationTimeUnit != null ) { builder . expireAfterAccess ( accessExpirationDuration , accessExpirationTimeUnit ) ; } if ( refreshTimeUnit != null ) { builder . refreshAfterWrite ( refreshDuration , refreshTimeUnit ) ; } return builder ; }

Returns a CacheBuilder configured according to this instance's specification.

Returns a CacheBuilder configured according to this instance s specification .


public Joiner skipNulls() {
    return new Joiner(this) {
      @Override
      public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException {
        checkNotNull(appendable, "appendable");
        checkNotNull(parts, "parts");
        while (parts.hasNext()) {
          Object part = parts.next();
          if (part != null) {
            appendable.append(Joiner.this.toString(part));
            break;
          }
        }
        while (parts.hasNext()) {
          Object part = parts.next();
          if (part != null) {
            appendable.append(separator);
            appendable.append(Joiner.this.toString(part));
          }
        }
        return appendable;
      }

      @Override
      public Joiner useForNull(String nullText) {
        throw new UnsupportedOperationException("already specified skipNulls");
      }

      @Override
      public MapJoiner withKeyValueSeparator(String kvs) {
        throw new UnsupportedOperationException("can't use .skipNulls() with maps");
      }
    };
  }

public
Joiner
skipNulls
(
)
{
return
new
Joiner
(
this
)
{
@
Override
public
<
A
extends
Appendable
>
A
appendTo
(
A
appendable
,
Iterator
<
>
parts
)
throws
IOException
{
checkNotNull
(
appendable
,
"appendable"
)
;
checkNotNull
(
parts
,
"parts"
)
;
while
(
parts
.
hasNext
(
)
)
{
Object
part
=
parts
.
next
(
)
;
if
(
part
!=
)
{
appendable
.
append
(
Joiner
.
this
.
toString
(
part
)
)
;
break
;
}
}
while
(
parts
.
hasNext
(
)
)
{
Object
part
=
parts
.
next
(
)
;
if
(
part
!=
)
{
appendable
.
append
(
separator
)
;
appendable
.
append
(
Joiner
.
this
.
toString
(
part
)
)
;
}
}
return
appendable
;
}
@
Override
public
Joiner
useForNull
(
String
nullText
)
{
throw
new
UnsupportedOperationException
(
"already specified skipNulls"
)
;
}
@
Override
public
MapJoiner
withKeyValueSeparator
(
String
kvs
)
{
throw
new
UnsupportedOperationException
(
"can't use .skipNulls() with maps"
)
;
}
}
;
}

Returns a joiner with the same behavior as this joiner, except automatically skipping over any
provided null elements.

Returns a joiner with the same behavior as this joiner except automatically skipping over any provided null elements .


public static ImmutableIntArray of(int first, int... rest) {
    checkArgument(
        rest.length <= Integer.MAX_VALUE - 1, "the total number of elements must fit in an int");
    int[] array = new int[rest.length + 1];
    array[0] = first;
    System.arraycopy(rest, 0, array, 1, rest.length);
    return new ImmutableIntArray(array);
  }

okay since we have to copy the just-created array anyway.

okay since we have to copy the just - created array anyway .


public ImmutableIntArray subArray(int startIndex, int endIndex) {
    Preconditions.checkPositionIndexes(startIndex, endIndex, length());
    return startIndex == endIndex
        ? EMPTY
        : new ImmutableIntArray(array, start + startIndex, start + endIndex);
  }

public ImmutableIntArray subArray ( int startIndex , int endIndex ) { Preconditions . checkPositionIndexes ( startIndex , endIndex , length ( ) ) ; return startIndex == endIndex ? EMPTY : new ImmutableIntArray ( array , start + startIndex , start + endIndex ) ; }

Returns a new immutable array containing the values in the specified range.

Performance note: The returned array has the same full memory footprint as this one
does (no actual copying is performed). To reduce memory usage, use {@code subArray(start,
end).trimmed()}.

Returns a new immutable array containing the values in the specified range .


@Override
  @CanIgnoreReturnValue
  public int read() throws IOException {
    int b = in.read();
    if (b != -1) {
      hasher.putByte((byte) b);
    }
    return b;
  }

@ Override @ CanIgnoreReturnValue public int read ( ) throws IOException { int b = in . read ( ) ; if ( b != - 1 ) { hasher . putByte ( ( byte ) b ) ; } return b ; }

Reads the next byte of data from the underlying input stream and updates the hasher with the
byte read.

Reads the next byte of data from the underlying input stream and updates the hasher with the byte read .


@Override
  @CanIgnoreReturnValue
  public int read(byte[] bytes, int off, int len) throws IOException {
    int numOfBytesRead = in.read(bytes, off, len);
    if (numOfBytesRead != -1) {
      hasher.putBytes(bytes, off, numOfBytesRead);
    }
    return numOfBytesRead;
  }

@ Override @ CanIgnoreReturnValue public int read ( byte [ ] bytes , int off , int len ) throws IOException { int numOfBytesRead = in . read ( bytes , off , len ) ; if ( numOfBytesRead != - 1 ) { hasher . putBytes ( bytes , off , numOfBytesRead ) ; } return numOfBytesRead ; }

Reads the specified bytes of data from the underlying input stream and updates the hasher with
the bytes read.

Reads the specified bytes of data from the underlying input stream and updates the hasher with the bytes read .


static <K, V> void writeMap(Map<K, V> map, ObjectOutputStream stream) throws IOException {
    stream.writeInt(map.size());
    for (Map.Entry<K, V> entry : map.entrySet()) {
      stream.writeObject(entry.getKey());
      stream.writeObject(entry.getValue());
    }
  }

static < K , V > void writeMap ( Map < K , V > map , ObjectOutputStream stream ) throws IOException { stream . writeInt ( map . size ( ) ) ; for ( Map . Entry < K , V > entry : map . entrySet ( ) ) { stream . writeObject ( entry . getKey ( ) ) ; stream . writeObject ( entry . getValue ( ) ) ; } }

Stores the contents of a map in an output stream, as part of serialization. It does not support
concurrent maps whose content may change while the method is running.

<p>The serialized output consists of the number of entries, first key, first value, second key,
second value, and so on.

Stores the contents of a map in an output stream as part of serialization . It does not support concurrent maps whose content may change while the method is running .


static <E> void writeMultiset(Multiset<E> multiset, ObjectOutputStream stream)
      throws IOException {
    int entryCount = multiset.entrySet().size();
    stream.writeInt(entryCount);
    for (Multiset.Entry<E> entry : multiset.entrySet()) {
      stream.writeObject(entry.getElement());
      stream.writeInt(entry.getCount());
    }
  }

static < E > void writeMultiset ( Multiset < E > multiset , ObjectOutputStream stream ) throws IOException { int entryCount = multiset . entrySet ( ) . size ( ) ; stream . writeInt ( entryCount ) ; for ( Multiset . Entry < E > entry : multiset . entrySet ( ) ) { stream . writeObject ( entry . getElement ( ) ) ; stream . writeInt ( entry . getCount ( ) ) ; } }

Stores the contents of a multiset in an output stream, as part of serialization. It does not
support concurrent multisets whose content may change while the method is running.

<p>The serialized output consists of the number of distinct elements, the first element, its
count, the second element, its count, and so on.

Stores the contents of a multiset in an output stream as part of serialization . It does not support concurrent multisets whose content may change while the method is running .


static <T> FieldSetter<T> getFieldSetter(final Class<T> clazz, String fieldName) {
    try {
      Field field = clazz.getDeclaredField(fieldName);
      return new FieldSetter<T>(field);
    } catch (NoSuchFieldException e) {
      throw new AssertionError(e); // programmer error
    }
  }

static
<
T
>
FieldSetter
<
T
>
getFieldSetter
(
final
Class
<
T
>
clazz
,
String
fieldName
)
{
try
{
Field
field
=
clazz
.
getDeclaredField
(
fieldName
)
;
return
new
FieldSetter
<
T
>
(
field
)
;
}
catch
(
NoSuchFieldException
e
)
{
throw
new
AssertionError
(
e
)
;
// programmer error
}
}

Secret sauce for setting final fields; don't make it public.

Secret sauce for setting final fields ; don t make it public .


@CanIgnoreReturnValue
  public Stopwatch start() {
    checkState(!isRunning, "This stopwatch is already running.");
    isRunning = true;
    startTick = ticker.read();
    return this;
  }

@
CanIgnoreReturnValue
public
Stopwatch
start
(
)
{
checkState
(
!
isRunning
,
"This stopwatch is already running."
)
;
isRunning
=
true
;
startTick
=
ticker
.
read
(
)
;
return
this
;
}

Starts the stopwatch.

@return this {@code Stopwatch} instance
@throws IllegalStateException if the stopwatch is already running.


@CanIgnoreReturnValue
  @Override
  public int add(E element, int occurrences) {
    checkNotNull(element);
    if (occurrences == 0) {
      return count(element);
    }
    CollectPreconditions.checkPositive(occurrences, "occurences");

    while (true) {
      AtomicInteger existingCounter = Maps.safeGet(countMap, element);
      if (existingCounter == null) {
        existingCounter = countMap.putIfAbsent(element, new AtomicInteger(occurrences));
        if (existingCounter == null) {
          return 0;
        }
        // existingCounter != null: fall through to operate against the existing AtomicInteger
      }

      while (true) {
        int oldValue = existingCounter.get();
        if (oldValue != 0) {
          try {
            int newValue = IntMath.checkedAdd(oldValue, occurrences);
            if (existingCounter.compareAndSet(oldValue, newValue)) {
              // newValue can't == 0, so no need to check & remove
              return oldValue;
            }
          } catch (ArithmeticException overflow) {
            throw new IllegalArgumentException(
                "Overflow adding " + occurrences + " occurrences to a count of " + oldValue);
          }
        } else {
          // In the case of a concurrent remove, we might observe a zero value, which means another
          // thread is about to remove (element, existingCounter) from the map. Rather than wait,
          // we can just do that work here.
          AtomicInteger newCounter = new AtomicInteger(occurrences);
          if ((countMap.putIfAbsent(element, newCounter) == null)
              || countMap.replace(element, existingCounter, newCounter)) {
            return 0;
          }
          break;
        }
      }

      // If we're still here, there was a race, so just try again.
    }
  }

Adds a number of occurrences of the specified element to this multiset.

@param element the element to add
@param occurrences the number of occurrences to add
@return the previous count of the element before the operation; possibly zero
@throws IllegalArgumentException if {@code occurrences} is negative, or if the resulting amount
would exceed {@link Integer#MAX_VALUE}

Adds a number of occurrences of the specified element to this multiset .


private void resizeMeMaybe(int newSize) {
    int entriesSize = entries.length;
    if (newSize > entriesSize) {
      int newCapacity = entriesSize + Math.max(1, entriesSize >>> 1);
      if (newCapacity < 0) {
        newCapacity = Integer.MAX_VALUE;
      }
      if (newCapacity != entriesSize) {
        resizeEntries(newCapacity);
      }
    }
  }

private void resizeMeMaybe ( int newSize ) { int entriesSize = entries . length ; if ( newSize > entriesSize ) { int newCapacity = entriesSize + Math . max ( 1 , entriesSize >>> 1 ) ; if ( newCapacity < 0 ) { newCapacity = Integer . MAX_VALUE ; } if ( newCapacity != entriesSize ) { resizeEntries ( newCapacity ) ; } } }

Resizes the entries storage if necessary.

Resizes the entries storage if necessary .


private static InetAddress bytesToInetAddress(byte[] addr) {
    try {
      return InetAddress.getByAddress(addr);
    } catch (UnknownHostException e) {
      throw new AssertionError(e);
    }
  }

private static InetAddress bytesToInetAddress ( byte [ ] addr ) { try { return InetAddress . getByAddress ( addr ) ; } catch ( UnknownHostException e ) { throw new AssertionError ( e ) ; } }

Convert a byte array into an InetAddress.

<p>{@link InetAddress#getByAddress} is documented as throwing a checked exception "if IP
address is of illegal length." We replace it with an unchecked exception, for use by callers
who already know that addr is an array of length 4 or 16.

@param addr the raw 4-byte or 16-byte IP address in big-endian order
@return an InetAddress object created from the raw IP address

Convert a byte array into an InetAddress .


private static void compressLongestRunOfZeroes(int[] hextets) {
    int bestRunStart = -1;
    int bestRunLength = -1;
    int runStart = -1;
    for (int i = 0; i < hextets.length + 1; i++) {
      if (i < hextets.length && hextets[i] == 0) {
        if (runStart < 0) {
          runStart = i;
        }
      } else if (runStart >= 0) {
        int runLength = i - runStart;
        if (runLength > bestRunLength) {
          bestRunStart = runStart;
          bestRunLength = runLength;
        }
        runStart = -1;
      }
    }
    if (bestRunLength >= 2) {
      Arrays.fill(hextets, bestRunStart, bestRunStart + bestRunLength, -1);
    }
  }

private static void compressLongestRunOfZeroes ( int [ ] hextets ) { int bestRunStart = - 1 ; int bestRunLength = - 1 ; int runStart = - 1 ; for ( int i = 0 ; i < hextets . length + 1 ; i ++ ) { if ( i < hextets . length && hextets [ i ] == 0 ) { if ( runStart < 0 ) { runStart = i ; } } else if ( runStart >= 0 ) { int runLength = i - runStart ; if ( runLength > bestRunLength ) { bestRunStart = runStart ; bestRunLength = runLength ; } runStart = - 1 ; } } if ( bestRunLength >= 2 ) { Arrays . fill ( hextets , bestRunStart , bestRunStart + bestRunLength , - 1 ) ; } }

Identify and mark the longest run of zeroes in an IPv6 address.

<p>Only runs of two or more hextets are considered. In case of a tie, the leftmost run wins. If
a qualifying run is found, its hextets are replaced by the sentinel value -1.

@param hextets {@code int[]} mutable array of eight 16-bit hextets

Identify and mark the longest run of zeroes in an IPv6 address .


private static String hextetsToIPv6String(int[] hextets) {
    // While scanning the array, handle these state transitions:
    //   start->num => "num"     start->gap => "::"
    //   num->num   => ":num"    num->gap   => "::"
    //   gap->num   => "num"     gap->gap   => ""
    StringBuilder buf = new StringBuilder(39);
    boolean lastWasNumber = false;
    for (int i = 0; i < hextets.length; i++) {
      boolean thisIsNumber = hextets[i] >= 0;
      if (thisIsNumber) {
        if (lastWasNumber) {
          buf.append(':');
        }
        buf.append(Integer.toHexString(hextets[i]));
      } else {
        if (i == 0 || lastWasNumber) {
          buf.append("::");
        }
      }
      lastWasNumber = thisIsNumber;
    }
    return buf.toString();
  }

//   gap->num   => "num"     gap->gap   => ""

Convert a list of hextets into a human-readable IPv6 address.

<p>In order for "::" compression to work, the input should contain negative sentinel values in
place of the elided zeroes.

@param hextets {@code int[]} array of eight 16-bit hextets, or -1s

Convert a list of hextets into a human - readable IPv6 address .


public static InetAddress forUriString(String hostAddr) {
    InetAddress addr = forUriStringNoThrow(hostAddr);
    if (addr == null) {
      throw formatIllegalArgumentException("Not a valid URI IP literal: '%s'", hostAddr);
    }

    return addr;
  }

public
static
InetAddress
forUriString
(
String
hostAddr
)
{
InetAddress
addr
=
forUriStringNoThrow
(
hostAddr
)
;
if
(
addr
==
)
{
throw
formatIllegalArgumentException
(
"Not a valid URI IP literal: '%s'"
,
hostAddr
)
;
}
return
addr
;
}

Returns an InetAddress representing the literal IPv4 or IPv6 host portion of a URL, encoded in
the format specified by RFC 3986 section 3.2.2.

This function is similar to {@link InetAddresses#forString(String)}, however, it requires
that IPv6 addresses are surrounded by square brackets.

This function is the inverse of {@link InetAddresses#toUriString(java.net.InetAddress)}.

@param hostAddr A RFC 3986 section 3.2.2 encoded IPv4 or IPv6 address
@return an InetAddress representing the address in {@code hostAddr}
@throws IllegalArgumentException if {@code hostAddr} is not a valid IPv4 address, or IPv6
address surrounded by square brackets

Returns an InetAddress representing the literal IPv4 or IPv6 host portion of a URL encoded in the format specified by RFC 3986 section 3 . 2 . 2 .


public static boolean isCompatIPv4Address(Inet6Address ip) {
    if (!ip.isIPv4CompatibleAddress()) {
      return false;
    }

    byte[] bytes = ip.getAddress();
    if ((bytes[12] == 0)
        && (bytes[13] == 0)
        && (bytes[14] == 0)
        && ((bytes[15] == 0) || (bytes[15] == 1))) {
      return false;
    }

    return true;
  }

public static boolean isCompatIPv4Address ( Inet6Address ip ) { if ( ! ip . isIPv4CompatibleAddress ( ) ) { return false ; } byte [ ] bytes = ip . getAddress ( ) ; if ( ( bytes [ 12 ] == 0 ) && ( bytes [ 13 ] == 0 ) && ( bytes [ 14 ] == 0 ) && ( ( bytes [ 15 ] == 0 ) || ( bytes [ 15 ] == 1 ) ) ) { return false ; } return true ; }

Evaluates whether the argument is an IPv6 "compat" address.

An "IPv4 compatible", or "compat", address is one with 96 leading bits of zero, with the
remaining 32 bits interpreted as an IPv4 address. These are conventionally represented in
string literals as {@code "::192.168.0.1"}, though {@code "::c0a8:1"} is also considered an
IPv4 compatible address (and equivalent to {@code "::192.168.0.1"}).

For more on IPv4 compatible addresses see section 2.5.5.1 of RFC 4291.

NOTE: This method is different from {@link Inet6Address#isIPv4CompatibleAddress} in that it
more correctly classifies {@code "::"} and {@code "::1"} as proper IPv6 addresses (which they
are), NOT IPv4 compatible addresses (which they are generally NOT considered to be).

@param ip {@link Inet6Address} to be examined for embedded IPv4 compatible address format
@return {@code true} if the argument is a valid "compat" address

Evaluates whether the argument is an IPv6 compat address .


public static Inet4Address getCompatIPv4Address(Inet6Address ip) {
    checkArgument(
        isCompatIPv4Address(ip), "Address '%s' is not IPv4-compatible.", toAddrString(ip));

    return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16));
  }

public
static
Inet4Address
getCompatIPv4Address
(
Inet6Address
ip
)
{
checkArgument
(
isCompatIPv4Address
(
ip
)
,
"Address '%s' is not IPv4-compatible."
,
toAddrString
(
ip
)
)
;
return
getInet4Address
(
Arrays
.
copyOfRange
(
ip
.
getAddress
(
)
,
12
,
16
)
)
;
}

Returns the IPv4 address embedded in an IPv4 compatible address.

@param ip {@link Inet6Address} to be examined for an embedded IPv4 address
@return {@link Inet4Address} of the embedded IPv4 address
@throws IllegalArgumentException if the argument is not a valid IPv4 compatible address

Returns the IPv4 address embedded in an IPv4 compatible address .


public static boolean isTeredoAddress(Inet6Address ip) {
    byte[] bytes = ip.getAddress();
    return (bytes[0] == (byte) 0x20)
        && (bytes[1] == (byte) 0x01)
        && (bytes[2] == 0)
        && (bytes[3] == 0);
  }

public static boolean isTeredoAddress ( Inet6Address ip ) { byte [ ] bytes = ip . getAddress ( ) ; return ( bytes [ 0 ] == ( byte ) 0x20 ) && ( bytes [ 1 ] == ( byte ) 0x01 ) && ( bytes [ 2 ] == 0 ) && ( bytes [ 3 ] == 0 ) ; }

Evaluates whether the argument is a Teredo address.

<p>Teredo addresses begin with the {@code "2001::/32"} prefix.

@param ip {@link Inet6Address} to be examined for Teredo address format
@return {@code true} if the argument is a Teredo address

Evaluates whether the argument is a Teredo address .


public static boolean isIsatapAddress(Inet6Address ip) {

    // If it's a Teredo address with the right port (41217, or 0xa101)
    // which would be encoded as 0x5efe then it can't be an ISATAP address.
    if (isTeredoAddress(ip)) {
      return false;
    }

    byte[] bytes = ip.getAddress();

    if ((bytes[8] | (byte) 0x03) != (byte) 0x03) {

      // Verify that high byte of the 64 bit identifier is zero, modulo
      // the U/L and G bits, with which we are not concerned.
      return false;
    }

    return (bytes[9] == (byte) 0x00) && (bytes[10] == (byte) 0x5e) && (bytes[11] == (byte) 0xfe);
  }

Evaluates whether the argument is an ISATAP address.

From RFC 5214: "ISATAP interface identifiers are constructed in Modified EUI-64 format [...]
by concatenating the 24-bit IANA OUI (00-00-5E), the 8-bit hexadecimal value 0xFE, and a 32-bit
IPv4 address in network byte order [...]"

For more on ISATAP addresses see section 6.1 of RFC 5214.

@param ip {@link Inet6Address} to be examined for ISATAP address format
@return {@code true} if the argument is an ISATAP address

Evaluates whether the argument is an ISATAP address .


public static Inet4Address getIsatapIPv4Address(Inet6Address ip) {
    checkArgument(isIsatapAddress(ip), "Address '%s' is not an ISATAP address.", toAddrString(ip));

    return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16));
  }

Returns the IPv4 address embedded in an ISATAP address.

@param ip {@link Inet6Address} to be examined for embedded IPv4 in ISATAP address
@return {@link Inet4Address} of embedded IPv4 in an ISATAP address
@throws IllegalArgumentException if the argument is not a valid IPv6 ISATAP address

Returns the IPv4 address embedded in an ISATAP address .


public static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip) {
    if (isCompatIPv4Address(ip)) {
      return getCompatIPv4Address(ip);
    }

    if (is6to4Address(ip)) {
      return get6to4IPv4Address(ip);
    }

    if (isTeredoAddress(ip)) {
      return getTeredoInfo(ip).getClient();
    }

    throw formatIllegalArgumentException("'%s' has no embedded IPv4 address.", toAddrString(ip));
  }

public
static
Inet4Address
getEmbeddedIPv4ClientAddress
(
Inet6Address
ip
)
{
if
(
isCompatIPv4Address
(
ip
)
)
{
return
getCompatIPv4Address
(
ip
)
;
}
if
(
is6to4Address
(
ip
)
)
{
return
get6to4IPv4Address
(
ip
)
;
}
if
(
isTeredoAddress
(
ip
)
)
{
return
getTeredoInfo
(
ip
)
.
getClient
(
)
;
}
throw
formatIllegalArgumentException
(
"'%s' has no embedded IPv4 address."
,
toAddrString
(
ip
)
)
;
}

Examines the Inet6Address to extract the embedded IPv4 client address if the InetAddress is an
IPv6 address of one of the specified address types that contain an embedded IPv4 address.

<p>NOTE: ISATAP addresses are explicitly excluded from this method due to their trivial
spoofability. With other transition addresses spoofing involves (at least) infection of one's
BGP routing table.

@param ip {@link Inet6Address} to be examined for embedded IPv4 client address
@return {@link Inet4Address} of embedded IPv4 client address
@throws IllegalArgumentException if the argument does not have a valid embedded IPv4 address

Examines the Inet6Address to extract the embedded IPv4 client address if the InetAddress is an IPv6 address of one of the specified address types that contain an embedded IPv4 address .


public static boolean isMappedIPv4Address(String ipString) {
    byte[] bytes = ipStringToBytes(ipString);
    if (bytes != null && bytes.length == 16) {
      for (int i = 0; i < 10; i++) {
        if (bytes[i] != 0) {
          return false;
        }
      }
      for (int i = 10; i < 12; i++) {
        if (bytes[i] != (byte) 0xff) {
          return false;
        }
      }
      return true;
    }
    return false;
  }

public static boolean isMappedIPv4Address ( String ipString ) { byte [ ] bytes = ipStringToBytes ( ipString ) ; if ( bytes != null && bytes . length == 16 ) { for ( int i = 0 ; i < 10 ; i ++ ) { if ( bytes [ i ] != 0 ) { return false ; } } for ( int i = 10 ; i < 12 ; i ++ ) { if ( bytes [ i ] != ( byte ) 0xff ) { return false ; } } return true ; } return false ; }

Evaluates whether the argument is an "IPv4 mapped" IPv6 address.

An "IPv4 mapped" address is anything in the range ::ffff:0:0/96 (sometimes written as
::ffff:0.0.0.0/96), with the last 32 bits interpreted as an IPv4 address.

For more on IPv4 mapped addresses see section 2.5.5.2 of RFC 4291.

Note: This method takes a {@code String} argument because {@link InetAddress} automatically
collapses mapped addresses to IPv4. (It is actually possible to avoid this using one of the
obscure {@link Inet6Address} methods, but it would be unwise to depend on such a
poorly-documented feature.)

@param ipString {@code String} to be examined for embedded IPv4-mapped IPv6 address format
@return {@code true} if the argument is a valid "mapped" address
@since 10.0

Evaluates whether the argument is an IPv4 mapped IPv6 address .


public static InetAddress decrement(InetAddress address) {
    byte[] addr = address.getAddress();
    int i = addr.length - 1;
    while (i >= 0 && addr[i] == (byte) 0x00) {
      addr[i] = (byte) 0xff;
      i--;
    }

    checkArgument(i >= 0, "Decrementing %s would wrap.", address);

    addr[i]--;
    return bytesToInetAddress(addr);
  }

public
static
InetAddress
decrement
(
InetAddress
address
)
{
byte
[
]
addr
=
address
.
getAddress
(
)
;
int
i
=
addr
.
length
1
;
while
(
i
>=
0
&&
addr
[
i
]
==
(
byte
)
0x00
)
{
addr
[
i
]
=
(
byte
)
0xff
;
i
;
}
checkArgument
(
i
>=
0
,
"Decrementing %s would wrap."
,
address
)
;
addr
[
i
]
;
return
bytesToInetAddress
(
addr
)
;
}

Returns a new InetAddress that is one less than the passed in address. This method works for
both IPv4 and IPv6 addresses.

@param address the InetAddress to decrement
@return a new InetAddress that is one less than the passed in address
@throws IllegalArgumentException if InetAddress is at the beginning of its range
@since 18.0

Returns a new InetAddress that is one less than the passed in address . This method works for both IPv4 and IPv6 addresses .


@Beta
  public static BufferedReader newReader(File file, Charset charset) throws FileNotFoundException {
    checkNotNull(file);
    checkNotNull(charset);
    return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
  }

@ Beta public static BufferedReader newReader ( File file , Charset charset ) throws FileNotFoundException { checkNotNull ( file ) ; checkNotNull ( charset ) ; return new BufferedReader ( new InputStreamReader ( new FileInputStream ( file ) , charset ) ) ; }

Returns a buffered reader that reads from a file using the given character set.

{@link java.nio.file.Path} equivalent: {@link
java.nio.file.Files#newBufferedReader(java.nio.file.Path, Charset)}.

@param file the file to read from
@param charset the charset used to decode the input stream; see {@link StandardCharsets} for
helpful predefined constants
@return the buffered reader

Returns a buffered reader that reads from a file using the given character set .


@Beta
  public static void write(byte[] from, File to) throws IOException {
    asByteSink(to).write(from);
  }

@ Beta public static void write ( byte [ ] from , File to ) throws IOException { asByteSink ( to ) . write ( from ) ; }

Overwrites a file with the contents of a byte array.

{@link java.nio.file.Path} equivalent: {@link
java.nio.file.Files#write(java.nio.file.Path, byte[], java.nio.file.OpenOption...)}.

@param from the bytes to write
@param to the destination file
@throws IOException if an I/O error occurs

Overwrites a file with the contents of a byte array .


@Beta
  public static void copy(File from, OutputStream to) throws IOException {
    asByteSource(from).copyTo(to);
  }

@ Beta public static void copy ( File from , OutputStream to ) throws IOException { asByteSource ( from ) . copyTo ( to ) ; }

Copies all bytes from a file to an output stream.

{@link java.nio.file.Path} equivalent: {@link
java.nio.file.Files#copy(java.nio.file.Path, OutputStream)}.

@param from the source file
@param to the output stream
@throws IOException if an I/O error occurs

Copies all bytes from a file to an output stream .


@Beta
  public static void copy(File from, File to) throws IOException {
    checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to);
    asByteSource(from).copyTo(asByteSink(to));
  }

Copies all the bytes from one file to another.

Copying is not an atomic operation - in the case of an I/O error, power loss, process
termination, or other problems, {@code to} may not be a complete copy of {@code from}. If you
need to guard against those conditions, you should employ other file-level synchronization.

Warning: If {@code to} represents an existing file, that file will be overwritten
with the contents of {@code from}. If {@code to} and {@code from} refer to the same
file, the contents of that file will be deleted.

{@link java.nio.file.Path} equivalent: {@link
java.nio.file.Files#copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...)}.

@param from the source file
@param to the destination file
@throws IOException if an I/O error occurs
@throws IllegalArgumentException if {@code from.equals(to)}

Copies all the bytes from one file to another .


@Beta
  @SuppressWarnings("GoodTime") // reading system time without TimeSource
  public static void touch(File file) throws IOException {
    checkNotNull(file);
    if (!file.createNewFile() && !file.setLastModified(System.currentTimeMillis())) {
      throw new IOException("Unable to update modification time of " + file);
    }
  }

Creates an empty file or updates the last updated timestamp on the same as the unix command of
the same name.

@param file the file to create or update
@throws IOException if an I/O error occurs

Creates an empty file or updates the last updated timestamp on the same as the unix command of the same name .


@Beta
  @Deprecated
  public
  static String readFirstLine(File file, Charset charset) throws IOException {
    return asCharSource(file, charset).readFirstLine();
  }

@ Beta @ Deprecated public static String readFirstLine ( File file , Charset charset ) throws IOException { return asCharSource ( file , charset ) . readFirstLine ( ) ; }

Reads the first line from a file. The line does not include line-termination characters, but
does include other leading and trailing whitespace.

@param file the file to read from
@param charset the charset used to decode the input stream; see {@link StandardCharsets} for
helpful predefined constants
@return the first line, or null if the file is empty
@throws IOException if an I/O error occurs
@deprecated Prefer {@code asCharSource(file, charset).readFirstLine()}. This method is
scheduled to be removed in January 2019.

Reads the first line from a file . The line does not include line - termination characters but does include other leading and trailing whitespace .


@Beta
  public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) {
    checkNonnegative(expectedSize, "expectedSize");
    return new Builder<>(expectedSize);
  }

@ Beta public static < K , V > Builder < K , V > builderWithExpectedSize ( int expectedSize ) { checkNonnegative ( expectedSize , "expectedSize" ) ; return new Builder <> ( expectedSize ) ; }

Returns a new builder, expecting the specified number of entries to be added.

If {@code expectedSize} is exactly the number of entries added to the builder before {@link
Builder#build} is called, the builder is likely to perform better than an unsized {@link
#builder()} would have.

It is not specified if any performance benefits apply if {@code expectedSize} is close to,
but not exactly, the number of entries added to the builder.

@since 23.1

Returns a new builder expecting the specified number of entries to be added .


@CanIgnoreReturnValue
  @Deprecated
  @Override
  public V forcePut(K key, V value) {
    throw new UnsupportedOperationException();
  }

@ CanIgnoreReturnValue @ Deprecated @ Override public V forcePut ( K key , V value ) { throw new UnsupportedOperationException ( ) ; }

Guaranteed to throw an exception and leave the bimap unmodified.

@throws UnsupportedOperationException always
@deprecated Unsupported operation.

Guaranteed to throw an exception and leave the bimap unmodified .


public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create(
      Iterable<? extends E> initialContents) {
    return new Builder<E>(Ordering.<E>natural()).create(initialContents);
  }

public static < E extends Comparable < E > > MinMaxPriorityQueue < E > create ( Iterable < ? extends E > initialContents ) { return new Builder < E > ( Ordering . < E > natural ( ) ) . create ( initialContents ) ; }

Creates a new min-max priority queue using natural order, no maximum size, and initially
containing the given elements.

Creates a new min - max priority queue using natural order no maximum size and initially containing the given elements .


private int calculateNewCapacity() {
    int oldCapacity = queue.length;
    int newCapacity =
        (oldCapacity < 64) ? (oldCapacity + 1) * 2 : IntMath.checkedMultiply(oldCapacity / 2, 3);
    return capAtMaximumSize(newCapacity, maximumSize);
  }

private int calculateNewCapacity ( ) { int oldCapacity = queue . length ; int newCapacity = ( oldCapacity < 64 ) ? ( oldCapacity + 1 ) * 2 : IntMath . checkedMultiply ( oldCapacity / 2 , 3 ) ; return capAtMaximumSize ( newCapacity , maximumSize ) ; }

Returns ~2x the old capacity if small; ~1.5x otherwise.

Returns ~2x the old capacity if small ; ~1 . 5x otherwise .


private static HashCode fmix(int h1, int length) {
    h1 ^= length;
    h1 ^= h1 >>> 16;
    h1 *= 0x85ebca6b;
    h1 ^= h1 >>> 13;
    h1 *= 0xc2b2ae35;
    h1 ^= h1 >>> 16;
    return HashCode.fromInt(h1);
  }

private static HashCode fmix ( int h1 , int length ) { h1 ^= length ; h1 ^= h1 >>> 16 ; h1 *= 0x85ebca6b ; h1 ^= h1 >>> 13 ; h1 *= 0xc2b2ae35 ; h1 ^= h1 >>> 16 ; return HashCode . fromInt ( h1 ) ; }

Finalization mix - force all bits of a hash block to avalanche


public static <S extends Comparable<? super S>> ElementOrder<S> natural() {
    return new ElementOrder<S>(Type.SORTED, Ordering.<S>natural());
  }

public static < S extends Comparable < ? super S > > ElementOrder < S > natural ( ) { return new ElementOrder < S > ( Type . SORTED , Ordering . < S > natural ( ) ) ; }

Returns an instance which specifies that the natural ordering of the elements is guaranteed.

Returns an instance which specifies that the natural ordering of the elements is guaranteed .


@SuppressWarnings("GoodTime") // should accept a java.time.Duration
  public boolean enter(long time, TimeUnit unit) {
    final long timeoutNanos = toSafeNanos(time, unit);
    final ReentrantLock lock = this.lock;
    if (!fair && lock.tryLock()) {
      return true;
    }
    boolean interrupted = Thread.interrupted();
    try {
      final long startTime = System.nanoTime();
      for (long remainingNanos = timeoutNanos; ; ) {
        try {
          return lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS);
        } catch (InterruptedException interrupt) {
          interrupted = true;
          remainingNanos = remainingNanos(startTime, timeoutNanos);
        }
      }
    } finally {
      if (interrupted) {
        Thread.currentThread().interrupt();
      }
    }
  }

@
SuppressWarnings
(
"GoodTime"
)
// should accept a java.time.Duration
public
boolean
enter
(
long
time
,
TimeUnit
unit
)
{
final
long
timeoutNanos
=
toSafeNanos
(
time
,
unit
)
;
final
ReentrantLock
lock
=
this
.
lock
;
if
(
!
fair
&&
lock
.
tryLock
(
)
)
{
return
true
;
}
boolean
interrupted
=
Thread
.
interrupted
(
)
;
try
{
final
long
startTime
=
System
.
nanoTime
(
)
;
for
(
long
remainingNanos
=
timeoutNanos
;
;
)
{
try
{
return
lock
.
tryLock
(
remainingNanos
,
TimeUnit
.
NANOSECONDS
)
;
}
catch
(
InterruptedException
interrupt
)
{
interrupted
=
true
;
remainingNanos
=
remainingNanos
(
startTime
,
timeoutNanos
)
;
}
}
}
finally
{
if
(
interrupted
)
{
Thread
.
currentThread
(
)
.
interrupt
(
)
;
}
}
}

Enters this monitor. Blocks at most the given time.

@return whether the monitor was entered

Enters this monitor . Blocks at most the given time .


@SuppressWarnings("GoodTime") // should accept a java.time.Duration
  public boolean enterInterruptibly(long time, TimeUnit unit) throws InterruptedException {
    return lock.tryLock(time, unit);
  }

@
SuppressWarnings
(
"GoodTime"
)
// should accept a java.time.Duration
public
boolean
enterInterruptibly
(
long
time
,
TimeUnit
unit
)
throws
InterruptedException
{
return
lock
.
tryLock
(
time
,
unit
)
;
}

Enters this monitor. Blocks at most the given time, and may be interrupted.

@return whether the monitor was entered
@throws InterruptedException if interrupted while waiting

Enters this monitor . Blocks at most the given time and may be interrupted .


public void enterWhen(Guard guard) throws InterruptedException {
    if (guard.monitor != this) {
      throw new IllegalMonitorStateException();
    }
    final ReentrantLock lock = this.lock;
    boolean signalBeforeWaiting = lock.isHeldByCurrentThread();
    lock.lockInterruptibly();

    boolean satisfied = false;
    try {
      if (!guard.isSatisfied()) {
        await(guard, signalBeforeWaiting);
      }
      satisfied = true;
    } finally {
      if (!satisfied) {
        leave();
      }
    }
  }

public void enterWhen ( Guard guard ) throws InterruptedException { if ( guard . monitor != this ) { throw new IllegalMonitorStateException ( ) ; } final ReentrantLock lock = this . lock ; boolean signalBeforeWaiting = lock . isHeldByCurrentThread ( ) ; lock . lockInterruptibly ( ) ; boolean satisfied = false ; try { if ( ! guard . isSatisfied ( ) ) { await ( guard , signalBeforeWaiting ) ; } satisfied = true ; } finally { if ( ! satisfied ) { leave ( ) ; } } }

Enters this monitor when the guard is satisfied. Blocks indefinitely, but may be interrupted.

@throws InterruptedException if interrupted while waiting

Enters this monitor when the guard is satisfied . Blocks indefinitely but may be interrupted .


@SuppressWarnings("GoodTime") // should accept a java.time.Duration
  public boolean enterWhen(Guard guard, long time, TimeUnit unit) throws InterruptedException {
    final long timeoutNanos = toSafeNanos(time, unit);
    if (guard.monitor != this) {
      throw new IllegalMonitorStateException();
    }
    final ReentrantLock lock = this.lock;
    boolean reentrant = lock.isHeldByCurrentThread();
    long startTime = 0L;

    locked:
    {
      if (!fair) {
        // Check interrupt status to get behavior consistent with fair case.
        if (Thread.interrupted()) {
          throw new InterruptedException();
        }
        if (lock.tryLock()) {
          break locked;
        }
      }
      startTime = initNanoTime(timeoutNanos);
      if (!lock.tryLock(time, unit)) {
        return false;
      }
    }

    boolean satisfied = false;
    boolean threw = true;
    try {
      satisfied =
          guard.isSatisfied()
              || awaitNanos(
                  guard,
                  (startTime == 0L) ? timeoutNanos : remainingNanos(startTime, timeoutNanos),
                  reentrant);
      threw = false;
      return satisfied;
    } finally {
      if (!satisfied) {
        try {
          // Don't need to signal if timed out, but do if interrupted
          if (threw && !reentrant) {
            signalNextWaiter();
          }
        } finally {
          lock.unlock();
        }
      }
    }
  }

Enters this monitor when the guard is satisfied. Blocks at most the given time, including both
the time to acquire the lock and the time to wait for the guard to be satisfied, and may be
interrupted.

@return whether the monitor was entered, which guarantees that the guard is now satisfied
@throws InterruptedException if interrupted while waiting

Enters this monitor when the guard is satisfied . Blocks at most the given time including both the time to acquire the lock and the time to wait for the guard to be satisfied and may be interrupted .


public void enterWhenUninterruptibly(Guard guard) {
    if (guard.monitor != this) {
      throw new IllegalMonitorStateException();
    }
    final ReentrantLock lock = this.lock;
    boolean signalBeforeWaiting = lock.isHeldByCurrentThread();
    lock.lock();

    boolean satisfied = false;
    try {
      if (!guard.isSatisfied()) {
        awaitUninterruptibly(guard, signalBeforeWaiting);
      }
      satisfied = true;
    } finally {
      if (!satisfied) {
        leave();
      }
    }
  }

public void enterWhenUninterruptibly ( Guard guard ) { if ( guard . monitor != this ) { throw new IllegalMonitorStateException ( ) ; } final ReentrantLock lock = this . lock ; boolean signalBeforeWaiting = lock . isHeldByCurrentThread ( ) ; lock . lock ( ) ; boolean satisfied = false ; try { if ( ! guard . isSatisfied ( ) ) { awaitUninterruptibly ( guard , signalBeforeWaiting ) ; } satisfied = true ; } finally { if ( ! satisfied ) { leave ( ) ; } } }

Enters this monitor when the guard is satisfied. Blocks indefinitely.

Enters this monitor when the guard is satisfied . Blocks indefinitely .


public boolean enterIf(Guard guard) {
    if (guard.monitor != this) {
      throw new IllegalMonitorStateException();
    }
    final ReentrantLock lock = this.lock;
    lock.lock();

    boolean satisfied = false;
    try {
      return satisfied = guard.isSatisfied();
    } finally {
      if (!satisfied) {
        lock.unlock();
      }
    }
  }

public boolean enterIf ( Guard guard ) { if ( guard . monitor != this ) { throw new IllegalMonitorStateException ( ) ; } final ReentrantLock lock = this . lock ; lock . lock ( ) ; boolean satisfied = false ; try { return satisfied = guard . isSatisfied ( ) ; } finally { if ( ! satisfied ) { lock . unlock ( ) ; } } }

Enters this monitor if the guard is satisfied. Blocks indefinitely acquiring the lock, but does
not wait for the guard to be satisfied.

@return whether the monitor was entered, which guarantees that the guard is now satisfied

Enters this monitor if the guard is satisfied . Blocks indefinitely acquiring the lock but does not wait for the guard to be satisfied .


@SuppressWarnings("GoodTime") // should accept a java.time.Duration
  public boolean enterIf(Guard guard, long time, TimeUnit unit) {
    if (guard.monitor != this) {
      throw new IllegalMonitorStateException();
    }
    if (!enter(time, unit)) {
      return false;
    }

    boolean satisfied = false;
    try {
      return satisfied = guard.isSatisfied();
    } finally {
      if (!satisfied) {
        lock.unlock();
      }
    }
  }

@
SuppressWarnings
(
"GoodTime"
)
// should accept a java.time.Duration
public
boolean
enterIf
(
Guard
guard
,
long
time
,
TimeUnit
unit
)
{
if
(
guard
.
monitor
!=
this
)
{
throw
new
IllegalMonitorStateException
(
)
;
}
if
(
!
enter
(
time
,
unit
)
)
{
return
false
;
}
boolean
satisfied
=
false
;
try
{
return
satisfied
=
guard
.
isSatisfied
(
)
;
}
finally
{
if
(
!
satisfied
)
{
lock
.
unlock
(
)
;
}
}
}

Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the
lock, but does not wait for the guard to be satisfied.

@return whether the monitor was entered, which guarantees that the guard is now satisfied

Enters this monitor if the guard is satisfied . Blocks at most the given time acquiring the lock but does not wait for the guard to be satisfied .


public boolean enterIfInterruptibly(Guard guard) throws InterruptedException {
    if (guard.monitor != this) {
      throw new IllegalMonitorStateException();
    }
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();

    boolean satisfied = false;
    try {
      return satisfied = guard.isSatisfied();
    } finally {
      if (!satisfied) {
        lock.unlock();
      }
    }
  }

public boolean enterIfInterruptibly ( Guard guard ) throws InterruptedException { if ( guard . monitor != this ) { throw new IllegalMonitorStateException ( ) ; } final ReentrantLock lock = this . lock ; lock . lockInterruptibly ( ) ; boolean satisfied = false ; try { return satisfied = guard . isSatisfied ( ) ; } finally { if ( ! satisfied ) { lock . unlock ( ) ; } } }

Enters this monitor if the guard is satisfied. Blocks indefinitely acquiring the lock, but does
not wait for the guard to be satisfied, and may be interrupted.

@return whether the monitor was entered, which guarantees that the guard is now satisfied
@throws InterruptedException if interrupted while waiting

Enters this monitor if the guard is satisfied . Blocks indefinitely acquiring the lock but does not wait for the guard to be satisfied and may be interrupted .


public boolean tryEnterIf(Guard guard) {
    if (guard.monitor != this) {
      throw new IllegalMonitorStateException();
    }
    final ReentrantLock lock = this.lock;
    if (!lock.tryLock()) {
      return false;
    }

    boolean satisfied = false;
    try {
      return satisfied = guard.isSatisfied();
    } finally {
      if (!satisfied) {
        lock.unlock();
      }
    }
  }

public boolean tryEnterIf ( Guard guard ) { if ( guard . monitor != this ) { throw new IllegalMonitorStateException ( ) ; } final ReentrantLock lock = this . lock ; if ( ! lock . tryLock ( ) ) { return false ; } boolean satisfied = false ; try { return satisfied = guard . isSatisfied ( ) ; } finally { if ( ! satisfied ) { lock . unlock ( ) ; } } }

Enters this monitor if it is possible to do so immediately and the guard is satisfied. Does not
block acquiring the lock and does not wait for the guard to be satisfied.

Note: This method disregards the fairness setting of this monitor.

@return whether the monitor was entered, which guarantees that the guard is now satisfied

Enters this monitor if it is possible to do so immediately and the guard is satisfied . Does not block acquiring the lock and does not wait for the guard to be satisfied .


public void waitFor(Guard guard) throws InterruptedException {
    if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) {
      throw new IllegalMonitorStateException();
    }
    if (!guard.isSatisfied()) {
      await(guard, true);
    }
  }

public void waitFor ( Guard guard ) throws InterruptedException { if ( ! ( ( guard . monitor == this ) & lock . isHeldByCurrentThread ( ) ) ) { throw new IllegalMonitorStateException ( ) ; } if ( ! guard . isSatisfied ( ) ) { await ( guard , true ) ; } }

Waits for the guard to be satisfied. Waits indefinitely, but may be interrupted. May be called
only by a thread currently occupying this monitor.

@throws InterruptedException if interrupted while waiting

Waits for the guard to be satisfied . Waits indefinitely but may be interrupted . May be called only by a thread currently occupying this monitor .


public void waitForUninterruptibly(Guard guard) {
    if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) {
      throw new IllegalMonitorStateException();
    }
    if (!guard.isSatisfied()) {
      awaitUninterruptibly(guard, true);
    }
  }

public void waitForUninterruptibly ( Guard guard ) { if ( ! ( ( guard . monitor == this ) & lock . isHeldByCurrentThread ( ) ) ) { throw new IllegalMonitorStateException ( ) ; } if ( ! guard . isSatisfied ( ) ) { awaitUninterruptibly ( guard , true ) ; } }

Waits for the guard to be satisfied. Waits indefinitely. May be called only by a thread
currently occupying this monitor.

Waits for the guard to be satisfied . Waits indefinitely . May be called only by a thread currently occupying this monitor .


@SuppressWarnings("GoodTime") // should accept a java.time.Duration
  public boolean waitForUninterruptibly(Guard guard, long time, TimeUnit unit) {
    final long timeoutNanos = toSafeNanos(time, unit);
    if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) {
      throw new IllegalMonitorStateException();
    }
    if (guard.isSatisfied()) {
      return true;
    }
    boolean signalBeforeWaiting = true;
    final long startTime = initNanoTime(timeoutNanos);
    boolean interrupted = Thread.interrupted();
    try {
      for (long remainingNanos = timeoutNanos; ; ) {
        try {
          return awaitNanos(guard, remainingNanos, signalBeforeWaiting);
        } catch (InterruptedException interrupt) {
          interrupted = true;
          if (guard.isSatisfied()) {
            return true;
          }
          signalBeforeWaiting = false;
          remainingNanos = remainingNanos(startTime, timeoutNanos);
        }
      }
    } finally {
      if (interrupted) {
        Thread.currentThread().interrupt();
      }
    }
  }

@
SuppressWarnings
(
"GoodTime"
)
// should accept a java.time.Duration
public
boolean
waitForUninterruptibly
(
Guard
guard
,
long
time
,
TimeUnit
unit
)
{
final
long
timeoutNanos
=
toSafeNanos
(
time
,
unit
)
;
if
(
!
(
(
guard
.
monitor
==
this
)
&
lock
.
isHeldByCurrentThread
(
)
)
)
{
throw
new
IllegalMonitorStateException
(
)
;
}
if
(
guard
.
isSatisfied
(
)
)
{
return
true
;
}
boolean
signalBeforeWaiting
=
true
;
final
long
startTime
=
initNanoTime
(
timeoutNanos
)
;
boolean
interrupted
=
Thread
.
interrupted
(
)
;
try
{
for
(
long
remainingNanos
=
timeoutNanos
;
;
)
{
try
{
return
awaitNanos
(
guard
,
remainingNanos
,
signalBeforeWaiting
)
;
}
catch
(
InterruptedException
interrupt
)
{
interrupted
=
true
;
if
(
guard
.
isSatisfied
(
)
)
{
return
true
;
}
signalBeforeWaiting
=
false
;
remainingNanos
=
remainingNanos
(
startTime
,
timeoutNanos
)
;
}
}
}
finally
{
if
(
interrupted
)
{
Thread
.
currentThread
(
)
.
interrupt
(
)
;
}
}
}

Waits for the guard to be satisfied. Waits at most the given time. May be called only by a
thread currently occupying this monitor.

@return whether the guard is now satisfied

Waits for the guard to be satisfied . Waits at most the given time . May be called only by a thread currently occupying this monitor .


public int getWaitQueueLength(Guard guard) {
    if (guard.monitor != this) {
      throw new IllegalMonitorStateException();
    }
    lock.lock();
    try {
      return guard.waiterCount;
    } finally {
      lock.unlock();
    }
  }

public int getWaitQueueLength ( Guard guard ) { if ( guard . monitor != this ) { throw new IllegalMonitorStateException ( ) ; } lock . lock ( ) ; try { return guard . waiterCount ; } finally { lock . unlock ( ) ; } }

Returns an estimate of the number of threads waiting for the given guard to become satisfied.
Note that because timeouts and interrupts may occur at any time, the estimate serves only as an
upper bound on the actual number of waiters. This method is designed for use in monitoring of
the system state, not for synchronization control.

Returns an estimate of the number of threads waiting for the given guard to become satisfied . Note that because timeouts and interrupts may occur at any time the estimate serves only as an upper bound on the actual number of waiters . This method is designed for use in monitoring of the system state not for synchronization control .


@GuardedBy("lock")
  private void signalNextWaiter() {
    for (Guard guard = activeGuards; guard != null; guard = guard.next) {
      if (isSatisfied(guard)) {
        guard.condition.signal();
        break;
      }
    }
  }

@ GuardedBy ( "lock" ) private void signalNextWaiter ( ) { for ( Guard guard = activeGuards ; guard != null ; guard = guard . next ) { if ( isSatisfied ( guard ) ) { guard . condition . signal ( ) ; break ; } } }

Signals some other thread waiting on a satisfied guard, if one exists.

We manage calls to this method carefully, to signal only when necessary, but never losing a
signal, which is the classic problem of this kind of concurrency construct. We must signal if
the current thread is about to relinquish the lock and may have changed the state protected by
the monitor, thereby causing some guard to be satisfied.

In addition, any thread that has been signalled when its guard was satisfied acquires the
responsibility of signalling the next thread when it again relinquishes the lock. Unlike a
normal Condition, there is no guarantee that an interrupted thread has not been signalled,
since the concurrency control must manage multiple Conditions. So this method must generally be
called when waits are interrupted.

On the other hand, if a signalled thread wakes up to discover that its guard is still not
satisfied, it does *not* need to call this method before returning to wait. This can only
happen due to spurious wakeup (ignorable) or another thread acquiring the lock before the
current thread can and returning the guard to the unsatisfied state. In the latter case the
other thread (last thread modifying the state protected by the monitor) takes over the
responsibility of signalling the next waiter.

This method must not be called from within a beginWaitingFor/endWaitingFor block, or else
the current thread's guard might be mistakenly signalled, leading to a lost signal.

Signals some other thread waiting on a satisfied guard if one exists .


@GuardedBy("lock")
  private void signalAllWaiters() {
    for (Guard guard = activeGuards; guard != null; guard = guard.next) {
      guard.condition.signalAll();
    }
  }

@ GuardedBy ( "lock" ) private void signalAllWaiters ( ) { for ( Guard guard = activeGuards ; guard != null ; guard = guard . next ) { guard . condition . signalAll ( ) ; } }


@GuardedBy("lock")
  private void beginWaitingFor(Guard guard) {
    int waiters = guard.waiterCount++;
    if (waiters == 0) {
      // push guard onto activeGuards
      guard.next = activeGuards;
      activeGuards = guard;
    }
  }

@
GuardedBy
(
"lock"
)
private
void
beginWaitingFor
(
Guard
guard
)
{
int
waiters
=
guard
.
waiterCount
++
;
if
(
waiters
==
0
)
{
// push guard onto activeGuards
guard
.
next
=
activeGuards
;
activeGuards
=
guard
;
}
}

Records that the current thread is about to wait on the specified guard.

Records that the current thread is about to wait on the specified guard .


@GuardedBy("lock")
  private void endWaitingFor(Guard guard) {
    int waiters = --guard.waiterCount;
    if (waiters == 0) {
      // unlink guard from activeGuards
      for (Guard p = activeGuards, pred = null; ; pred = p, p = p.next) {
        if (p == guard) {
          if (pred == null) {
            activeGuards = p.next;
          } else {
            pred.next = p.next;
          }
          p.next = null; // help GC
          break;
        }
      }
    }
  }

@
GuardedBy
(
"lock"
)
private
void
endWaitingFor
(
Guard
guard
)
{
int
waiters
=
guard
.
waiterCount
;
if
(
waiters
==
0
)
{
// unlink guard from activeGuards
for
(
Guard
p
=
activeGuards
,
pred
=
;
;
pred
=
p
,
p
=
p
.
next
)
{
if
(
p
==
guard
)
{
if
(
pred
==
)
{
activeGuards
=
p
.
next
;
}
else
{
pred
.
next
=
p
.
next
;
}
p
.
next
=
;
// help GC
break
;
}
}
}
}

Records that the current thread is no longer waiting on the specified guard.

Records that the current thread is no longer waiting on the specified guard .


@GuardedBy("lock")
  private boolean awaitNanos(Guard guard, long nanos, boolean signalBeforeWaiting)
      throws InterruptedException {
    boolean firstTime = true;
    try {
      do {
        if (nanos <= 0L) {
          return false;
        }
        if (firstTime) {
          if (signalBeforeWaiting) {
            signalNextWaiter();
          }
          beginWaitingFor(guard);
          firstTime = false;
        }
        nanos = guard.condition.awaitNanos(nanos);
      } while (!guard.isSatisfied());
      return true;
    } finally {
      if (!firstTime) {
        endWaitingFor(guard);
      }
    }
  }

@ GuardedBy ( "lock" ) private boolean awaitNanos ( Guard guard , long nanos , boolean signalBeforeWaiting ) throws InterruptedException { boolean firstTime = true ; try { do { if ( nanos <= 0L ) { return false ; } if ( firstTime ) { if ( signalBeforeWaiting ) { signalNextWaiter ( ) ; } beginWaitingFor ( guard ) ; firstTime = false ; } nanos = guard . condition . awaitNanos ( nanos ) ; } while ( ! guard . isSatisfied ( ) ) ; return true ; } finally { if ( ! firstTime ) { endWaitingFor ( guard ) ; } } }

Caller should check before calling that guard is not satisfied.

Caller should check before calling that guard is not satisfied .


@Beta
  @CanIgnoreReturnValue
  @GwtIncompatible // concurrency
  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
  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();
  }

Shuts down the given executor service gradually, first disabling new submissions and later, if
necessary, cancelling remaining tasks.

The method takes the following steps:

calls {@link ExecutorService#shutdown()}, disabling acceptance of new submitted tasks.

awaits executor service termination for half of the specified timeout.

if the timeout expires, it calls {@link ExecutorService#shutdownNow()}, cancelling
pending tasks and interrupting running tasks.

awaits executor service termination for the other half of the specified timeout.

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

Shuts down the given executor service gradually first disabling new submissions and later if necessary cancelling remaining tasks .


public void write(CharSequence charSequence) throws IOException {
    checkNotNull(charSequence);

    Closer closer = Closer.create();
    try {
      Writer out = closer.register(openStream());
      out.append(charSequence);
      out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

Writes the given character sequence to this sink.

@throws IOException if an I/O error while writing to this sink

Writes the given character sequence to this sink .


public void execute() {
    // Lock while we update our state so the add method above will finish adding any listeners
    // before we start to run them.
    RunnableExecutorPair list;
    synchronized (this) {
      if (executed) {
        return;
      }
      executed = true;
      list = runnables;
      runnables = null; // allow GC to free listeners even if this stays around for a while.
    }
    // If we succeeded then list holds all the runnables we to execute. The pairs in the stack are
    // in the opposite order from how they were added so we need to reverse the list to fulfill our
    // contract.
    // This is somewhat annoying, but turns out to be very fast in practice. Alternatively, we could
    // drop the contract on the method that enforces this queue like behavior since depending on it
    // is likely to be a bug anyway.

    // N.B. All writes to the list and the next pointers must have happened before the above
    // synchronized block, so we can iterate the list without the lock held here.
    RunnableExecutorPair reversedList = null;
    while (list != null) {
      RunnableExecutorPair tmp = list;
      list = list.next;
      tmp.next = reversedList;
      reversedList = tmp;
    }
    while (reversedList != null) {
      executeListener(reversedList.runnable, reversedList.executor);
      reversedList = reversedList.next;
    }
  }

Runs this execution list, executing all existing pairs in the order they were added. However,
note that listeners added after this point may be executed before those previously added, and
note that the execution order of all listeners is ultimately chosen by the implementations of
the supplied executors.

<p>This method is idempotent. Calling it several times in parallel is semantically equivalent
to calling it exactly once.

@since 10.0 (present in 1.0 as {@code run})

Runs this execution list executing all existing pairs in the order they were added . However note that listeners added after this point may be executed before those previously added and note that the execution order of all listeners is ultimately chosen by the implementations of the supplied executors .


static long load64Safely(byte[] input, int offset, int length) {
    long result = 0;
    // Due to the way we shift, we can stop iterating once we've run out of data, the rest
    // of the result already being filled with zeros.

    // This loop is critical to performance, so please check HashBenchmark if altering it.
    int limit = Math.min(length, 8);
    for (int i = 0; i < limit; i++) {
      // Shift value left while iterating logically through the array.
      result |= (input[offset + i] & 0xFFL) << (i * 8);
    }
    return result;
  }

Similar to load64, but allows offset + 8 > input.length, padding the result with zeroes. This
has to explicitly reverse the order of the bytes as it packs them into the result which makes
it slower than the native version.

@param input the input bytes
@param offset the offset into the array at which to start reading
@param length the number of bytes from the input to read
@return a long of a concatenated 8 bytes

Similar to load64 but allows offset + 8 > input . length padding the result with zeroes . This has to explicitly reverse the order of the bytes as it packs them into the result which makes it slower than the native version .


static void store64(byte[] sink, int offset, long value) {
    // We don't want to assert in production code.
    assert offset >= 0 && offset + 8 <= sink.length;
    // Delegates to the fast (unsafe)version or the fallback.
    byteArray.putLongLittleEndian(sink, offset, value);
  }

Store 8 bytes into the provided array at the indicated offset, using the value provided.

@param sink the output byte array
@param offset the offset into the array at which to start writing
@param value the value to write

Store 8 bytes into the provided array at the indicated offset using the value provided .


static int load32(byte[] source, int offset) {
    // TODO(user): Measure the benefit of delegating this to LittleEndianBytes also.
    return (source[offset] & 0xFF)
        | ((source[offset + 1] & 0xFF) << 8)
        | ((source[offset + 2] & 0xFF) << 16)
        | ((source[offset + 3] & 0xFF) << 24);
  }

Load 4 bytes from the provided array at the indicated offset.

@param source the input bytes
@param offset the offset into the array at which to start
@return the value found in the array in the form of a long

Load 4 bytes from the provided array at the indicated offset .


public static MediaType create(String type, String subtype) {
    MediaType mediaType = create(type, subtype, ImmutableListMultimap.<String, String>of());
    mediaType.parsedCharset = Optional.absent();
    return mediaType;
  }

public static MediaType create ( String type , String subtype ) { MediaType mediaType = create ( type , subtype , ImmutableListMultimap . < String , String > of ( ) ) ; mediaType . parsedCharset = Optional . absent ( ) ; return mediaType ; }

Creates a new media type with the given type and subtype.

@throws IllegalArgumentException if type or subtype is invalid or if a wildcard is used for the
type, but not the subtype.

Creates a new media type with the given type and subtype .


public static MediaType parse(String input) {
    checkNotNull(input);
    Tokenizer tokenizer = new Tokenizer(input);
    try {
      String type = tokenizer.consumeToken(TOKEN_MATCHER);
      tokenizer.consumeCharacter('/');
      String subtype = tokenizer.consumeToken(TOKEN_MATCHER);
      ImmutableListMultimap.Builder<String, String> parameters = ImmutableListMultimap.builder();
      while (tokenizer.hasMore()) {
        tokenizer.consumeTokenIfPresent(LINEAR_WHITE_SPACE);
        tokenizer.consumeCharacter(';');
        tokenizer.consumeTokenIfPresent(LINEAR_WHITE_SPACE);
        String attribute = tokenizer.consumeToken(TOKEN_MATCHER);
        tokenizer.consumeCharacter('=');
        final String value;
        if ('"' == tokenizer.previewChar()) {
          tokenizer.consumeCharacter('"');
          StringBuilder valueBuilder = new StringBuilder();
          while ('"' != tokenizer.previewChar()) {
            if ('\\' == tokenizer.previewChar()) {
              tokenizer.consumeCharacter('\\');
              valueBuilder.append(tokenizer.consumeCharacter(ascii()));
            } else {
              valueBuilder.append(tokenizer.consumeToken(QUOTED_TEXT_MATCHER));
            }
          }
          value = valueBuilder.toString();
          tokenizer.consumeCharacter('"');
        } else {
          value = tokenizer.consumeToken(TOKEN_MATCHER);
        }
        parameters.put(attribute, value);
      }
      return create(type, subtype, parameters.build());
    } catch (IllegalStateException e) {
      throw new IllegalArgumentException("Could not parse '" + input + "'", e);
    }
  }

public
static
MediaType
parse
(
String
input
)
{
checkNotNull
(
input
)
;
Tokenizer
tokenizer
=
new
Tokenizer
(
input
)
;
try
{
String
type
=
tokenizer
.
consumeToken
(
TOKEN_MATCHER
)
;
tokenizer
.
consumeCharacter
(
'
'
)
;
String
subtype
=
tokenizer
.
consumeToken
(
TOKEN_MATCHER
)
;
ImmutableListMultimap
.
Builder
<
String
,
String
>
parameters
=
ImmutableListMultimap
.
builder
(
)
;
while
(
tokenizer
.
hasMore
(
)
)
{
tokenizer
.
consumeTokenIfPresent
(
LINEAR_WHITE_SPACE
)
;
tokenizer
.
consumeCharacter
(
'
'
)
;
tokenizer
.
consumeTokenIfPresent
(
LINEAR_WHITE_SPACE
)
;
String
attribute
=
tokenizer
.
consumeToken
(
TOKEN_MATCHER
)
;
tokenizer
.
consumeCharacter
(
'
'
)
;
final
String
value
;
if
(
'
'
==
tokenizer
.
previewChar
(
)
)
{
tokenizer
.
consumeCharacter
(
'
'
)
;
StringBuilder
valueBuilder
=
new
StringBuilder
(
)
;
while
(
'
'
!=
tokenizer
.
previewChar
(
)
)
{
if
(
'
'
==
tokenizer
.
previewChar
(
)
)
{
tokenizer
.
consumeCharacter
(
'
'
)
;
valueBuilder
.
append
(
tokenizer
.
consumeCharacter
(
ascii
(
)
)
)
;
}
else
{
valueBuilder
.
append
(
tokenizer
.
consumeToken
(
QUOTED_TEXT_MATCHER
)
)
;
}
}
value
=
valueBuilder
.
toString
(
)
;
tokenizer
.
consumeCharacter
(
'
'
)
;
}
else
{
value
=
tokenizer
.
consumeToken
(
TOKEN_MATCHER
)
;
}
parameters
.
put
(
attribute
,
value
)
;
}
return
create
(
type
,
subtype
,
parameters
.
build
(
)
)
;
}
catch
(
IllegalStateException
e
)
{
throw
new
IllegalArgumentException
(
"Could not parse '"
+
input
+
"'"
,
e
)
;
}
}

Parses a media type from its string representation.

@throws IllegalArgumentException if the input is not parsable

Parses a media type from its string representation .


final Type capture() {
    Type superclass = getClass().getGenericSuperclass();
    checkArgument(superclass instanceof ParameterizedType, "%s isn't parameterized", superclass);
    return ((ParameterizedType) superclass).getActualTypeArguments()[0];
  }

final
Type
capture
(
)
{
Type
superclass
=
getClass
(
)
.
getGenericSuperclass
(
)
;
checkArgument
(
superclass
instanceof
ParameterizedType
,
"%s isn't parameterized"
,
superclass
)
;
return
(
(
ParameterizedType
)
superclass
)
.
getActualTypeArguments
(
)
[
0
]
;
}


static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) {
    boolean changed = false;
    while (iterator.hasNext()) {
      changed |= set.remove(iterator.next());
    }
    return changed;
  }

static boolean removeAllImpl ( Set < ? > set , Iterator < ? > iterator ) { boolean changed = false ; while ( iterator . hasNext ( ) ) { changed |= set . remove ( iterator . next ( ) ) ; } return changed ; }

Remove each element in an iterable from a set.

Remove each element in an iterable from a set .


@Override
  public String escape(String string) {
    checkNotNull(string); // GWT specific check (do not optimize)
    // Inlineable fast-path loop which hands off to escapeSlow() only if needed
    int length = string.length();
    for (int index = 0; index < length; index++) {
      if (escape(string.charAt(index)) != null) {
        return escapeSlow(string, index);
      }
    }
    return string;
  }

Returns the escaped form of a given literal string.

@param string the literal string to be escaped
@return the escaped form of {@code string}
@throws NullPointerException if {@code string} is null

Returns the escaped form of a given literal string .


private static char[] growBuffer(char[] dest, int index, int size) {
    if (size < 0) { // overflow - should be OutOfMemoryError but GWT/j2cl don't support it
      throw new AssertionError("Cannot increase internal buffer any further");
    }
    char[] copy = new char[size];
    if (index > 0) {
      System.arraycopy(dest, 0, copy, 0, index);
    }
    return copy;
  }

Helper method to grow the character buffer as needed, this only happens once in a while so it's
ok if it's in a method call. If the index passed in is 0 then no copying will be done.

Helper method to grow the character buffer as needed this only happens once in a while so it s ok if it s in a method call . If the index passed in is 0 then no copying will be done .


public CacheBuilder<K, V> concurrencyLevel(int concurrencyLevel) {
    checkState(
        this.concurrencyLevel == UNSET_INT,
        "concurrency level was already set to %s",
        this.concurrencyLevel);
    checkArgument(concurrencyLevel > 0);
    this.concurrencyLevel = concurrencyLevel;
    return this;
  }

Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The
table is internally partitioned to try to permit the indicated number of concurrent updates
without contention. Because assignment of entries to these partitions is not necessarily
uniform, the actual concurrency observed may vary. Ideally, you should choose a value to
accommodate as many threads as will ever concurrently modify the table. Using a significantly
higher value than you need can waste space and time, and a significantly lower value can lead
to thread contention. But overestimates and underestimates within an order of magnitude do not
usually have much noticeable impact. A value of one permits only one thread to modify the cache
at a time, but since read operations and cache loading computations can proceed concurrently,
this still yields higher concurrency than full synchronization.

Defaults to 4. Note:The default may change in the future. If you care about this
value, you should always choose it explicitly.

The current implementation uses the concurrency level to create a fixed number of hashtable
segments, each governed by its own write lock. The segment lock is taken once for each explicit
write, and twice for each cache loading computation (once prior to loading the new value, and
once after loading completes). Much internal cache management is performed at the segment
granularity. For example, access queues and write queues are kept per segment when they are
required by the selected eviction algorithm. As such, when writing unit tests it is not
uncommon to specify {@code concurrencyLevel(1)} in order to achieve more deterministic eviction
behavior.

Note that future implementations may abandon segment locking in favor of more advanced
concurrency controls.

@return this {@code CacheBuilder} instance (for chaining)
@throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
@throws IllegalStateException if a concurrency level was already set

Guides the allowed concurrency among update operations . Used as a hint for internal sizing . The table is internally partitioned to try to permit the indicated number of concurrent updates without contention . Because assignment of entries to these partitions is not necessarily uniform the actual concurrency observed may vary . Ideally you should choose a value to accommodate as many threads as will ever concurrently modify the table . Using a significantly higher value than you need can waste space and time and a significantly lower value can lead to thread contention . But overestimates and underestimates within an order of magnitude do not usually have much noticeable impact . A value of one permits only one thread to modify the cache at a time but since read operations and cache loading computations can proceed concurrently this still yields higher concurrency than full synchronization .


public <K1 extends K, V1 extends V> Cache<K1, V1> build() {
    checkWeightWithWeigher();
    checkNonLoadingCache();
    return new LocalCache.LocalManualCache<>(this);
  }

public < K1 extends K , V1 extends V > Cache < K1 , V1 > build ( ) { checkWeightWithWeigher ( ) ; checkNonLoadingCache ( ) ; return new LocalCache . LocalManualCache <> ( this ) ; }

Builds a cache which does not automatically load values when keys are requested.

Consider {@link #build(CacheLoader)} instead, if it is feasible to implement a {@code
CacheLoader}.

This method does not alter the state of this {@code CacheBuilder} instance, so it can be
invoked again to create multiple independent caches.

@return a cache having the requested features
@since 11.0

Builds a cache which does not automatically load values when keys are requested .


void allocArrays() {
    Preconditions.checkState(needsAllocArrays(), "Arrays already allocated");

    int expectedSize = modCount;
    int buckets = Hashing.closedTableSize(expectedSize, LOAD_FACTOR);
    this.table = newTable(buckets);

    this.entries = newEntries(expectedSize);
    this.keys = new Object[expectedSize];
    this.values = new Object[expectedSize];
  }

void
allocArrays
(
)
{
Preconditions
.
checkState
(
needsAllocArrays
(
)
,
"Arrays already allocated"
)
;
int
expectedSize
=
modCount
;
int
buckets
=
Hashing
.
closedTableSize
(
expectedSize
,
LOAD_FACTOR
)
;
this
.
table
=
newTable
(
buckets
)
;
this
.
entries
=
newEntries
(
expectedSize
)
;
this
.
keys
=
new
Object
[
expectedSize
]
;
this
.
values
=
new
Object
[
expectedSize
]
;
}


public void add(double value) {
    if (count == 0) {
      count = 1;
      mean = value;
      min = value;
      max = value;
      if (!isFinite(value)) {
        sumOfSquaresOfDeltas = NaN;
      }
    } else {
      count++;
      if (isFinite(value) && isFinite(mean)) {
        // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15) and (16)
        double delta = value - mean;
        mean += delta / count;
        sumOfSquaresOfDeltas += delta * (value - mean);
      } else {
        mean = calculateNewMeanNonFinite(mean, value);
        sumOfSquaresOfDeltas = NaN;
      }
      min = Math.min(min, value);
      max = Math.max(max, value);
    }
  }


static double calculateNewMeanNonFinite(double previousMean, double value) {
    /*
     * Desired behaviour is to match the results of applying the naive mean formula. In particular,
     * the update formula can subtract infinities in cases where the naive formula would add them.
     *
     * Consequently:
     * 1. If the previous mean is finite and the new value is non-finite then the new mean is that
     *    value (whether it is NaN or infinity).
     * 2. If the new value is finite and the previous mean is non-finite then the mean is unchanged
     *    (whether it is NaN or infinity).
     * 3. If both the previous mean and the new value are non-finite and...
     * 3a. ...either or both is NaN (so mean != value) then the new mean is NaN.
     * 3b. ...they are both the same infinities (so mean == value) then the mean is unchanged.
     * 3c. ...they are different infinities (so mean != value) then the new mean is NaN.
     */
    if (isFinite(previousMean)) {
      // This is case 1.
      return value;
    } else if (isFinite(value) || previousMean == value) {
      // This is case 2. or 3b.
      return previousMean;
    } else {
      // This is case 3a. or 3c.
      return NaN;
    }
  }

Calculates the new value for the accumulated mean when a value is added, in the case where at
least one of the previous mean and the value is non-finite.

Calculates the new value for the accumulated mean when a value is added in the case where at least one of the previous mean and the value is non - finite .


static Object[] rebuildHashTable(int newTableSize, Object[] elements, int n) {
    Object[] hashTable = new Object[newTableSize];
    int mask = hashTable.length - 1;
    for (int i = 0; i < n; i++) {
      Object e = elements[i];
      int j0 = Hashing.smear(e.hashCode());
      for (int j = j0; ; j++) {
        int index = j & mask;
        if (hashTable[index] == null) {
          hashTable[index] = e;
          break;
        }
      }
    }
    return hashTable;
  }

static Object [ ] rebuildHashTable ( int newTableSize , Object [ ] elements , int n ) { Object [ ] hashTable = new Object [ newTableSize ] ; int mask = hashTable . length - 1 ; for ( int i = 0 ; i < n ; i ++ ) { Object e = elements [ i ] ; int j0 = Hashing . smear ( e . hashCode ( ) ) ; for ( int j = j0 ; ; j ++ ) { int index = j & mask ; if ( hashTable [ index ] == null ) { hashTable [ index ] = e ; break ; } } } return hashTable ; }

Builds a new open-addressed hash table from the first n objects in elements.

Builds a new open - addressed hash table from the first n objects in elements .


@VisibleForTesting
  static int chooseTableSize(int setSize) {
    setSize = Math.max(setSize, 2);
    // Correct the size for open addressing to match desired load factor.
    if (setSize < CUTOFF) {
      // Round up to the next highest power of 2.
      int tableSize = Integer.highestOneBit(setSize - 1) << 1;
      while (tableSize * DESIRED_LOAD_FACTOR < setSize) {
        tableSize <<= 1;
      }
      return tableSize;
    }

    // The table can't be completely full or we'll get infinite reprobes
    checkArgument(setSize < MAX_TABLE_SIZE, "collection too large");
    return MAX_TABLE_SIZE;
  }

Returns an array size suitable for the backing array of a hash table that uses open addressing
with linear probing in its implementation. The returned size is the smallest power of two that
can hold setSize elements with the desired load factor. Always returns at least setSize + 2.

Returns an array size suitable for the backing array of a hash table that uses open addressing with linear probing in its implementation . The returned size is the smallest power of two that can hold setSize elements with the desired load factor . Always returns at least setSize + 2 .


@SuppressWarnings("unchecked")
  public static <R, C, V> ImmutableTable<R, C, V> of() {
    return (ImmutableTable<R, C, V>) SparseImmutableTable.EMPTY;
  }

@ SuppressWarnings ( "unchecked" ) public static < R , C , V > ImmutableTable < R , C , V > of ( ) { return ( ImmutableTable < R , C , V > ) SparseImmutableTable . EMPTY ; }


public static <R, C, V> ImmutableTable<R, C, V> of(R rowKey, C columnKey, V value) {
    return new SingletonImmutableTable<>(rowKey, columnKey, value);
  }

public static < R , C , V > ImmutableTable < R , C , V > of ( R rowKey , C columnKey , V value ) { return new SingletonImmutableTable <> ( rowKey , columnKey , value ) ; }

Returns an immutable table containing a single cell.

Returns an immutable table containing a single cell .


public static <R, C, V> ImmutableTable<R, C, V> copyOf(
      Table<? extends R, ? extends C, ? extends V> table) {
    if (table instanceof ImmutableTable) {
      @SuppressWarnings("unchecked")
      ImmutableTable<R, C, V> parameterizedTable = (ImmutableTable<R, C, V>) table;
      return parameterizedTable;
    } else {
      return copyOf(table.cellSet());
    }
  }

public static < R , C , V > ImmutableTable < R , C , V > copyOf ( Table < ? extends R , ? extends C , ? extends V > table ) { if ( table instanceof ImmutableTable ) { @ SuppressWarnings ( "unchecked" ) ImmutableTable < R , C , V > parameterizedTable = ( ImmutableTable < R , C , V > ) table ; return parameterizedTable ; } else { return copyOf ( table . cellSet ( ) ) ; } }

Returns an immutable copy of the provided table.

The {@link Table#cellSet()} iteration order of the provided table determines the iteration
ordering of all views in the returned table. Note that some views of the original table and the
copied table may have different iteration orders. For more control over the ordering, create a
{@link Builder} and call {@link Builder#orderRowsBy}, {@link Builder#orderColumnsBy}, and
{@link Builder#putAll}

Despite the method name, this method attempts to avoid actually copying the data when it is
safe to do so. The exact circumstances under which a copy will or will not be performed are
undocumented and subject to change.

Returns an immutable copy of the provided table .


@SuppressWarnings("unchecked") // implementation is "fully variant"
  public static <T> Converter<T, T> identity() {
    return (IdentityConverter<T>) IdentityConverter.INSTANCE;
  }

@
SuppressWarnings
(
"unchecked"
)
// implementation is "fully variant"
public
static
<
T
>
Converter
<
T
,
T
>
identity
(
)
{
return
(
IdentityConverter
<
T
>
)
IdentityConverter
.
INSTANCE
;
}

Returns a serializable converter that always converts or reverses an object to itself.

Returns a serializable converter that always converts or reverses an object to itself .


static <R, C, V> RegularImmutableTable<R, C, V> forOrderedComponents(
      ImmutableList<Cell<R, C, V>> cellList,
      ImmutableSet<R> rowSpace,
      ImmutableSet<C> columnSpace) {
    // use a dense table if more than half of the cells have values
    // TODO(gak): tune this condition based on empirical evidence
    return (cellList.size() > (((long) rowSpace.size() * columnSpace.size()) / 2))
        ? new DenseImmutableTable<R, C, V>(cellList, rowSpace, columnSpace)
        : new SparseImmutableTable<R, C, V>(cellList, rowSpace, columnSpace);
  }

A factory that chooses the most space-efficient representation of the table.

A factory that chooses the most space - efficient representation of the table .