signature:
public class Splitter { /** * Returns a splitter that divides strings into pieces of the given length . For example , { @ code
 * Splitter . fixedLength ( 2 ) . split ( " abcde " ) } returns an iterable containing { @ code [ " ab " , " cd " ,
 * " e " ] } . The last piece can be smaller than { @ code length } but will never be empty .
 * < p > < b > Note : < / b > if { @ link # fixedLength } is used in conjunction with { @ link # limit } , the final
 * split piece < i > may be longer than the specified fixed length < / i > . This is because the splitter
 * will < i > stop splitting when the limit is reached < / i > , and just return the final piece as - is .
 * < p > < b > Exception : < / b > for consistency with separator - based splitters , { @ code split ( " " ) } does not
 * yield an empty iterable , but an iterable containing { @ code " " } . This is the only case in which
 * { @ code Iterables . size ( split ( input ) ) } does not equal { @ code IntMath . divide ( input . length ( ) ,
 * length , CEILING ) } . To avoid this behavior , use { @ code omitEmptyStrings } .
 * @ param length the desired length of pieces after splitting , a positive integer
 * @ return a splitter , with default settings , that can split into fixed sized pieces
 * @ throws IllegalArgumentException if { @ code length } is zero or negative */
public static Splitter fixedLength ( final int length ) { } }

implementation: checkArgument ( length > 0 , "The length may not be less than 1" ) ; return new Splitter ( new Strategy ( ) { @ Override public SplittingIterator iterator ( final Splitter splitter , CharSequence toSplit ) { return new SplittingIterator ( splitter , toSplit ) { @ Override public int separatorStart ( int start ) { int nextChunkStart = start + length ; return ( nextChunkStart < toSplit . length ( ) ? nextChunkStart : - 1 ) ; } @ Override public int separatorEnd ( int separatorPosition ) { return separatorPosition ; } } ; } } ) ;


signature:
public class Splitter { /** * TODO ( kevinb ) : throw if a trimmer was already specified ! */
public Splitter trimResults ( CharMatcher trimmer ) { } }

implementation: checkNotNull ( trimmer ) ; return new Splitter ( strategy , omitEmptyStrings , trimmer , limit ) ;


signature:
public class Splitter { /** * Splits { @ code sequence } into string components and makes them available through an { @ link
 * Iterator } , which may be lazily evaluated . If you want an eagerly computed { @ link List } , use
 * { @ link # splitToList ( CharSequence ) } .
 * @ param sequence the sequence of characters to split
 * @ return an iteration over the segments split from the parameter */
public Iterable < String > split ( final CharSequence sequence ) { } }

implementation: checkNotNull ( sequence ) ; return new Iterable < String > ( ) { @ Override public Iterator < String > iterator ( ) { return splittingIterator ( sequence ) ; } @ Override public String toString ( ) { return Joiner . on ( ", " ) . appendTo ( new StringBuilder ( ) . append ( '[' ) , this ) . append ( ']' ) . toString ( ) ; } } ;


signature:
public class Splitter { /** * Splits { @ code sequence } into string components and returns them as an immutable list . If you
 * want an { @ link Iterable } which may be lazily evaluated , use { @ link # split ( CharSequence ) } .
 * @ param sequence the sequence of characters to split
 * @ return an immutable list of the segments split from the parameter
 * @ since 15.0 */
public List < String > splitToList ( CharSequence sequence ) { } }

implementation: checkNotNull ( sequence ) ; Iterator < String > iterator = splittingIterator ( sequence ) ; List < String > result = new ArrayList < > ( ) ; while ( iterator . hasNext ( ) ) { result . add ( iterator . next ( ) ) ; } return Collections . unmodifiableList ( result ) ;


signature:
public class ForwardingMultiset { /** * A sensible , albeit inefficient , definition of { @ link # count } in terms of { @ link # entrySet } . If
 * you override { @ link # entrySet } , you may wish to override { @ link # count } to forward to this
 * implementation .
 * @ since 7.0 */
@ Beta protected int standardCount ( @ Nullable Object object ) { } }

implementation: for ( Entry < ? > entry : this . entrySet ( ) ) { if ( Objects . equal ( entry . getElement ( ) , object ) ) { return entry . getCount ( ) ; } } return 0 ;


signature:
public class ForwardingMultiset { /** * A sensible definition of { @ link # setCount ( Object , int , int ) } in terms of { @ link # count ( Object ) }
 * and { @ link # setCount ( Object , int ) } . If you override either of these methods , you may wish to
 * override { @ link # setCount ( Object , int , int ) } to forward to this implementation .
 * @ since 7.0 */
protected boolean standardSetCount ( E element , int oldCount , int newCount ) { } }

implementation: return Multisets . setCountImpl ( this , element , oldCount , newCount ) ;


signature:
public class AbstractIdleService { /** * Returns the { @ link Executor } that will be used to run this service . Subclasses may override
 * this method to use a custom { @ link Executor } , which may configure its worker thread with a
 * specific name , thread group or priority . The returned executor ' s { @ link
 * Executor # execute ( Runnable ) execute ( ) } method is called when this service is started and
 * stopped , and should return promptly . */
protected Executor executor ( ) { } }

implementation: return new Executor ( ) { @ Override public void execute ( Runnable command ) { MoreExecutors . newThread ( threadNameSupplier . get ( ) , command ) . start ( ) ; } } ;


signature:
public class Files { /** * Returns a buffered reader that reads from a file using the given character set .
 * < p > < b > { @ link java . nio . file . Path } equivalent : < / b > { @ 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 */
@ Beta public static BufferedReader newReader ( File file , Charset charset ) throws FileNotFoundException { } }

implementation: checkNotNull ( file ) ; checkNotNull ( charset ) ; return new BufferedReader ( new InputStreamReader ( new FileInputStream ( file ) , charset ) ) ;


signature:
public class Files { /** * Returns a new { @ link CharSource } for reading character data from the given file using the given
 * character set .
 * @ since 14.0 */
public static CharSource asCharSource ( File file , Charset charset ) { } }

implementation: return asByteSource ( file ) . asCharSource ( charset ) ;


signature:
public class Files { /** * Returns a new { @ link CharSink } for writing character data to the given file using the given
 * character set . The given { @ code modes } control how the file is opened for writing . When no mode
 * is provided , the file will be truncated before writing . When the { @ link FileWriteMode # APPEND
 * APPEND } mode is provided , writes will append to the end of the file without truncating it .
 * @ since 14.0 */
public static CharSink asCharSink ( File file , Charset charset , FileWriteMode ... modes ) { } }

implementation: return asByteSink ( file , modes ) . asCharSink ( charset ) ;


signature:
public class Files { /** * Overwrites a file with the contents of a byte array .
 * < p > < b > { @ link java . nio . file . Path } equivalent : < / b > { @ 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 */
@ Beta public static void write ( byte [ ] from , File to ) throws IOException { } }

implementation: asByteSink ( to ) . write ( from ) ;


signature:
public class Files { /** * Copies all bytes from a file to an output stream .
 * < p > < b > { @ link java . nio . file . Path } equivalent : < / b > { @ 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 */
@ Beta public static void copy ( File from , OutputStream to ) throws IOException { } }

implementation: asByteSource ( from ) . copyTo ( to ) ;


signature:
public class Files { /** * Copies all the bytes from one file to another .
 * < p > 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 .
 * < p > < b > Warning : < / b > 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 < i > same < / i >
 * file , the contents of that file will be deleted .
 * < p > < b > { @ link java . nio . file . Path } equivalent : < / b > { @ 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 ) } */
@ Beta public static void copy ( File from , File to ) throws IOException { } }

implementation: checkArgument ( ! from . equals ( to ) , "Source %s and destination %s must be different" , from , to ) ; asByteSource ( from ) . copyTo ( asByteSink ( to ) ) ;


signature:
public class Files { /** * Appends a character sequence ( such as a string ) to a file using the given character set .
 * @ param from the character sequence to append
 * @ param to the destination file
 * @ param charset the charset used to encode the output stream ; see { @ link StandardCharsets } for
 * helpful predefined constants
 * @ throws IOException if an I / O error occurs
 * @ deprecated Prefer { @ code asCharSink ( to , charset , FileWriteMode . APPEND ) . write ( from ) } . This
 * method is scheduled to be removed in January 2019. */
@ Beta @ Deprecated public static void append ( CharSequence from , File to , Charset charset ) throws IOException { } }

implementation: asCharSink ( to , charset , FileWriteMode . APPEND ) . write ( from ) ;


signature:
public class Files { /** * 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 */
@ Beta @ SuppressWarnings ( "GoodTime" ) // reading system time without TimeSource
public static void touch ( File file ) throws IOException { } }

implementation: checkNotNull ( file ) ; if ( ! file . createNewFile ( ) && ! file . setLastModified ( System . currentTimeMillis ( ) ) ) { throw new IOException ( "Unable to update modification time of " + file ) ; }


signature:
public class Files { /** * Creates any necessary but nonexistent parent directories of the specified file . Note that if
 * this operation fails it may have succeeded in creating some ( but not all ) of the necessary
 * parent directories .
 * @ throws IOException if an I / O error occurs , or if any necessary but nonexistent parent
 * directories of the specified file could not be created .
 * @ since 4.0 */
@ Beta public static void createParentDirs ( File file ) throws IOException { } }

implementation:
checkNotNull ( file ) ; File parent = file . getCanonicalFile ( ) . getParentFile ( ) ; if ( parent == null ) { /* * The given directory is a filesystem root . All zero of its ancestors exist . This doesn ' t
 * mean that the root itself exists - - consider x : \ on a Windows machine without such a drive
 * - - or even that the caller can create it , but this method makes no such guarantees even for
 * non - root files . */
return ; } parent . mkdirs ( ) ; if ( ! parent . isDirectory ( ) ) { throw new IOException ( "Unable to create parent directories of " + file ) ; }


signature:
public class Files { /** * Moves a file from one path to another . This method can rename a file and / or move it to a
 * different directory . In either case { @ code to } must be the target path for the file itself ; not
 * just the new name for the file or the path to the new parent directory .
 * < p > < b > { @ link java . nio . file . Path } equivalent : < / b > { @ link java . nio . file . Files # move } .
 * @ 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 ) } */
@ Beta public static void move ( File from , File to ) throws IOException { } }

implementation: checkNotNull ( from ) ; checkNotNull ( to ) ; checkArgument ( ! from . equals ( to ) , "Source %s and destination %s must be different" , from , to ) ; if ( ! from . renameTo ( to ) ) { copy ( from , to ) ; if ( ! from . delete ( ) ) { if ( ! to . delete ( ) ) { throw new IOException ( "Unable to delete " + to ) ; } throw new IOException ( "Unable to delete " + from ) ; } }


signature:
public class Files { /** * 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. */
@ Beta @ Deprecated public static String readFirstLine ( File file , Charset charset ) throws IOException { } }

implementation: return asCharSource ( file , charset ) . readFirstLine ( ) ;


signature:
public class Files { /** * Computes the hash code of the { @ code file } using { @ code hashFunction } .
 * @ param file the file to read
 * @ param hashFunction the hash function to use to hash the data
 * @ return the { @ link HashCode } of all of the bytes in the file
 * @ throws IOException if an I / O error occurs
 * @ since 12.0
 * @ deprecated Prefer { @ code asByteSource ( file ) . hash ( hashFunction ) } . This method is scheduled to
 * be removed in January 2019. */
@ Beta @ Deprecated public static HashCode hash ( File file , HashFunction hashFunction ) throws IOException { } }

implementation: return asByteSource ( file ) . hash ( hashFunction ) ;


signature:
public class Files { /** * Fully maps a file read - only in to memory as per { @ link
 * FileChannel # map ( java . nio . channels . FileChannel . MapMode , long , long ) } .
 * < p > Files are mapped from offset 0 to its length .
 * < p > This only works for files ≤ { @ link Integer # MAX _ VALUE } bytes .
 * @ param file the file to map
 * @ return a read - only buffer reflecting { @ code file }
 * @ throws FileNotFoundException if the { @ code file } does not exist
 * @ throws IOException if an I / O error occurs
 * @ see FileChannel # map ( MapMode , long , long )
 * @ since 2.0 */
@ Beta public static MappedByteBuffer map ( File file ) throws IOException { } }

implementation: checkNotNull ( file ) ; return map ( file , MapMode . READ_ONLY ) ;


signature:
public class Files { /** * Fully maps a file in to memory as per { @ link
 * FileChannel # map ( java . nio . channels . FileChannel . MapMode , long , long ) } using the requested { @ link
 * MapMode } .
 * < p > Files are mapped from offset 0 to its length .
 * < p > This only works for files ≤ { @ link Integer # MAX _ VALUE } bytes .
 * @ param file the file to map
 * @ param mode the mode to use when mapping { @ code file }
 * @ return a buffer reflecting { @ code file }
 * @ throws FileNotFoundException if the { @ code file } does not exist
 * @ throws IOException if an I / O error occurs
 * @ see FileChannel # map ( MapMode , long , long )
 * @ since 2.0 */
@ Beta public static MappedByteBuffer map ( File file , MapMode mode ) throws IOException { } }

implementation: return mapInternal ( file , mode , - 1 ) ;


signature:
public class Files { /** * Maps a file in to memory as per { @ link FileChannel # map ( java . nio . channels . FileChannel . MapMode ,
 * long , long ) } using the requested { @ link MapMode } .
 * < p > Files are mapped from offset 0 to { @ code size } .
 * < p > If the mode is { @ link MapMode # READ _ WRITE } and the file does not exist , it will be created
 * with the requested { @ code size } . Thus this method is useful for creating memory mapped files
 * which do not yet exist .
 * < p > This only works for files ≤ { @ link Integer # MAX _ VALUE } bytes .
 * @ param file the file to map
 * @ param mode the mode to use when mapping { @ code file }
 * @ return a buffer reflecting { @ code file }
 * @ throws IOException if an I / O error occurs
 * @ see FileChannel # map ( MapMode , long , long )
 * @ since 2.0 */
@ Beta public static MappedByteBuffer map ( File file , MapMode mode , long size ) throws IOException { } }

implementation: checkArgument ( size >= 0 , "size (%s) may not be negative" , size ) ; return mapInternal ( file , mode , size ) ;


signature:
public class ImmutableBiMap { /** * Returns a { @ link Collector } that accumulates elements into an { @ code ImmutableBiMap } whose keys
 * and values are the result of applying the provided mapping functions to the input elements .
 * Entries appear in the result { @ code ImmutableBiMap } in encounter order .
 * < p > If the mapped keys or values contain duplicates ( according to { @ link Object # equals ( Object ) } ,
 * an { @ code IllegalArgumentException } is thrown when the collection operation is performed . ( This
 * differs from the { @ code Collector } returned by { @ link Collectors # toMap ( Function , Function ) } ,
 * which throws an { @ code IllegalStateException } . )
 * @ since 21.0 */
public static < T , K , V > Collector < T , ? , ImmutableBiMap < K , V > > toImmutableBiMap ( Function < ? super T , ? extends K > keyFunction , Function < ? super T , ? extends V > valueFunction ) { } }

implementation: return CollectCollectors . toImmutableBiMap ( keyFunction , valueFunction ) ;


signature:
public class ImmutableBiMap { /** * Casting to any type is safe because the set will never hold any elements . */
@ SuppressWarnings ( "unchecked" ) public static < K , V > ImmutableBiMap < K , V > of ( ) { } }

implementation: return ( ImmutableBiMap < K , V > ) RegularImmutableBiMap . EMPTY ;


signature:
public class ImmutableBiMap { /** * Returns an immutable map containing the given entries , in order .
 * @ throws IllegalArgumentException if duplicate keys or values are added */
public static < K , V > ImmutableBiMap < K , V > of ( K k1 , V v1 , K k2 , V v2 ) { } }

implementation: return RegularImmutableBiMap . fromEntries ( entryOf ( k1 , v1 ) , entryOf ( k2 , v2 ) ) ;


signature:
public class ImmutableBiMap { /** * Returns a new builder , expecting the specified number of entries to be added .
 * < p > 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 .
 * < p > 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 */
@ Beta public static < K , V > Builder < K , V > builderWithExpectedSize ( int expectedSize ) { } }

implementation: checkNonnegative ( expectedSize , "expectedSize" ) ; return new Builder < > ( expectedSize ) ;


signature:
public class ImmutableBiMap { /** * Guaranteed to throw an exception and leave the bimap unmodified .
 * @ throws UnsupportedOperationException always
 * @ deprecated Unsupported operation . */
@ CanIgnoreReturnValue @ Deprecated @ Override public V forcePut ( K key , V value ) { } }

implementation: throw new UnsupportedOperationException ( ) ;


signature:
public class MinMaxPriorityQueue { /** * Creates a new min - max priority queue with default settings : natural order , no maximum size , no
 * initial contents , and an initial expected size of 11. */
public static < E extends Comparable < E > > MinMaxPriorityQueue < E > create ( ) { } }

implementation: return new Builder < Comparable > ( Ordering . natural ( ) ) . create ( ) ;


signature:
public class MinMaxPriorityQueue { /** * Creates a new min - max priority queue using natural order , no maximum size , and initially
 * containing the given elements . */
public static < E extends Comparable < E > > MinMaxPriorityQueue < E > create ( Iterable < ? extends E > initialContents ) { } }

implementation: return new Builder < E > ( Ordering . < E > natural ( ) ) . create ( initialContents ) ;


signature:
public class MinMaxPriorityQueue { /** * Creates and returns a new builder , configured to build { @ code MinMaxPriorityQueue } instances
 * that use { @ code comparator } to determine the least and greatest elements . */
public static < B > Builder < B > orderedBy ( Comparator < B > comparator ) { } }

implementation: return new Builder < B > ( comparator ) ;


signature:
public class MinMaxPriorityQueue { /** * Creates and returns a new builder , configured to build { @ code MinMaxPriorityQueue } instances
 * sized appropriately to hold { @ code expectedSize } elements . */
public static Builder < Comparable > expectedSize ( int expectedSize ) { } }

implementation: return new Builder < Comparable > ( Ordering . natural ( ) ) . expectedSize ( expectedSize ) ;


signature:
public class MinMaxPriorityQueue { /** * Creates and returns a new builder , configured to build { @ code MinMaxPriorityQueue } instances
 * that are limited to { @ code maximumSize } elements . Each time a queue grows beyond this bound , it
 * immediately removes its greatest element ( according to its comparator ) , which might be the
 * element that was just added . */
public static Builder < Comparable > maximumSize ( int maximumSize ) { } }

implementation: return new Builder < Comparable > ( Ordering . natural ( ) ) . maximumSize ( maximumSize ) ;


signature:
public class MinMaxPriorityQueue { /** * Adds the given element to this queue . If this queue has a maximum size , after adding { @ code
 * element } the queue will automatically evict its greatest element ( according to its comparator ) ,
 * which may be { @ code element } itself . */
@ CanIgnoreReturnValue @ Override public boolean offer ( E element ) { } }

implementation:
checkNotNull ( element ) ; modCount ++ ; int insertIndex = size ++ ; growIfNeeded ( ) ; // Adds the element to the end of the heap and bubbles it up to the correct
// position .
heapForIndex ( insertIndex ) . bubbleUp ( insertIndex , element ) ; return size <= maximumSize || pollLast ( ) != element ;


signature:
public class MinMaxPriorityQueue { /** * Removes and returns the value at { @ code index } . */
private E removeAndGet ( int index ) { } }

implementation: E value = elementData ( index ) ; removeAt ( index ) ; return value ;


signature:
public class MinMaxPriorityQueue { /** * Returns { @ code true } if the MinMax heap structure holds . This is only used in testing .
 * < p > TODO ( kevinb ) : move to the test class ? */
@ VisibleForTesting boolean isIntact ( ) { } }

implementation: for ( int i = 1 ; i < size ; i ++ ) { if ( ! heapForIndex ( i ) . verifyIndex ( i ) ) { return false ; } } return true ;


signature:
public class MinMaxPriorityQueue { /** * Returns ~ 2x the old capacity if small ; ~ 1.5x otherwise . */
private int calculateNewCapacity ( ) { } }

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


signature:
public class ImmutableLongArray { /** * Returns an immutable array containing the given values , in order . */
public static ImmutableLongArray of ( long e0 , long e1 , long e2 , long e3 , long e4 ) { } }

implementation: return new ImmutableLongArray ( new long [ ] { e0 , e1 , e2 , e3 , e4 } ) ;


signature:
public class ImmutableLongArray { /** * Returns an immutable array containing the given values , in order . */
public static ImmutableLongArray copyOf ( long [ ] values ) { } }

implementation: return values . length == 0 ? EMPTY : new ImmutableLongArray ( Arrays . copyOf ( values , values . length ) ) ;


signature:
public class ImmutableLongArray { /** * Returns an immutable array containing the given values , in order . */
public static ImmutableLongArray copyOf ( Collection < Long > values ) { } }

implementation: return values . isEmpty ( ) ? EMPTY : new ImmutableLongArray ( Longs . toArray ( values ) ) ;


signature:
public class ImmutableLongArray { /** * Returns an immutable array containing the given values , in order .
 * < p > < b > Performance note : < / b > this method delegates to { @ link # copyOf ( Collection ) } if { @ code
 * values } is a { @ link Collection } . Otherwise it creates a { @ link # builder } and uses { @ link
 * Builder # addAll ( Iterable ) } , with all the performance implications associated with that . */
public static ImmutableLongArray copyOf ( Iterable < Long > values ) { } }

implementation: if ( values instanceof Collection ) { return copyOf ( ( Collection < Long > ) values ) ; } return builder ( ) . addAll ( values ) . build ( ) ;


signature:
public class Murmur3_32HashFunction { /** * Finalization mix - force all bits of a hash block to avalanche */
private static HashCode fmix ( int h1 , int length ) { } }


signature:
public class Platform { /** * Returns the platform preferred implementation of a map based on a hash table . */
static < K , V > Map < K , V > newHashMapWithExpectedSize ( int expectedSize ) { } }

implementation: return Maps . newHashMapWithExpectedSize ( expectedSize ) ;


signature:
public class Platform { /** * Returns the platform preferred implementation of an insertion ordered map based on a hash
 * table . */
static < K , V > Map < K , V > newLinkedHashMapWithExpectedSize ( int expectedSize ) { } }

implementation: return Maps . newLinkedHashMapWithExpectedSize ( expectedSize ) ;


signature:
public class Platform { /** * Returns a new array of the given length with the same type as a reference array .
 * @ param reference any array of the desired type
 * @ param length the length of the new array */
static < T > T [ ] newArray ( T [ ] reference , int length ) { } }

implementation:
Class < ? > type = reference . getClass ( ) . getComponentType ( ) ; // the cast is safe because
// result . getClass ( ) = = reference . getClass ( ) . getComponentType ( )
@ SuppressWarnings ( "unchecked" ) T [ ] result = ( T [ ] ) Array . newInstance ( type , length ) ; return result ;


signature:
public class Platform { /** * Equivalent to Arrays . copyOfRange ( source , from , to , arrayOfType . getClass ( ) ) . */
static < T > T [ ] copy ( Object [ ] source , int from , int to , T [ ] arrayOfType ) { } }

implementation: return Arrays . copyOfRange ( source , from , to , ( Class < ? extends T [ ] > ) arrayOfType . getClass ( ) ) ;


signature:
public class Interners { /** * Returns a function that delegates to the { @ link Interner # intern } method of the given interner .
 * @ since 8.0 */
public static < E > Function < E , E > asFunction ( Interner < E > interner ) { } }

implementation: return new InternerFunction < E > ( checkNotNull ( interner ) ) ;


signature:
public class TreeRangeSet { /** * Creates an empty { @ code TreeRangeSet } instance . */
public static < C extends Comparable < ? > > TreeRangeSet < C > create ( ) { } }

implementation: return new TreeRangeSet < C > ( new TreeMap < Cut < C > , Range < C > > ( ) ) ;


signature:
public class TreeRangeSet { /** * Returns a { @ code TreeRangeSet } initialized with the ranges in the specified range set . */
public static < C extends Comparable < ? > > TreeRangeSet < C > create ( RangeSet < C > rangeSet ) { } }

implementation: TreeRangeSet < C > result = create ( ) ; result . addAll ( rangeSet ) ; return result ;


signature:
public class TreeRangeSet { /** * Returns a { @ code TreeRangeSet } representing the union of the specified ranges .
 * < p > This is the smallest { @ code RangeSet } which encloses each of the specified ranges . An
 * element will be contained in this { @ code RangeSet } if and only if it is contained in at least
 * one { @ code Range } in { @ code ranges } .
 * @ since 21.0 */
public static < C extends Comparable < ? > > TreeRangeSet < C > create ( Iterable < Range < C > > ranges ) { } }

implementation: TreeRangeSet < C > result = create ( ) ; result . addAll ( ranges ) ; return result ;


signature:
public class ReverseNaturalOrdering { /** * Override the min / max methods to " hoist " delegation outside loops */
@ Override public < E extends Comparable > E min ( E a , E b ) { } }

implementation: return NaturalOrdering . INSTANCE . max ( a , b ) ;


signature:
public class ElementOrder { /** * Returns an instance which specifies that the natural ordering of the elements is guaranteed . */
public static < S extends Comparable < ? super S > > ElementOrder < S > natural ( ) { } }

implementation: return new ElementOrder < S > ( Type . SORTED , Ordering . < S > natural ( ) ) ;


signature:
public class ElementOrder { /** * Returns an instance which specifies that the ordering of the elements is guaranteed to be
 * determined by { @ code comparator } . */
public static < S > ElementOrder < S > sorted ( Comparator < S > comparator ) { } }

implementation: return new ElementOrder < S > ( Type . SORTED , comparator ) ;


signature:
public class ElementOrder { /** * Returns an empty mutable map whose keys will respect this { @ link ElementOrder } . */
< K extends T , V > Map < K , V > createMap ( int expectedSize ) { } }

implementation: switch ( type ) { case UNORDERED : return Maps . newHashMapWithExpectedSize ( expectedSize ) ; case INSERTION : return Maps . newLinkedHashMapWithExpectedSize ( expectedSize ) ; case SORTED : return Maps . newTreeMap ( comparator ( ) ) ; default : throw new AssertionError ( ) ; }


signature:
public class Ordering { /** * Returns a serializable ordering that uses the natural order of the values . The ordering throws
 * a { @ link NullPointerException } when passed a null parameter .
 * < p > The type specification is { @ code < C extends Comparable > } , instead of the technically correct
 * { @ code < C extends Comparable < ? super C > > } , to support legacy types from before Java 5.
 * < p > < b > Java 8 users : < / b > use { @ link Comparator # naturalOrder } instead . */
@ GwtCompatible ( serializable = true ) @ SuppressWarnings ( "unchecked" ) // TODO ( kevinb ) : right way to explain this ? ?
public static < C extends Comparable > Ordering < C > natural ( ) { } }

implementation: return ( Ordering < C > ) NaturalOrdering . INSTANCE ;


signature:
public class Ordering { /** * Returns an ordering based on an < i > existing < / i > comparator instance . Note that it is
 * unnecessary to create a < i > new < / i > anonymous inner class implementing { @ code Comparator } just
 * to pass it in here . Instead , simply subclass { @ code Ordering } and implement its { @ code compare }
 * method directly .
 * < p > < b > Java 8 users : < / b > this class is now obsolete as explained in the class documentation , so
 * there is no need to use this method .
 * @ param comparator the comparator that defines the order
 * @ return comparator itself if it is already an { @ code Ordering } ; otherwise an ordering that
 * wraps that comparator */
@ GwtCompatible ( serializable = true ) public static < T > Ordering < T > from ( Comparator < T > comparator ) { } }

implementation: return ( comparator instanceof Ordering ) ? ( Ordering < T > ) comparator : new ComparatorOrdering < T > ( comparator ) ;


signature:
public class Ordering { /** * Simply returns its argument .
 * @ deprecated no need to use this */
@ GwtCompatible ( serializable = true ) @ Deprecated public static < T > Ordering < T > from ( Ordering < T > ordering ) { } }

implementation: return checkNotNull ( ordering ) ;


signature:
public class Ordering { /** * TODO ( kevinb ) : provide replacement */
@ GwtCompatible ( serializable = true ) public static < T > Ordering < T > explicit ( List < T > valuesInOrder ) { } }

implementation: return new ExplicitOrdering < T > ( valuesInOrder ) ;


signature:
public class Ordering { /** * TODO ( kevinb ) : provide replacement */
@ GwtCompatible ( serializable = true ) public static < T > Ordering < T > explicit ( T leastValue , T ... remainingValuesInOrder ) { } }

implementation: return explicit ( Lists . asList ( leastValue , remainingValuesInOrder ) ) ;


signature:
public class Ordering { /** * Ordering < String > o = Ordering . < String > natural ( ) . reverse ( ) ; */
@ GwtCompatible ( serializable = true ) public < S extends T > Ordering < S > reverse ( ) { } }

implementation: return new ReverseOrdering < S > ( this ) ;


signature:
public class Ordering { /** * Ordering < String > o = Ordering . < String > natural ( ) . nullsFirst ( ) ; */
@ GwtCompatible ( serializable = true ) public < S extends T > Ordering < S > nullsFirst ( ) { } }

implementation: return new NullsFirstOrdering < S > ( this ) ;


signature:
public class Ordering { /** * Ordering < String > o = Ordering . < String > natural ( ) . nullsLast ( ) ; */
@ GwtCompatible ( serializable = true ) public < S extends T > Ordering < S > nullsLast ( ) { } }

implementation: return new NullsLastOrdering < S > ( this ) ;


signature:
public class Ordering { /** * Returns a new ordering on { @ code F } which orders elements by first applying a function to them ,
 * then comparing those results using { @ code this } . For example , to compare objects by their
 * string forms , in a case - insensitive manner , use :
 * < pre > { @ code
 * Ordering . from ( String . CASE _ INSENSITIVE _ ORDER )
 * . onResultOf ( Functions . toStringFunction ( ) )
 * } < / pre >
 * < p > < b > Java 8 users : < / b > Use { @ code Comparator . comparing ( function , thisComparator ) } instead ( you
 * can omit the comparator if it is the natural order ) . */
@ GwtCompatible ( serializable = true ) public < F > Ordering < F > onResultOf ( Function < F , ? extends T > function ) { } }

implementation: return new ByFunctionOrdering < > ( function , this ) ;


signature:
public class Ordering { /** * Returns an ordering which first uses the ordering { @ code this } , but which in the event of a
 * " tie " , then delegates to { @ code secondaryComparator } . For example , to sort a bug list first by
 * status and second by priority , you might use { @ code byStatus . compound ( byPriority ) } . For a
 * compound ordering with three or more components , simply chain multiple calls to this method .
 * < p > An ordering produced by this method , or a chain of calls to this method , is equivalent to
 * one created using { @ link Ordering # compound ( Iterable ) } on the same component comparators .
 * < p > < b > Java 8 users : < / b > Use { @ code thisComparator . thenComparing ( secondaryComparator ) } instead .
 * Depending on what { @ code secondaryComparator } is , one of the other overloads of { @ code
 * thenComparing } may be even more useful . */
@ GwtCompatible ( serializable = true ) public < U extends T > Ordering < U > compound ( Comparator < ? super U > secondaryComparator ) { } }

implementation: return new CompoundOrdering < U > ( this , checkNotNull ( secondaryComparator ) ) ;


signature:
public class Ordering { /** * Returns an ordering which tries each given comparator in order until a non - zero result is
 * found , returning that result , and returning zero only if all comparators return zero . The
 * returned ordering is based on the state of the { @ code comparators } iterable at the time it was
 * provided to this method .
 * < p > The returned ordering is equivalent to that produced using { @ code
 * Ordering . from ( comp1 ) . compound ( comp2 ) . compound ( comp3 ) . . . } .
 * < p > < b > Warning : < / b > Supplying an argument with undefined iteration order , such as a { @ link
 * HashSet } , will produce non - deterministic results .
 * < p > < b > Java 8 users : < / b > Use a chain of calls to { @ link Comparator # thenComparing ( Comparator ) } ,
 * or { @ code comparatorCollection . stream ( ) . reduce ( Comparator : : thenComparing ) . get ( ) } ( if the
 * collection might be empty , also provide a default comparator as the { @ code identity } parameter
 * to { @ code reduce } ) .
 * @ param comparators the comparators to try in order */
@ GwtCompatible ( serializable = true ) public static < T > Ordering < T > compound ( Iterable < ? extends Comparator < ? super T > > comparators ) { } }

implementation: return new CompoundOrdering < T > ( comparators ) ;


signature:
public class Ordering { /** * Returns a new ordering which sorts iterables by comparing corresponding elements pairwise until
 * a nonzero result is found ; imposes " dictionary order " . If the end of one iterable is reached ,
 * but not the other , the shorter iterable is considered to be less than the longer one . For
 * example , a lexicographical natural ordering over integers considers { @ code [ ] < [ 1 ] < [ 1 , 1 ] <
 * [ 1 , 2 ] < [ 2 ] } .
 * < p > Note that { @ code ordering . lexicographical ( ) . reverse ( ) } is not equivalent to { @ code
 * ordering . reverse ( ) . lexicographical ( ) } ( consider how each would order { @ code [ 1 ] } and { @ code [ 1,
 * < p > < b > Java 8 users : < / b > Use { @ link Comparators # lexicographical ( Comparator ) } instead .
 * @ since 2.0 */
@ GwtCompatible ( serializable = true ) // type parameter < S > lets us avoid the extra < String > in statements like :
// Ordering < Iterable < String > > o =
// Ordering . < String > natural ( ) . lexicographical ( ) ;
public < S extends T > Ordering < Iterable < S > > lexicographical ( ) { } }

implementation:
/* * Note that technically the returned ordering should be capable of
 * handling not just { @ code Iterable < S > } instances , but also any { @ code
 * Iterable < ? extends S > } . However , the need for this comes up so rarely
 * that it doesn ' t justify making everyone else deal with the very ugly
 * wildcard . */
return new LexicographicalOrdering < S > ( this ) ;


signature:
public class Ordering { /** * Returns the lesser of the two values according to this ordering . If the values compare as 0,
 * the first is returned .
 * < p > < b > Implementation note : < / b > this method is invoked by the default implementations of the
 * other { @ code min } overloads , so overriding it will affect their behavior .
 * < p > < b > Java 8 users : < / b > Use { @ code Collections . min ( Arrays . asList ( a , b ) , thisComparator ) }
 * instead ( but note that it does not guarantee which tied minimum element is returned ) .
 * @ param a value to compare , returned if less than or equal to b .
 * @ param b value to compare .
 * @ throws ClassCastException if the parameters are not < i > mutually comparable < / i > under this
 * ordering . */
public < E extends T > E min ( @ NullableDecl E a , @ NullableDecl E b ) { } }

implementation: return ( compare ( a , b ) <= 0 ) ? a : b ;


signature:
public class Ordering { /** * Returns the least of the specified values according to this ordering . If there are multiple
 * least values , the first of those is returned .
 * < p > < b > Java 8 users : < / b > Use { @ code Collections . min ( Arrays . asList ( a , b , c . . . ) , thisComparator ) }
 * instead ( but note that it does not guarantee which tied minimum element is returned ) .
 * @ param a value to compare , returned if less than or equal to the rest .
 * @ param b value to compare
 * @ param c value to compare
 * @ param rest values to compare
 * @ throws ClassCastException if the parameters are not < i > mutually comparable < / i > under this
 * ordering . */
public < E extends T > E min ( @ NullableDecl E a , @ NullableDecl E b , @ NullableDecl E c , E ... rest ) { } }

implementation: E minSoFar = min ( min ( a , b ) , c ) ; for ( E r : rest ) { minSoFar = min ( minSoFar , r ) ; } return minSoFar ;


signature:
public class Ordering { /** * Returns the greater of the two values according to this ordering . If the values compare as 0,
 * the first is returned .
 * < p > < b > Implementation note : < / b > this method is invoked by the default implementations of the
 * other { @ code max } overloads , so overriding it will affect their behavior .
 * < p > < b > Java 8 users : < / b > Use { @ code Collections . max ( Arrays . asList ( a , b ) , thisComparator ) }
 * instead ( but note that it does not guarantee which tied maximum element is returned ) .
 * @ param a value to compare , returned if greater than or equal to b .
 * @ param b value to compare .
 * @ throws ClassCastException if the parameters are not < i > mutually comparable < / i > under this
 * ordering . */
public < E extends T > E max ( @ NullableDecl E a , @ NullableDecl E b ) { } }

implementation: return ( compare ( a , b ) >= 0 ) ? a : b ;


signature:
public class Ordering { /** * TODO ( kevinb ) : rerun benchmarks including new options */
public < E extends T > List < E > sortedCopy ( Iterable < E > elements ) { } }

implementation:
@ SuppressWarnings ( "unchecked" ) // does not escape , and contains only E ' s
E [ ] array = ( E [ ] ) Iterables . toArray ( elements ) ; Arrays . sort ( array , this ) ; return Lists . newArrayList ( Arrays . asList ( array ) ) ;


signature:
public class Ordering { /** * TODO ( kevinb ) : rerun benchmarks including new options */
public < E extends T > ImmutableList < E > immutableSortedCopy ( Iterable < E > elements ) { } }

implementation: return ImmutableList . sortedCopyOf ( this , elements ) ;


signature:
public class Ordering { /** * Returns { @ code true } if each element in { @ code iterable } after the first is greater than or
 * equal to the element that preceded it , according to this ordering . Note that this is always
 * true when the iterable has fewer than two elements .
 * < p > < b > Java 8 users : < / b > Use the equivalent { @ link Comparators # isInOrder ( Iterable , Comparator ) }
 * instead , since the rest of { @ code Ordering } is mostly obsolete ( as explained in the class
 * documentation ) . */
public boolean isOrdered ( Iterable < ? extends T > iterable ) { } }

implementation: Iterator < ? extends T > it = iterable . iterator ( ) ; if ( it . hasNext ( ) ) { T prev = it . next ( ) ; while ( it . hasNext ( ) ) { T next = it . next ( ) ; if ( compare ( prev , next ) > 0 ) { return false ; } prev = next ; } } return true ;


signature:
public class Ordering { /** * { @ link Collections # binarySearch ( List , Object , Comparator ) Searches } { @ code sortedList } for
 * { @ code key } using the binary search algorithm . The list must be sorted using this ordering .
 * @ param sortedList the list to be searched
 * @ param key the key to be searched for
 * @ deprecated Use { @ link Collections # binarySearch ( List , Object , Comparator ) } directly . */
@ Deprecated public int binarySearch ( List < ? extends T > sortedList , @ NullableDecl T key ) { } }

implementation: return Collections . binarySearch ( sortedList , key , this ) ;


signature:
public class Monitor { /** * Enters this monitor . Blocks at most the given time .
 * @ return whether the monitor was entered */
@ SuppressWarnings ( "GoodTime" ) // should accept a java . time . Duration
public boolean enter ( long time , TimeUnit unit ) { } }

implementation: 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 ( ) ; } }


signature:
public class Monitor { /** * 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 */
@ SuppressWarnings ( "GoodTime" ) // should accept a java . time . Duration
public boolean enterInterruptibly ( long time , TimeUnit unit ) throws InterruptedException { } }

implementation: return lock . tryLock ( time , unit ) ;


signature:
public class Monitor { /** * Enters this monitor when the guard is satisfied . Blocks indefinitely , but may be interrupted .
 * @ throws InterruptedException if interrupted while waiting */
public void enterWhen ( Guard guard ) throws InterruptedException { } }

implementation: 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 ( ) ; } }


signature:
public class Monitor { /** * 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 */
@ SuppressWarnings ( "GoodTime" ) // should accept a java . time . Duration
public boolean enterWhen ( Guard guard , long time , TimeUnit unit ) throws InterruptedException { } }

implementation:
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 ( ) ; } } }


signature:
public class Monitor { /** * Enters this monitor when the guard is satisfied . Blocks indefinitely . */
public void enterWhenUninterruptibly ( Guard guard ) { } }

implementation: 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 ( ) ; } }


signature:
public class Monitor { /** * 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 */
public boolean enterIf ( Guard guard ) { } }

implementation: 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 ( ) ; } }


signature:
public class Monitor { /** * 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 */
@ SuppressWarnings ( "GoodTime" ) // should accept a java . time . Duration
public boolean enterIf ( Guard guard , long time , TimeUnit unit ) { } }

implementation: 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 ( ) ; } }


signature:
public class Monitor { /** * 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 */
public boolean enterIfInterruptibly ( Guard guard ) throws InterruptedException { } }

implementation: 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 ( ) ; } }


signature:
public class Monitor { /** * 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 .
 * < p > < b > Note : < / b > This method disregards the fairness setting of this monitor .
 * @ return whether the monitor was entered , which guarantees that the guard is now satisfied */
public boolean tryEnterIf ( Guard guard ) { } }

implementation: 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 ( ) ; } }


signature:
public class Monitor { /** * 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 */
public void waitFor ( Guard guard ) throws InterruptedException { } }

implementation: if ( ! ( ( guard . monitor == this ) & lock . isHeldByCurrentThread ( ) ) ) { throw new IllegalMonitorStateException ( ) ; } if ( ! guard . isSatisfied ( ) ) { await ( guard , true ) ; }


signature:
public class Monitor { /** * Waits for the guard to be satisfied . Waits indefinitely . May be called only by a thread
 * currently occupying this monitor . */
public void waitForUninterruptibly ( Guard guard ) { } }

implementation: if ( ! ( ( guard . monitor == this ) & lock . isHeldByCurrentThread ( ) ) ) { throw new IllegalMonitorStateException ( ) ; } if ( ! guard . isSatisfied ( ) ) { awaitUninterruptibly ( guard , true ) ; }


signature:
public class Monitor { /** * 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 */
@ SuppressWarnings ( "GoodTime" ) // should accept a java . time . Duration
public boolean waitForUninterruptibly ( Guard guard , long time , TimeUnit unit ) { } }

implementation: 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 ( ) ; } }


signature:
public class Monitor { /** * 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 . */
public int getWaitQueueLength ( Guard guard ) { } }

implementation: if ( guard . monitor != this ) { throw new IllegalMonitorStateException ( ) ; } lock . lock ( ) ; try { return guard . waiterCount ; } finally { lock . unlock ( ) ; }


signature:
public class Monitor { /** * Returns unit . toNanos ( time ) , additionally ensuring the returned value is not at risk of
 * overflowing or underflowing , by bounding the value between 0 and ( Long . MAX _ VALUE / 4 ) * 3.
 * Actually waiting for more than 219 years is not supported ! */
private static long toSafeNanos ( long time , TimeUnit unit ) { } }

implementation: long timeoutNanos = unit . toNanos ( time ) ; return ( timeoutNanos <= 0L ) ? 0L : ( timeoutNanos > ( Long . MAX_VALUE / 4 ) * 3 ) ? ( Long . MAX_VALUE / 4 ) * 3 : timeoutNanos ;


signature:
public class Monitor { /** * Signals some other thread waiting on a satisfied guard , if one exists .
 * < p > 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 .
 * < p > 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 .
 * < p > 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 .
 * < p > 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 . */
@ GuardedBy ( "lock" ) private void signalNextWaiter ( ) { } }

implementation: for ( Guard guard = activeGuards ; guard != null ; guard = guard . next ) { if ( isSatisfied ( guard ) ) { guard . condition . signal ( ) ; break ; } }


signature:
public class Monitor { /** * Exactly like guard . isSatisfied ( ) , but in addition signals all waiting threads in the ( hopefully
 * unlikely ) event that isSatisfied ( ) throws . */
@ GuardedBy ( "lock" ) private boolean isSatisfied ( Guard guard ) { } }

implementation: try { return guard . isSatisfied ( ) ; } catch ( Throwable throwable ) { signalAllWaiters ( ) ; throw throwable ; }


signature:
public class Monitor { /** * Signals all threads waiting on guards . */
@ GuardedBy ( "lock" ) private void signalAllWaiters ( ) { } }

implementation: for ( Guard guard = activeGuards ; guard != null ; guard = guard . next ) { guard . condition . signalAll ( ) ; }


signature:
public class Monitor { /** * Records that the current thread is about to wait on the specified guard . */
@ GuardedBy ( "lock" ) private void beginWaitingFor ( Guard guard ) { } }

implementation:
int waiters = guard . waiterCount ++ ; if ( waiters == 0 ) { // push guard onto activeGuards
guard . next = activeGuards ; activeGuards = guard ; }


signature:
public class Monitor { /** * Records that the current thread is no longer waiting on the specified guard . */
@ GuardedBy ( "lock" ) private void endWaitingFor ( Guard guard ) { } }

implementation:
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 ; } } }


signature:
public class Monitor { /** * Methods that loop waiting on a guard ' s condition until the guard is satisfied , while recording
 * this fact so that other threads know to check our guard and signal us . It ' s caller ' s
 * responsibility to ensure that the guard is * not * currently satisfied . */
@ GuardedBy ( "lock" ) private void await ( Guard guard , boolean signalBeforeWaiting ) throws InterruptedException { } }

implementation: if ( signalBeforeWaiting ) { signalNextWaiter ( ) ; } beginWaitingFor ( guard ) ; try { do { guard . condition . await ( ) ; } while ( ! guard . isSatisfied ( ) ) ; } finally { endWaitingFor ( guard ) ; }


signature:
public class Monitor { /** * Caller should check before calling that guard is not satisfied . */
@ GuardedBy ( "lock" ) private boolean awaitNanos ( Guard guard , long nanos , boolean signalBeforeWaiting ) throws InterruptedException { } }

implementation: 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 ) ; } }


signature:
public class Enums { /** * Returns the { @ link Field } in which { @ code enumValue } is defined . For example , to get the { @ code
 * Description } annotation on the { @ code GOLF } constant of enum { @ code Sport } , use { @ code
 * Enums . getField ( Sport . GOLF ) . getAnnotation ( Description . class ) } .
 * @ since 12.0 */
@ GwtIncompatible // reflection
public static Field getField ( Enum < ? > enumValue ) { } }

implementation: Class < ? > clazz = enumValue . getDeclaringClass ( ) ; try { return clazz . getDeclaredField ( enumValue . name ( ) ) ; } catch ( NoSuchFieldException impossible ) { throw new AssertionError ( impossible ) ; }


signature:
public class Enums { /** * Returns an optional enum constant for the given type , using { @ link Enum # valueOf } . If the
 * constant does not exist , { @ link Optional # absent } is returned . A common use case is for parsing
 * user input or falling back to a default enum constant . For example , { @ code
 * Enums . getIfPresent ( Country . class , countryInput ) . or ( Country . DEFAULT ) ; }
 * @ since 12.0 */
public static < T extends Enum < T > > Optional < T > getIfPresent ( Class < T > enumClass , String value ) { } }

implementation: checkNotNull ( enumClass ) ; checkNotNull ( value ) ; return Platform . getEnumIfPresent ( enumClass , value ) ;


signature:
public class Enums { /** * Returns a converter that converts between strings and { @ code enum } values of type { @ code
 * enumClass } using { @ link Enum # valueOf ( Class , String ) } and { @ link Enum # name ( ) } . The converter
 * will throw an { @ code IllegalArgumentException } if the argument is not the name of any enum
 * constant in the specified enum .
 * @ since 16.0 */
public static < T extends Enum < T > > Converter < String , T > stringConverter ( final Class < T > enumClass ) { } }

implementation: return new StringConverter < T > ( enumClass ) ;


signature:
public class MoreExecutors { /** * Creates an { @ link ExecutorService } whose { @ code submit } and { @ code invokeAll } methods submit
 * { @ link ListenableFutureTask } instances to the given delegate executor . Those methods , as well
 * as { @ code execute } and { @ code invokeAny } , are implemented in terms of calls to { @ code
 * delegate . execute } . All other methods are forwarded unchanged to the delegate . This implies that
 * the returned { @ code ListeningExecutorService } never calls the delegate ' s { @ code submit } , { @ code
 * invokeAll } , and { @ code invokeAny } methods , so any special handling of tasks must be implemented
 * in the delegate ' s { @ code execute } method or by wrapping the returned { @ code
 * ListeningExecutorService } .
 * < p > If the delegate executor was already an instance of { @ code ListeningExecutorService } , it is
 * returned untouched , and the rest of this documentation does not apply .
 * @ since 10.0 */
@ GwtIncompatible // TODO
public static ListeningExecutorService listeningDecorator ( ExecutorService delegate ) { } }

implementation: return ( delegate instanceof ListeningExecutorService ) ? ( ListeningExecutorService ) delegate : ( delegate instanceof ScheduledExecutorService ) ? new ScheduledListeningDecorator ( ( ScheduledExecutorService ) delegate ) : new ListeningDecorator ( delegate ) ;


signature:
public class MoreExecutors { /** * Shuts down the given executor service gradually , first disabling new submissions and later , if
 * necessary , cancelling remaining tasks .
 * < p > The method takes the following steps :
 * < ol >
 * < li > calls { @ link ExecutorService # shutdown ( ) } , disabling acceptance of new submitted tasks .
 * < li > awaits executor service termination for half of the specified timeout .
 * < li > if the timeout expires , it calls { @ link ExecutorService # shutdownNow ( ) } , cancelling
 * pending tasks and interrupting running tasks .
 * < li > awaits executor service termination for the other half of the specified timeout .
 * < / ol >
 * < p > If , at any step of the process , the calling thread is interrupted , the method calls { @ link
 * ExecutorService # shutdownNow ( ) } and returns .
 * @ param service the { @ code ExecutorService } to shut down
 * @ param timeout the maximum time to wait for the { @ code ExecutorService } to terminate
 * @ param unit the time unit of the timeout argument
 * @ return { @ code true } if the { @ code ExecutorService } was terminated successfully , { @ code false }
 * if the call timed out or was interrupted
 * @ since 17.0 */
@ Beta @ CanIgnoreReturnValue @ GwtIncompatible // concurrency
@ SuppressWarnings ( "GoodTime" ) // should accept a java . time . Duration
public static boolean shutdownAndAwaitTermination ( ExecutorService service , long timeout , TimeUnit unit ) { } }

implementation:
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 ( ) ;


signature:
public class MoreExecutors { /** * Returns an Executor that will propagate { @ link RejectedExecutionException } from the delegate
 * executor to the given { @ code future } .
 * < p > Note , the returned executor can only be used once . */
static Executor rejectionPropagatingExecutor ( final Executor delegate , final AbstractFuture < ? > future ) { } }

implementation:
checkNotNull ( delegate ) ; checkNotNull ( future ) ; if ( delegate == directExecutor ( ) ) { // directExecutor ( ) cannot throw RejectedExecutionException
return delegate ; } return new Executor ( ) { boolean thrownFromDelegate = true ; @ Override public void execute ( final Runnable command ) { try { delegate . execute ( new Runnable ( ) { @ Override public void run ( ) { thrownFromDelegate = false ; command . run ( ) ; } } ) ; } catch ( RejectedExecutionException e ) { if ( thrownFromDelegate ) { // wrap exception ?
future . setException ( e ) ; } // otherwise it must have been thrown from a transitive call and the delegate runnable
// should have handled it .
} } } ;


signature:
public class CharSink { /** * Opens a new buffered { @ link Writer } for writing to this sink . The returned stream is not
 * required to be a { @ link BufferedWriter } in order to allow implementations to simply delegate to
 * { @ link # openStream ( ) } when the stream returned by that method does not benefit from additional
 * buffering . This method returns a new , independent writer each time it is called .
 * < p > The caller is responsible for ensuring that the returned writer is closed .
 * @ throws IOException if an I / O error occurs while opening the writer
 * @ since 15.0 ( in 14.0 with return type { @ link BufferedWriter } ) */
public Writer openBufferedStream ( ) throws IOException { } }

implementation: Writer writer = openStream ( ) ; return ( writer instanceof BufferedWriter ) ? ( BufferedWriter ) writer : new BufferedWriter ( writer ) ;


signature:
public class CharSink { /** * Writes the given character sequence to this sink .
 * @ throws IOException if an I / O error while writing to this sink */
public void write ( CharSequence charSequence ) throws IOException { } }

implementation:
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 ( ) ; }


signature:
public class CharSink { /** * Writes the given lines of text to this sink with each line ( including the last ) terminated with
 * the given line separator .
 * @ throws IOException if an I / O error occurs while writing to this sink */
public void writeLines ( Iterable < ? extends CharSequence > lines , String lineSeparator ) throws IOException { } }

implementation: writeLines ( lines . iterator ( ) , lineSeparator ) ;


signature:
public class CharSink { /** * Writes the given lines of text to this sink with each line ( including the last ) terminated with
 * the operating system ' s default line separator . This method is equivalent to { @ code
 * writeLines ( lines , System . getProperty ( " line . separator " ) ) } .
 * @ throws IOException if an I / O error occurs while writing to this sink
 * @ since 22.0 */
@ Beta public void writeLines ( Stream < ? extends CharSequence > lines ) throws IOException { } }

implementation: writeLines ( lines , System . getProperty ( "line.separator" ) ) ;


signature:
public class CharSink { /** * Writes the given lines of text to this sink with each line ( including the last ) terminated with
 * the given line separator .
 * @ throws IOException if an I / O error occurs while writing to this sink
 * @ since 22.0 */
@ Beta public void writeLines ( Stream < ? extends CharSequence > lines , String lineSeparator ) throws IOException { } }


signature:
public class Closer { /** * Stores the given throwable and rethrows it . It will be rethrown as is if it is an { @ code
 * IOException } , { @ code RuntimeException } , { @ code Error } or a checked exception of the given type .
 * Otherwise , it will be rethrown wrapped in a { @ code RuntimeException } . < b > Note : < / b > Be sure to
 * declare all of the checked exception types your try block can throw when calling an overload of
 * this method so as to avoid losing the original exception type .
 * < p > This method always throws , and as such should be called as { @ code throw closer . rethrow ( e ,
 * . . . ) ; } to ensure the compiler knows that it will throw .
 * @ return this method does not return ; it always throws
 * @ throws IOException when the given throwable is an IOException
 * @ throws X when the given throwable is of the declared type X */
public < X extends Exception > RuntimeException rethrow ( Throwable e , Class < X > declaredType ) throws IOException , X { } }

implementation: checkNotNull ( e ) ; thrown = e ; Throwables . propagateIfPossible ( e , IOException . class ) ; Throwables . propagateIfPossible ( e , declaredType ) ; throw new RuntimeException ( e ) ;


signature:
public class Closer { /** * Stores the given throwable and rethrows it . It will be rethrown as is if it is an { @ code
 * IOException } , { @ code RuntimeException } , { @ code Error } or a checked exception of either of the
 * given types . Otherwise , it will be rethrown wrapped in a { @ code RuntimeException } . < b > Note : < / b >
 * Be sure to declare all of the checked exception types your try block can throw when calling an
 * overload of this method so as to avoid losing the original exception type .
 * < p > This method always throws , and as such should be called as { @ code throw closer . rethrow ( e ,
 * . . . ) ; } to ensure the compiler knows that it will throw .
 * @ return this method does not return ; it always throws
 * @ throws IOException when the given throwable is an IOException
 * @ throws X1 when the given throwable is of the declared type X1
 * @ throws X2 when the given throwable is of the declared type X2 */
public < X1 extends Exception , X2 extends Exception > RuntimeException rethrow ( Throwable e , Class < X1 > declaredType1 , Class < X2 > declaredType2 ) throws IOException , X1 , X2 { } }

implementation: checkNotNull ( e ) ; thrown = e ; Throwables . propagateIfPossible ( e , IOException . class ) ; Throwables . propagateIfPossible ( e , declaredType1 , declaredType2 ) ; throw new RuntimeException ( e ) ;


signature:
public class Closer { /** * Closes all { @ code Closeable } instances that have been added to this { @ code Closer } . If an
 * exception was thrown in the try block and passed to one of the { @ code exceptionThrown } methods ,
 * any exceptions thrown when attempting to close a closeable will be suppressed . Otherwise , the
 * < i > first < / i > exception to be thrown from an attempt to close a closeable will be thrown and any
 * additional exceptions that are thrown after that will be suppressed . */
@ Override public void close ( ) throws IOException { } }

implementation:
Throwable throwable = thrown ; // close closeables in LIFO order
while ( ! stack . isEmpty ( ) ) { Closeable closeable = stack . removeFirst ( ) ; try { closeable . close ( ) ; } catch ( Throwable e ) { if ( throwable == null ) { throwable = e ; } else { suppressor . suppress ( closeable , throwable , e ) ; } } } if ( thrown == null && throwable != null ) { Throwables . propagateIfPossible ( throwable , IOException . class ) ; throw new AssertionError ( throwable ) ; // not possible
}


signature:
public class RemovalListeners { /** * Returns a { @ code RemovalListener } which processes all eviction notifications using { @ code
 * executor } .
 * @ param listener the backing listener
 * @ param executor the executor with which removal notifications are asynchronously executed */
public static < K , V > RemovalListener < K , V > asynchronous ( final RemovalListener < K , V > listener , final Executor executor ) { } }

implementation: checkNotNull ( listener ) ; checkNotNull ( executor ) ; return new RemovalListener < K , V > ( ) { @ Override public void onRemoval ( final RemovalNotification < K , V > notification ) { executor . execute ( new Runnable ( ) { @ Override public void run ( ) { listener . onRemoval ( notification ) ; } } ) ; } } ;


signature:
public class ExecutionList { /** * Adds the { @ code Runnable } and accompanying { @ code Executor } to the list of listeners to
 * execute . If execution has already begun , the listener is executed immediately .
 * < p > When selecting an executor , note that { @ code directExecutor } is dangerous in some cases . See
 * the discussion in the { @ link ListenableFuture # addListener ListenableFuture . addListener }
 * documentation . */
public void add ( Runnable runnable , Executor executor ) { } }

implementation:
// Fail fast on a null . We throw NPE here because the contract of Executor states that it throws
// NPE on null listener , so we propagate that contract up into the add method as well .
checkNotNull ( runnable , "Runnable was null." ) ; checkNotNull ( executor , "Executor was null." ) ; // Lock while we check state . We must maintain the lock while adding the new pair so that
// another thread can ' t run the list out from under us . We only add to the list if we have not
// yet started execution .
synchronized ( this ) { if ( ! executed ) { runnables = new RunnableExecutorPair ( runnable , executor , runnables ) ; return ; } } // Execute the runnable immediately . Because of scheduling this may end up getting called before
// some of the previously added runnables , but we ' re OK with that . If we want to change the
// contract to guarantee ordering among runnables we ' d have to modify the logic here to allow
// it .
executeListener ( runnable , executor ) ;


signature:
public class ExecutionList { /** * 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 } ) */
public void execute ( ) { } }

implementation:
// 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 ; }


signature:
public class Booleans { /** * Copies a collection of { @ code Boolean } instances into a new array of primitive { @ code boolean }
 * values .
 * < p > Elements are copied from the argument collection as if by { @ code collection . toArray ( ) } .
 * Calling this method is as thread - safe as calling that method .
 * < p > < b > Note : < / b > consider representing the collection as a { @ link java . util . BitSet } instead .
 * @ param collection a collection of { @ code Boolean } objects
 * @ return an array containing the same values as { @ code collection } , in the same order , converted
 * to primitives
 * @ throws NullPointerException if { @ code collection } or any of its elements is null */
public static boolean [ ] toArray ( Collection < Boolean > collection ) { } }

implementation:
if ( collection instanceof BooleanArrayAsList ) { return ( ( BooleanArrayAsList ) collection ) . toBooleanArray ( ) ; } Object [ ] boxedArray = collection . toArray ( ) ; int len = boxedArray . length ; boolean [ ] array = new boolean [ len ] ; for ( int i = 0 ; i < len ; i ++ ) { // checkNotNull for GWT ( do not optimize )
array [ i ] = ( Boolean ) checkNotNull ( boxedArray [ i ] ) ; } return array ;


signature:
public class Booleans { /** * Returns a fixed - size list backed by the specified array , similar to { @ link
 * Arrays # asList ( Object [ ] ) } . The list supports { @ link List # set ( int , Object ) } , but any attempt to
 * set a value to { @ code null } will result in a { @ link NullPointerException } .
 * < p > The returned list maintains the values , but not the identities , of { @ code Boolean } objects
 * written to or read from it . For example , whether { @ code list . get ( 0 ) = = list . get ( 0 ) } is true for
 * the returned list is unspecified .
 * @ param backingArray the array to back the list
 * @ return a list view of the array */
public static List < Boolean > asList ( boolean ... backingArray ) { } }

implementation: if ( backingArray . length == 0 ) { return Collections . emptyList ( ) ; } return new BooleanArrayAsList ( backingArray ) ;


signature:
public class Iterables { /** * Returns { @ code true } if { @ code iterable } contains any element { @ code o } for which { @ code
 * Objects . equals ( o , element ) } would return { @ code true } . Otherwise returns { @ code false } , even in
 * cases where { @ link Collection # contains } might throw { @ link NullPointerException } or { @ link
 * ClassCastException } . */
public static boolean contains ( Iterable < ? > iterable , @ Nullable Object element ) { } }

implementation: if ( iterable instanceof Collection ) { Collection < ? > collection = ( Collection < ? > ) iterable ; return Collections2 . safeContains ( collection , element ) ; } return Iterators . contains ( iterable . iterator ( ) , element ) ;


signature:
public class Iterables { /** * Removes , from an iterable , every element that satisfies the provided predicate .
 * < p > Removals may or may not happen immediately as each element is tested against the predicate .
 * The behavior of this method is not specified if { @ code predicate } is dependent on { @ code
 * removeFrom } .
 * < p > < b > Java 8 users : < / b > if { @ code removeFrom } is a { @ link Collection } , use { @ code
 * removeFrom . removeIf ( predicate ) } instead .
 * @ param removeFrom the iterable to ( potentially ) remove elements from
 * @ param predicate a predicate that determines whether an element should be removed
 * @ return { @ code true } if any elements were removed from the iterable
 * @ throws UnsupportedOperationException if the iterable does not support { @ code remove ( ) } .
 * @ since 2.0 */
@ CanIgnoreReturnValue public static < T > boolean removeIf ( Iterable < T > removeFrom , Predicate < ? super T > predicate ) { } }

implementation: if ( removeFrom instanceof Collection ) { return ( ( Collection < T > ) removeFrom ) . removeIf ( predicate ) ; } return Iterators . removeIf ( removeFrom . iterator ( ) , predicate ) ;


signature:
public class Iterables { /** * Returns an iterable whose iterators cycle indefinitely over the elements of { @ code iterable } .
 * < p > That iterator supports { @ code remove ( ) } if { @ code iterable . iterator ( ) } does . After { @ code
 * remove ( ) } is called , subsequent cycles omit the removed element , which is no longer in { @ code
 * iterable } . The iterator ' s { @ code hasNext ( ) } method returns { @ code true } until { @ code iterable }
 * is empty .
 * < p > < b > Warning : < / b > Typical uses of the resulting iterator may produce an infinite loop . You
 * should use an explicit { @ code break } or be certain that you will eventually remove all the
 * elements .
 * < p > To cycle over the iterable { @ code n } times , use the following : { @ code
 * Iterables . concat ( Collections . nCopies ( n , iterable ) ) }
 * < p > < b > Java 8 users : < / b > The { @ code Stream } equivalent of this method is { @ code
 * Stream . generate ( ( ) - > iterable ) . flatMap ( Streams : : stream ) } . */
public static < T > Iterable < T > cycle ( final Iterable < T > iterable ) { } }

implementation: checkNotNull ( iterable ) ; return new FluentIterable < T > ( ) { @ Override public Iterator < T > iterator ( ) { return Iterators . cycle ( iterable ) ; } @ Override public Spliterator < T > spliterator ( ) { return Stream . generate ( ( ) -> iterable ) . flatMap ( Streams :: stream ) . spliterator ( ) ; } @ Override public String toString ( ) { return iterable . toString ( ) + " (cycled)" ; } } ;


signature:
public class Iterables { /** * Returns a view of { @ code unfiltered } containing all elements that satisfy the input predicate
 * { @ code retainIfTrue } . The returned iterable ' s iterator does not support { @ code remove ( ) } .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ link Stream # filter } . */
public static < T > Iterable < T > filter ( final Iterable < T > unfiltered , final Predicate < ? super T > retainIfTrue ) { } }

implementation: checkNotNull ( unfiltered ) ; checkNotNull ( retainIfTrue ) ; return new FluentIterable < T > ( ) { @ Override public Iterator < T > iterator ( ) { return Iterators . filter ( unfiltered . iterator ( ) , retainIfTrue ) ; } @ Override public void forEach ( Consumer < ? super T > action ) { checkNotNull ( action ) ; unfiltered . forEach ( ( T a ) -> { if ( retainIfTrue . test ( a ) ) { action . accept ( a ) ; } } ) ; } @ Override public Spliterator < T > spliterator ( ) { return CollectSpliterators . filter ( unfiltered . spliterator ( ) , retainIfTrue ) ; } } ;


signature:
public class Iterables { /** * Returns the first element in { @ code iterable } that satisfies the given predicate , or { @ code
 * defaultValue } if none found . Note that this can usually be handled more naturally using { @ code
 * tryFind ( iterable , predicate ) . or ( defaultValue ) } .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ code
 * stream . filter ( predicate ) . findFirst ( ) . orElse ( defaultValue ) }
 * @ since 7.0 */
public static < T > @ Nullable T find ( Iterable < ? extends T > iterable , Predicate < ? super T > predicate , @ Nullable T defaultValue ) { } }

implementation: return Iterators . find ( iterable . iterator ( ) , predicate , defaultValue ) ;


signature:
public class Iterables { /** * Returns a view containing the result of applying { @ code function } to each element of { @ code
 * fromIterable } .
 * < p > The returned iterable ' s iterator supports { @ code remove ( ) } if { @ code fromIterable } ' s
 * iterator does . After a successful { @ code remove ( ) } call , { @ code fromIterable } no longer
 * contains the corresponding element .
 * < p > If the input { @ code Iterable } is known to be a { @ code List } or other { @ code Collection } ,
 * consider { @ link Lists # transform } and { @ link Collections2 # transform } .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ link Stream # map } */
public static < F , T > Iterable < T > transform ( final Iterable < F > fromIterable , final Function < ? super F , ? extends T > function ) { } }

implementation: checkNotNull ( fromIterable ) ; checkNotNull ( function ) ; return new FluentIterable < T > ( ) { @ Override public Iterator < T > iterator ( ) { return Iterators . transform ( fromIterable . iterator ( ) , function ) ; } @ Override public void forEach ( Consumer < ? super T > action ) { checkNotNull ( action ) ; fromIterable . forEach ( ( F f ) -> action . accept ( function . apply ( f ) ) ) ; } @ Override public Spliterator < T > spliterator ( ) { return CollectSpliterators . map ( fromIterable . spliterator ( ) , function ) ; } } ;


signature:
public class Iterables { /** * Returns a view of { @ code iterable } containing its first { @ code limitSize } elements . If { @ code
 * iterable } contains fewer than { @ code limitSize } elements , the returned view contains all of its
 * elements . The returned iterable ' s iterator supports { @ code remove ( ) } if { @ code iterable } ' s
 * iterator does .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ link Stream # limit }
 * @ param iterable the iterable to limit
 * @ param limitSize the maximum number of elements in the returned iterable
 * @ throws IllegalArgumentException if { @ code limitSize } is negative
 * @ since 3.0 */
public static < T > Iterable < T > limit ( final Iterable < T > iterable , final int limitSize ) { } }

implementation: checkNotNull ( iterable ) ; checkArgument ( limitSize >= 0 , "limit is negative" ) ; return new FluentIterable < T > ( ) { @ Override public Iterator < T > iterator ( ) { return Iterators . limit ( iterable . iterator ( ) , limitSize ) ; } @ Override public Spliterator < T > spliterator ( ) { return Streams . stream ( iterable ) . limit ( limitSize ) . spliterator ( ) ; } } ;


signature:
public class LittleEndianByteArray { /** * Load 8 bytes into long in a little endian manner , from the substring between position and
 * position + 8 . The array must have at least 8 bytes from offset ( inclusive ) .
 * @ param input the input bytes
 * @ param offset the offset into the array at which to start
 * @ return a long of a concatenated 8 bytes */
static long load64 ( byte [ ] input , int offset ) { } }

implementation:
// We don ' t want this in production code as this is the most critical part of the loop .
assert input . length >= offset + 8 ; // Delegates to the fast ( unsafe ) version or the fallback .
return byteArray . getLongLittleEndian ( input , offset ) ;


signature:
public class LittleEndianByteArray { /** * 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 */
static long load64Safely ( byte [ ] input , int offset , int length ) { } }

implementation:
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 ;


signature:
public class LittleEndianByteArray { /** * 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 */
static void store64 ( byte [ ] sink , int offset , long value ) { } }

implementation:
// 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 ) ;


signature:
public class LittleEndianByteArray { /** * 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 */
static int load32 ( byte [ ] source , int offset ) { } }

implementation:
// 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 ) ;


signature:
public class Callables { /** * Creates a { @ code Callable } which immediately returns a preset value each time it is called . */
public static < T > Callable < T > returning ( final @ Nullable T value ) { } }

implementation: return new Callable < T > ( ) { @ Override public T call ( ) { return value ; } } ;


signature:
public class Callables { /** * Creates an { @ link AsyncCallable } from a { @ link Callable } .
 * < p > The { @ link AsyncCallable } returns the { @ link ListenableFuture } resulting from { @ link
 * ListeningExecutorService # submit ( Callable ) } .
 * @ since 20.0 */
@ Beta @ GwtIncompatible public static < T > AsyncCallable < T > asAsyncCallable ( final Callable < T > callable , final ListeningExecutorService listeningExecutorService ) { } }

implementation: checkNotNull ( callable ) ; checkNotNull ( listeningExecutorService ) ; return new AsyncCallable < T > ( ) { @ Override public ListenableFuture < T > call ( ) throws Exception { return listeningExecutorService . submit ( callable ) ; } } ;


signature:
public class Callables { /** * Wraps the given runnable such that for the duration of { @ link Runnable # run } the thread that is
 * running with have the given name .
 * @ param task The Runnable to wrap
 * @ param nameSupplier The supplier of thread names , { @ link Supplier # get get } will be called once
 * for each invocation of the wrapped callable . */
@ GwtIncompatible // threads
static Runnable threadRenaming ( final Runnable task , final Supplier < String > nameSupplier ) { } }

implementation: checkNotNull ( nameSupplier ) ; checkNotNull ( task ) ; return new Runnable ( ) { @ Override public void run ( ) { Thread currentThread = Thread . currentThread ( ) ; String oldName = currentThread . getName ( ) ; boolean restoreName = trySetName ( nameSupplier . get ( ) , currentThread ) ; try { task . run ( ) ; } finally { if ( restoreName ) { boolean unused = trySetName ( oldName , currentThread ) ; } } } } ;


signature:
public class Callables { /** * Tries to set name of the given { @ link Thread } , returns true if successful . */
@ GwtIncompatible // threads
private static boolean trySetName ( final String threadName , Thread currentThread ) { } }

implementation:
// In AppEngine , this will always fail . Should we test for that explicitly using
// MoreExecutors . isAppEngine ? More generally , is there a way to see if we have the modifyThread
// permission without catching an exception ?
try { currentThread . setName ( threadName ) ; return true ; } catch ( SecurityException e ) { return false ; }


signature:
public class ImmutableSortedMultisetFauxverideShim { /** * Not supported . Use { @ link ImmutableSortedMultiset # toImmutableSortedMultiset } instead . This
 * method exists only to hide { @ link ImmutableMultiset # toImmutableMultiset } from consumers of
 * { @ code ImmutableSortedMultiset } .
 * @ throws UnsupportedOperationException always
 * @ deprecated Use { @ link ImmutableSortedMultiset # toImmutableSortedMultiset } .
 * @ since 22.0 */
@ Deprecated public static < T , E > Collector < T , ? , ImmutableMultiset < E > > toImmutableMultiset ( Function < ? super T , ? extends E > elementFunction , ToIntFunction < ? super T > countFunction ) { } }

implementation: throw new UnsupportedOperationException ( ) ;


signature:
public class GwtFluentFutureCatchingSpecialization { /** * In the GWT versions of the methods ( below ) , every exceptionType parameter is required to be
 * Class < Throwable > . To handle only certain kinds of exceptions under GWT , you ' ll need to write
 * your own instanceof tests . */
public final FluentFuture < V > catching ( Class < Throwable > exceptionType , Function < ? super Throwable , ? extends V > fallback , Executor executor ) { } }

implementation: return ( FluentFuture < V > ) Futures . catching ( this , exceptionType , fallback , executor ) ;


signature:
public class Preconditions { /** * Ensures the truth of an expression involving one or more parameters to the calling method .
 * @ param expression a boolean expression
 * @ param errorMessage the exception message to use if the check fails ; will be converted to a
 * string using { @ link String # valueOf ( Object ) }
 * @ throws IllegalArgumentException if { @ code expression } is false */
public static void checkArgument ( boolean expression , @ Nullable Object errorMessage ) { } }

implementation: if ( ! expression ) { throw new IllegalArgumentException ( String . valueOf ( errorMessage ) ) ; }


signature:
public class Preconditions { /** * Ensures the truth of an expression involving the state of the calling instance , but not
 * involving any parameters to the calling method .
 * @ param expression a boolean expression
 * @ param errorMessage the exception message to use if the check fails ; will be converted to a
 * string using { @ link String # valueOf ( Object ) }
 * @ throws IllegalStateException if { @ code expression } is false
 * @ see Verify # verify Verify . verify ( ) */
public static void checkState ( boolean expression , @ Nullable Object errorMessage ) { } }

implementation: if ( ! expression ) { throw new IllegalStateException ( String . valueOf ( errorMessage ) ) ; }


signature:
public class Preconditions { /** * Ensures that an object reference passed as a parameter to the calling method is not null .
 * @ param reference an object reference
 * @ return the non - null reference that was validated
 * @ throws NullPointerException if { @ code reference } is null
 * @ see Verify # verifyNotNull Verify . verifyNotNull ( ) */
@ CanIgnoreReturnValue public static < T extends @ NonNull Object > T checkNotNull ( T reference ) { } }

implementation: if ( reference == null ) { throw new NullPointerException ( ) ; } return reference ;


signature:
public class Preconditions { /** * Ensures that an object reference passed as a parameter to the calling method is not null .
 * @ param reference an object reference
 * @ param errorMessageTemplate a template for the exception message should the check fail . The
 * message is formed by replacing each { @ code % s } placeholder in the template with an
 * argument . These are matched by position - the first { @ code % s } gets { @ code
 * errorMessageArgs [ 0 ] } , etc . Unmatched arguments will be appended to the formatted message in
 * square braces . Unmatched placeholders will be left as - is .
 * @ param errorMessageArgs the arguments to be substituted into the message template . Arguments
 * are converted to strings using { @ link String # valueOf ( Object ) } .
 * @ return the non - null reference that was validated
 * @ throws NullPointerException if { @ code reference } is null
 * @ see Verify # verifyNotNull Verify . verifyNotNull ( ) */
@ CanIgnoreReturnValue public static < T extends @ NonNull Object > T checkNotNull ( T reference , @ Nullable String errorMessageTemplate , Object @ Nullable . . . errorMessageArgs ) { } }

implementation: if ( reference == null ) { throw new NullPointerException ( lenientFormat ( errorMessageTemplate , errorMessageArgs ) ) ; } return reference ;


signature:
public class Preconditions { /** * Ensures that an object reference passed as a parameter to the calling method is not null .
 * < p > See { @ link # checkNotNull ( Object , String , Object . . . ) } for details .
 * @ since 20.0 ( varargs overload since 2.0) */
@ CanIgnoreReturnValue public static < T extends @ NonNull Object > T checkNotNull ( T obj , @ Nullable String errorMessageTemplate , char p1 ) { } }

implementation: if ( obj == null ) { throw new NullPointerException ( lenientFormat ( errorMessageTemplate , p1 ) ) ; } return obj ;


signature:
public class MediaType { /** * < em > Replaces < / em > all parameters with the given parameters .
 * @ throws IllegalArgumentException if any parameter or value is invalid */
public MediaType withParameters ( Multimap < String , String > parameters ) { } }

implementation: return create ( type , subtype , parameters ) ;


signature:
public class MediaType { /** * < em > Replaces < / em > all parameters with the given attribute with a single parameter with the
 * given value . If multiple parameters with the same attributes are necessary use { @ link
 * # withParameters ( String , Iterable ) } . Prefer { @ link # withCharset } for setting the { @ code charset }
 * parameter when using a { @ link Charset } object .
 * @ throws IllegalArgumentException if either { @ code attribute } or { @ code value } is invalid */
public MediaType withParameter ( String attribute , String value ) { } }

implementation: return withParameters ( attribute , ImmutableSet . of ( value ) ) ;


signature:
public class MediaType { /** * Returns a new instance with the same type and subtype as this instance , with the { @ code
 * charset } parameter set to the { @ link Charset # name name } of the given charset . Only one { @ code
 * charset } parameter will be present on the new instance regardless of the number set on this
 * one .
 * < p > If a charset must be specified that is not supported on this JVM ( and thus is not
 * representable as a { @ link Charset } instance , use { @ link # withParameter } . */
public MediaType withCharset ( Charset charset ) { } }

implementation:
checkNotNull ( charset ) ; MediaType withCharset = withParameter ( CHARSET_ATTRIBUTE , charset . name ( ) ) ; // precache the charset so we don ' t need to parse it
withCharset . parsedCharset = Optional . of ( charset ) ; return withCharset ;


signature:
public class 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 . */
public static MediaType create ( String type , String subtype ) { } }

implementation: MediaType mediaType = create ( type , subtype , ImmutableListMultimap . < String , String > of ( ) ) ; mediaType . parsedCharset = Optional . absent ( ) ; return mediaType ;