signature:
public class StateMachineConfig { /** * Specify the arguments that must be supplied when a specific trigger is fired
 * @ param trigger The underlying trigger value
 * @ param classe0 Class argument
 * @ param classe1 Class argument
 * @ param classe2 Class argument
 * @ param < TArg0 > Type of the first trigger argument
 * @ param < TArg1 > Type of the second trigger argument
 * @ param < TArg2 > Type of the third trigger argument
 * @ return An object that can be passed to the fire ( ) method in order to fire the parameterised trigger */
public < TArg0 , TArg1 , TArg2 > TriggerWithParameters3 < TArg0 , TArg1 , TArg2 , TTrigger > setTriggerParameters ( TTrigger trigger , Class < TArg0 > classe0 , Class < TArg1 > classe1 , Class < TArg2 > classe2 ) { } }

implementation: TriggerWithParameters3 < TArg0 , TArg1 , TArg2 , TTrigger > configuration = new TriggerWithParameters3 < > ( trigger , classe0 , classe1 , classe2 ) ; saveTriggerConfiguration ( configuration ) ; return configuration ;


signature:
public class ExtendedSettableFuture { /** * Sets this current future with the result of the delegate .
 * Values and exceptions are both propagated to this Future .
 * If this Future is cancelled , than the delegate will also be cancelled
 * with the same interrupt flag . */
public void setAsync ( ListenableFuture < ? extends V > delegate ) { } }

implementation:
delegate . addListener ( ( ) -> { if ( super . isDone ( ) ) { // Opportunistically avoid calling getDone . This is critical for the performance
// of whenAnyCompleteCancelOthers because calling getDone for cancelled Future
// constructs CancellationException and populates stack trace .
// See BenchmarkWhenAnyCompleteCancelOthers for benchmark numbers .
return ; } try { set ( getDone ( delegate ) ) ; } catch ( ExecutionException e ) { setException ( e . getCause ( ) ) ; } catch ( RuntimeException | Error e ) { setException ( e ) ; } } , directExecutor ( ) ) ; super . addListener ( ( ) -> { if ( super . isCancelled ( ) ) { delegate . cancel ( super . wasInterrupted ( ) ) ; } } , directExecutor ( ) ) ;


signature:
public class JsonCodec { /** * Converts the specified instance to json .
 * @ param instance the instance to convert to json
 * @ return json string
 * @ throws IllegalArgumentException if the specified instance can not be converted to json */
public String toJson ( T instance ) throws IllegalArgumentException { } }

implementation: try { return mapper . writeValueAsString ( instance ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( format ( "%s could not be converted to JSON" , instance . getClass ( ) . getName ( ) ) , e ) ; }


signature:
public class JsonCodec { /** * Converts the specified instance to optional json string with a length limit . Returns Optional . empty ( ) if length limit is exceeded .
 * @ param instance the instance to convert to json
 * @ param lengthLimit the maximum length of the serialized string in characters
 * @ return json string
 * @ throws IllegalArgumentException if the specified instance can not be converted to json */
public Optional < String > toJsonWithLengthLimit ( T instance , int lengthLimit ) { } }

implementation: try ( StringWriter stringWriter = new StringWriter ( ) ; LengthLimitedWriter lengthLimitedWriter = new LengthLimitedWriter ( stringWriter , lengthLimit ) ) { mapper . writeValue ( lengthLimitedWriter , instance ) ; return Optional . of ( stringWriter . getBuffer ( ) . toString ( ) ) ; } catch ( LengthLimitExceededException e ) { return Optional . empty ( ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( format ( "%s could not be converted to JSON" , instance . getClass ( ) . getName ( ) ) , e ) ; }


signature:
public class JsonCodec { /** * Coverts the specified json bytes ( UTF - 8 ) into an instance of type T .
 * @ param json the json bytes ( UTF - 8 ) to parse
 * @ return parsed response ; never null
 * @ throws IllegalArgumentException if the json bytes can not be converted to the type T */
public T fromJson ( byte [ ] json ) throws IllegalArgumentException { } }

implementation: try { return mapper . readValue ( json , javaType ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( format ( "Invalid JSON bytes for %s" , javaType ) , e ) ; }


signature:
public class JsonCodec { /** * Converts the specified instance to json .
 * @ param instance the instance to convert to json
 * @ return json bytes ( UTF - 8)
 * @ throws IllegalArgumentException if the specified instance can not be converted to json */
public byte [ ] toJsonBytes ( T instance ) throws IllegalArgumentException { } }

implementation: try { return mapper . writeValueAsBytes ( instance ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( format ( "%s could not be converted to JSON" , instance . getClass ( ) . getName ( ) ) , e ) ; }


signature:
public class LifeCycleManager { /** * Start the life cycle - all instances will have their { @ link javax . annotation . PostConstruct } method ( s ) called
 * @ throws Exception errors */
public void start ( ) throws Exception { } }

implementation:
if ( ! state . compareAndSet ( State . LATENT , State . STARTING ) ) { throw new Exception ( "System already starting" ) ; } log . info ( "Life cycle starting..." ) ; for ( Object obj : managedInstances ) { LifeCycleMethods methods = methodsMap . get ( obj . getClass ( ) ) ; if ( ! methods . hasFor ( PreDestroy . class ) ) { managedInstances . remove ( obj ) ; // remove reference to instances that aren ' t needed anymore
} } Thread thread = new Thread ( ( ) -> { try { stop ( ) ; } catch ( Exception e ) { log . error ( e , "Trying to shut down" ) ; } } ) ; shutdownHook . set ( thread ) ; Runtime . getRuntime ( ) . addShutdownHook ( thread ) ; state . set ( State . STARTED ) ; log . info ( "Life cycle startup complete. System ready." ) ;


signature:
public class LifeCycleManager { /** * Stop the life cycle - all instances will have their { @ link javax . annotation . PreDestroy } method ( s ) called
 * @ throws Exception errors */
public void stop ( ) throws Exception { } }

implementation: if ( ! state . compareAndSet ( State . STARTED , State . STOPPING ) ) { return ; } Thread thread = shutdownHook . getAndSet ( null ) ; if ( thread != null ) { try { Runtime . getRuntime ( ) . removeShutdownHook ( thread ) ; } catch ( IllegalStateException ignored ) { } } log . info ( "Life cycle stopping..." ) ; List < Object > reversedInstances = new ArrayList < > ( managedInstances ) ; Collections . reverse ( reversedInstances ) ; for ( Object obj : reversedInstances ) { log . debug ( "Stopping %s" , obj . getClass ( ) . getName ( ) ) ; LifeCycleMethods methods = methodsMap . get ( obj . getClass ( ) ) ; for ( Method preDestroy : methods . methodsFor ( PreDestroy . class ) ) { log . debug ( "\t%s()" , preDestroy . getName ( ) ) ; preDestroy . invoke ( obj ) ; } } state . set ( State . STOPPED ) ; log . info ( "Life cycle stopped." ) ;


signature:
public class LifeCycleManager { /** * Add an additional managed instance
 * @ param instance instance to add
 * @ throws Exception errors */
public void addInstance ( Object instance ) throws Exception { } }

implementation: State currentState = state . get ( ) ; if ( ( currentState == State . STOPPING ) || ( currentState == State . STOPPED ) ) { throw new IllegalStateException ( ) ; } else { startInstance ( instance ) ; if ( methodsMap . get ( instance . getClass ( ) ) . hasFor ( PreDestroy . class ) ) { managedInstances . add ( instance ) ; } }


signature:
public class DenseHll { /** * Returns false if not overflow bucket matching the given bucket id was found */
private boolean setOverflow ( int bucket , int overflow ) { } }

implementation: for ( int i = 0 ; i < overflows ; i ++ ) { if ( overflowBuckets [ i ] == bucket ) { overflowValues [ i ] = ( byte ) overflow ; return true ; } } return false ;


signature:
public class DenseHll { /** * Returns " this " for chaining */
public DenseHll mergeWith ( DenseHll other ) { } }

implementation:
if ( indexBitLength != other . indexBitLength ) { throw new IllegalArgumentException ( String . format ( "Cannot merge HLLs with different number of buckets: %s vs %s" , numberOfBuckets ( indexBitLength ) , numberOfBuckets ( other . indexBitLength ) ) ) ; } int baseline = Math . max ( this . baseline , other . baseline ) ; int baselineCount = 0 ; int overflows = 0 ; int [ ] overflowBuckets = new int [ OVERFLOW_GROW_INCREMENT ] ; byte [ ] overflowValues = new byte [ OVERFLOW_GROW_INCREMENT ] ; int numberOfBuckets = numberOfBuckets ( indexBitLength ) ; for ( int i = 0 ; i < numberOfBuckets ; i ++ ) { int value = Math . max ( getValue ( i ) , other . getValue ( i ) ) ; int delta = value - baseline ; if ( delta == 0 ) { baselineCount ++ ; } else if ( delta > MAX_DELTA ) { // grow overflows arrays if necessary
overflowBuckets = Ints . ensureCapacity ( overflowBuckets , overflows + 1 , OVERFLOW_GROW_INCREMENT ) ; overflowValues = Bytes . ensureCapacity ( overflowValues , overflows + 1 , OVERFLOW_GROW_INCREMENT ) ; overflowBuckets [ overflows ] = i ; overflowValues [ overflows ] = ( byte ) ( delta - MAX_DELTA ) ; overflows ++ ; delta = MAX_DELTA ; } setDelta ( i , delta ) ; } this . baseline = ( byte ) baseline ; this . baselineCount = baselineCount ; this . overflows = overflows ; this . overflowBuckets = overflowBuckets ; this . overflowValues = overflowValues ; // all baseline values in one of the HLLs lost to the values
// in the other HLL , so we need to adjust the final baseline
adjustBaselineIfNeeded ( ) ; return this ;


signature:
public class DerUtils { /** * Encodes a sequence of encoded values . */
public static byte [ ] encodeSequence ( byte [ ] ... encodedValues ) { } }

implementation: int length = 0 ; for ( byte [ ] encodedValue : encodedValues ) { length += encodedValue . length ; } byte [ ] lengthEncoded = encodeLength ( length ) ; ByteArrayDataOutput out = ByteStreams . newDataOutput ( 1 + lengthEncoded . length + length ) ; out . write ( SEQUENCE_TAG ) ; out . write ( lengthEncoded ) ; for ( byte [ ] entry : encodedValues ) { out . write ( entry ) ; } return out . toByteArray ( ) ;


signature:
public class DerUtils { /** * Decodes a sequence of encoded values . */
public static List < byte [ ] > decodeSequence ( byte [ ] sequence ) { } }

implementation:
int index = 0 ; // check tag
checkArgument ( sequence [ 0 ] == SEQUENCE_TAG , "Expected sequence tag" ) ; index ++ ; // read length
int sequenceDataLength = decodeLength ( sequence , index ) ; index += encodedLengthSize ( sequenceDataLength ) ; checkArgument ( sequenceDataLength + index == sequence . length , "Invalid sequence" ) ; // read elements
ImmutableList . Builder < byte [ ] > elements = ImmutableList . builder ( ) ; while ( index < sequence . length ) { int elementStart = index ; // skip the tag
index ++ ; // read length
int length = decodeLength ( sequence , index ) ; index += encodedLengthSize ( length ) ; byte [ ] data = Arrays . copyOfRange ( sequence , elementStart , index + length ) ; elements . add ( data ) ; index += length ; } return elements . build ( ) ;


signature:
public class DerUtils { /** * Decodes a optional element of a sequence . */
public static byte [ ] decodeSequenceOptionalElement ( byte [ ] element ) { } }

implementation:
int index = 0 ; // check tag
checkArgument ( ( element [ 0 ] & 0xE0 ) == 0xA0 , "Expected optional sequence element tag" ) ; index ++ ; // read length
int length = decodeLength ( element , index ) ; index += encodedLengthSize ( length ) ; checkArgument ( length + index == element . length , "Invalid optional sequence element" ) ; return Arrays . copyOfRange ( element , index , index + length ) ;


signature:
public class DerUtils { /** * Encodes a bit string padded with the specified number of bits .
 * The encoding is a byte containing the padBits followed by the value bytes . */
public static byte [ ] encodeBitString ( int padBits , byte [ ] value ) { } }

implementation: checkArgument ( padBits >= 0 && padBits < 8 , "Invalid pad bits" ) ; byte [ ] lengthEncoded = encodeLength ( value . length + 1 ) ; ByteArrayDataOutput out = ByteStreams . newDataOutput ( 2 + lengthEncoded . length + value . length ) ; out . write ( BIT_STRING_TAG ) ; out . write ( lengthEncoded ) ; out . write ( padBits ) ; out . write ( value ) ; return out . toByteArray ( ) ;


signature:
public class DerUtils { /** * Encodes an octet string . */
public static byte [ ] encodeOctetString ( byte [ ] value ) { } }

implementation: byte [ ] lengthEncoded = encodeLength ( value . length ) ; ByteArrayDataOutput out = ByteStreams . newDataOutput ( 2 + lengthEncoded . length + value . length ) ; out . write ( OCTET_STRING_TAG ) ; out . write ( lengthEncoded ) ; out . write ( value ) ; return out . toByteArray ( ) ;


signature:
public class DerUtils { /** * Encodes the length of a DER value . The encoding of a 7bit value is simply the value . Values needing more than 7bits
 * are encoded as a lead byte with the high bit set and containing the number of value bytes . Then the following bytes
 * encode the length using the least number of bytes possible . */
public static byte [ ] encodeLength ( int length ) { } }

implementation: if ( length < 128 ) { return new byte [ ] { ( byte ) length } ; } int numberOfBits = 32 - Integer . numberOfLeadingZeros ( length ) ; int numberOfBytes = ( numberOfBits + 7 ) / 8 ; byte [ ] encoded = new byte [ 1 + numberOfBytes ] ; encoded [ 0 ] = ( byte ) ( numberOfBytes | 0x80 ) ; for ( int i = 0 ; i < numberOfBytes ; i ++ ) { int byteToEncode = ( numberOfBytes - i ) ; int shiftSize = ( byteToEncode - 1 ) * 8 ; encoded [ i + 1 ] = ( byte ) ( length >>> shiftSize ) ; } return encoded ;


signature:
public class DerUtils { /** * Encode an OID number part . The encoding is a big endian varint . */
private static void writeOidPart ( ByteArrayOutputStream out , final int number ) { } }

implementation: if ( number < 128 ) { out . write ( ( byte ) number ) ; return ; } int numberOfBits = Integer . SIZE - Integer . numberOfLeadingZeros ( number ) ; int numberOfParts = ( numberOfBits + 6 ) / 7 ; for ( int i = 0 ; i < numberOfParts - 1 ; i ++ ) { int partToEncode = ( numberOfParts - i ) ; int shiftSize = ( partToEncode - 1 ) * 7 ; int part = ( number >>> shiftSize ) & 0x7F | 0x80 ; out . write ( part ) ; } out . write ( number & 0x7f ) ;


signature:
public class Logger { /** * Gets a named logger
 * @ param name the name of the logger
 * @ return the named logger */
public static Logger get ( String name ) { } }

implementation: java . util . logging . Logger logger = java . util . logging . Logger . getLogger ( name ) ; return new Logger ( logger ) ;


signature:
public class Logger { /** * Logs a message at DEBUG level .
 * @ param exception an exception associated with the debug message being logged
 * @ param message a literal message to log */
public void debug ( Throwable exception , String message ) { } }

implementation: logger . log ( FINE , message , exception ) ;


signature:
public class Logger { /** * Logs a message at DEBUG level .
 * Usage example :
 * < pre >
 * logger . debug ( " value is % s ( % d ms ) " , value , time ) ;
 * < / pre >
 * If the format string is invalid or the arguments are insufficient , an error will be logged and execution
 * will continue .
 * @ param format a format string compatible with String . format ( )
 * @ param args arguments for the format string */
public void debug ( String format , Object ... args ) { } }

implementation: if ( logger . isLoggable ( FINE ) ) { String message ; try { message = format ( format , args ) ; } catch ( IllegalFormatException e ) { logger . log ( SEVERE , illegalFormatMessageFor ( "DEBUG" , format , args ) , e ) ; message = rawMessageFor ( format , args ) ; } logger . fine ( message ) ; }


signature:
public class Logger { /** * Logs a message at INFO level .
 * Usage example :
 * < pre >
 * logger . info ( " value is % s ( % d ms ) " , value , time ) ;
 * < / pre >
 * If the format string is invalid or the arguments are insufficient , an error will be logged and execution
 * will continue .
 * @ param format a format string compatible with String . format ( )
 * @ param args arguments for the format string */
public void info ( String format , Object ... args ) { } }

implementation: if ( logger . isLoggable ( INFO ) ) { String message ; try { message = format ( format , args ) ; } catch ( IllegalFormatException e ) { logger . log ( SEVERE , illegalFormatMessageFor ( "INFO" , format , args ) , e ) ; message = rawMessageFor ( format , args ) ; } logger . info ( message ) ; }


signature:
public class Logger { /** * Logs a message at WARN level .
 * @ param exception an exception associated with the warning being logged
 * @ param message a literal message to log */
public void warn ( Throwable exception , String message ) { } }

implementation: logger . log ( WARNING , message , exception ) ;


signature:
public class Logger { /** * Logs a message at ERROR level .
 * @ param exception an exception associated with the error being logged
 * @ param message a literal message to log */
public void error ( Throwable exception , String message ) { } }

implementation: logger . log ( SEVERE , message , exception ) ;


signature:
public class Logger { /** * Logs a message at ERROR level . The value of { @ code exception . getMessage ( ) } will be used as the log message .
 * Usage example :
 * < pre >
 * logger . error ( e ) ;
 * < / pre >
 * @ param exception an exception associated with the error being logged */
public void error ( Throwable exception ) { } }

implementation: if ( logger . isLoggable ( SEVERE ) ) { logger . log ( SEVERE , exception . getMessage ( ) , exception ) ; }


signature:
public class HttpUriBuilder { /** * Replace the current path with the given unencoded path */
public HttpUriBuilder replacePath ( String path ) { } }

implementation: requireNonNull ( path , "path is null" ) ; if ( ! path . isEmpty ( ) && ! path . startsWith ( "/" ) ) { path = "/" + path ; } this . path = path ; return this ;


signature:
public class HttpUriBuilder { /** * Append an unencoded path .
 * All reserved characters except ' / ' will be percent - encoded . ' / ' are considered as path separators and
 * appended verbatim . */
public HttpUriBuilder appendPath ( String path ) { } }

implementation: requireNonNull ( path , "path is null" ) ; StringBuilder builder = new StringBuilder ( this . path ) ; if ( ! this . path . endsWith ( "/" ) ) { builder . append ( '/' ) ; } if ( path . startsWith ( "/" ) ) { path = path . substring ( 1 ) ; } builder . append ( path ) ; this . path = builder . toString ( ) ; return this ;


signature:
public class HttpUriBuilder { /** * input must be an ASCII string representing a percent - encoded UTF - 8 byte sequence */
private static String percentDecode ( String encoded ) { } }

implementation: Preconditions . checkArgument ( ascii ( ) . matchesAllOf ( encoded ) , "string must be ASCII" ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( encoded . length ( ) ) ; for ( int i = 0 ; i < encoded . length ( ) ; i ++ ) { char c = encoded . charAt ( i ) ; if ( c == '%' ) { Preconditions . checkArgument ( i + 2 < encoded . length ( ) , "percent encoded value is truncated" ) ; int high = Character . digit ( encoded . charAt ( i + 1 ) , 16 ) ; int low = Character . digit ( encoded . charAt ( i + 2 ) , 16 ) ; Preconditions . checkArgument ( high != - 1 && low != - 1 , "percent encoded value is not a valid hex string: " , encoded . substring ( i , i + 2 ) ) ; int value = ( high << 4 ) | ( low ) ; out . write ( value ) ; i += 2 ; } else { out . write ( ( int ) c ) ; } } try { return UTF_8 . newDecoder ( ) . onMalformedInput ( CodingErrorAction . REPORT ) . decode ( ByteBuffer . wrap ( out . toByteArray ( ) ) ) . toString ( ) ; } catch ( CharacterCodingException e ) { throw new IllegalArgumentException ( "input does not represent a proper UTF8-encoded string" ) ; }


signature:
public class DecayCounter { /** * This is a hack to work around limitations in Jmxutils . */
@ Deprecated public synchronized void resetTo ( DecayCounter counter ) { } }

implementation: synchronized ( counter ) { landmarkInSeconds = counter . landmarkInSeconds ; count = counter . count ; }


signature:
public class HttpServerChannelListener { /** * Calculate the summary statistics for the interarrival time of the onResponseContent callbacks . */
@ Nullable private static DoubleSummaryStats processContentTimestamps ( List < Long > contentTimestamps ) { } }

implementation:
requireNonNull ( contentTimestamps , "contentTimestamps is null" ) ; // no content ( HTTP 204 ) or there was a single response chunk ( so no interarrival time )
if ( contentTimestamps . size ( ) == 0 || contentTimestamps . size ( ) == 1 ) { return null ; } DoubleSummaryStatistics statistics = new DoubleSummaryStatistics ( ) ; long previousTimestamp = contentTimestamps . get ( 0 ) ; for ( int i = 1 ; i < contentTimestamps . size ( ) ; i ++ ) { long timestamp = contentTimestamps . get ( i ) ; statistics . accept ( NANOSECONDS . toMillis ( timestamp - previousTimestamp ) ) ; previousTimestamp = timestamp ; } return new DoubleSummaryStats ( statistics ) ;


signature:
public class ConfigurationFactory { /** * This is used by the configuration provider */
< T > T build ( ConfigurationProvider < T > configurationProvider ) { } }

implementation:
requireNonNull ( configurationProvider , "configurationProvider" ) ; registerConfigurationProvider ( configurationProvider , Optional . empty ( ) ) ; // check for a prebuilt instance
T instance = getCachedInstance ( configurationProvider ) ; if ( instance != null ) { return instance ; } ConfigurationBinding < T > configurationBinding = configurationProvider . getConfigurationBinding ( ) ; ConfigurationHolder < T > holder = build ( configurationBinding . getConfigClass ( ) , configurationBinding . getPrefix ( ) , getConfigDefaults ( configurationBinding . getKey ( ) ) ) ; instance = holder . getInstance ( ) ; // inform caller about warnings
if ( warningsMonitor != null ) { for ( Message message : holder . getProblems ( ) . getWarnings ( ) ) { warningsMonitor . onWarning ( message . toString ( ) ) ; } } // add to instance cache
T existingValue = putCachedInstance ( configurationProvider , instance ) ; // if key was already associated with a value , there was a
// creation race and we lost . Just use the winners ' instance ;
if ( existingValue != null ) { return existingValue ; } return instance ;


signature:
public class SignatureAlgorithmIdentifier { /** * Encode an OID number part . The encoding is a big endian varint . */
private static void writePart ( OutputStream out , final int number ) throws IOException { } }


signature:
public class ExponentiallyDecayingSample { /** * Adds an old value with a fixed timestamp to the sample .
 * @ param value the value to be added
 * @ param timestamp the epoch timestamp of { @ code value } in seconds */
public void update ( long value , long timestamp ) { } }

implementation:
lockForRegularUsage ( ) ; try { final double priority = weight ( timestamp - startTime ) / random ( ) ; final long newCount = count . incrementAndGet ( ) ; if ( newCount <= reservoirSize ) { values . put ( priority , value ) ; } else { Double first = values . firstKey ( ) ; if ( first < priority ) { if ( values . putIfAbsent ( priority , value ) == null ) { // ensure we always remove an item
while ( values . remove ( first ) == null ) { first = values . firstKey ( ) ; } } } } } finally { unlockForRegularUsage ( ) ; } final long now = System . nanoTime ( ) ; final long next = nextScaleTime . get ( ) ; if ( now >= next ) { rescale ( now , next ) ; }


signature:
public class ExponentiallyDecayingSample { /** * / * " A common feature of the above techniques — indeed , the key technique that
 * allows us to track the decayed weights efficiently — is that they maintain
 * counts and other quantities based on g ( ti − L ) , and only scale by g ( t − L )
 * at query time . But while g ( ti − L ) / g ( t − L ) is guaranteed to lie between zero
 * and one , the intermediate values of g ( ti − L ) could become very large . For
 * polynomial functions , these values should not grow too large , and should be
 * effectively represented in practice by floating point values without loss of
 * precision . For exponential functions , these values could grow quite large as
 * new values of ( ti − L ) become large , and potentially exceed the capacity of
 * common floating point types . However , since the values stored by the
 * algorithms are linear combinations of g values ( scaled sums ) , they can be
 * rescaled relative to a new landmark . That is , by the analysis of exponential
 * decay in Section III - A , the choice of L does not affect the final result . We
 * can therefore multiply each value based on L by a factor of exp ( − α ( L ′ − L ) ) ,
 * and obtain the correct value as if we had instead computed relative to a new
 * landmark L ′ ( and then use this new L ′ at query time ) . This can be done with
 * a linear pass over whatever data structure is being used . " */
private void rescale ( long now , long next ) { } }

implementation: if ( nextScaleTime . compareAndSet ( next , now + RESCALE_THRESHOLD ) ) { lockForRescale ( ) ; try { final long oldStartTime = startTime ; this . startTime = tick ( ) ; final ArrayList < Double > keys = new ArrayList < > ( values . keySet ( ) ) ; for ( Double key : keys ) { final Long value = values . remove ( key ) ; values . put ( key * exp ( - alpha * ( startTime - oldStartTime ) ) , value ) ; } } finally { unlockForRescale ( ) ; } }


signature:
public class HttpMBeanServerRpc { /** * Encodes the specified data into a base64 string .
 * @ param bytes The unencoded raw data . */
public static String base64Encode ( byte [ ] bytes ) { } }

implementation:
// always sequence of 4 characters for each 3 bytes ; padded with ' = ' s as necessary :
StringBuilder buf = new StringBuilder ( ( ( bytes . length + 2 ) / 3 ) * 4 ) ; // first , handle complete chunks ( fast loop )
int i = 0 ; for ( int end = bytes . length - 2 ; i < end ; ) { int chunk = ( ( bytes [ i ++ ] & 0xFF ) << 16 ) | ( ( bytes [ i ++ ] & 0xFF ) << 8 ) | ( bytes [ i ++ ] & 0xFF ) ; buf . append ( lookup [ chunk >> 18 ] ) ; buf . append ( lookup [ ( chunk >> 12 ) & 0x3F ] ) ; buf . append ( lookup [ ( chunk >> 6 ) & 0x3F ] ) ; buf . append ( lookup [ chunk & 0x3F ] ) ; } // then leftovers , if any
int len = bytes . length ; if ( i < len ) { // 1 or 2 extra bytes ?
int chunk = ( ( bytes [ i ++ ] & 0xFF ) << 16 ) ; buf . append ( lookup [ chunk >> 18 ] ) ; if ( i < len ) { // 2 bytes
chunk |= ( ( bytes [ i ] & 0xFF ) << 8 ) ; buf . append ( lookup [ ( chunk >> 12 ) & 0x3F ] ) ; buf . append ( lookup [ ( chunk >> 6 ) & 0x3F ] ) ; } else { // 1 byte
buf . append ( lookup [ ( chunk >> 12 ) & 0x3F ] ) ; buf . append ( '=' ) ; } buf . append ( '=' ) ; } return buf . toString ( ) ;


signature:
public class HttpMBeanServerRpc { /** * Decodes the specified base64 string back into its raw data .
 * @ param encoded The base64 encoded string . */
public static byte [ ] base64Decode ( String encoded ) { } }

implementation: int padding = 0 ; for ( int i = encoded . length ( ) - 1 ; encoded . charAt ( i ) == '=' ; i -- ) { padding ++ ; } int length = encoded . length ( ) * 6 / 8 - padding ; byte [ ] bytes = new byte [ length ] ; for ( int i = 0 , index = 0 , n = encoded . length ( ) ; i < n ; i += 4 ) { int word = reverseLookup [ encoded . charAt ( i ) ] << 18 ; word += reverseLookup [ encoded . charAt ( i + 1 ) ] << 12 ; word += reverseLookup [ encoded . charAt ( i + 2 ) ] << 6 ; word += reverseLookup [ encoded . charAt ( i + 3 ) ] ; for ( int j = 0 ; j < 3 && index + j < length ; j ++ ) { bytes [ index + j ] = ( byte ) ( word >> ( 8 * ( 2 - j ) ) ) ; } index += 3 ; } return bytes ;


signature:
public class LoggingOutputStream { /** * write the current buffer contents to the underlying logger . */
@ Override public synchronized void flush ( ) throws IOException { } }

implementation:
super . flush ( ) ; String record = this . toString ( ) ; reset ( ) ; if ( record . isEmpty ( ) || record . equals ( lineSeparator ) ) { // avoid empty records
return ; } logger . info ( record ) ;


signature:
public class JettyHttpClient { /** * todo this should be @ Managed but operations with parameters are broken in jmx utils https : / / github . com / martint / jmxutils / issues / 27 */
@ SuppressWarnings ( "UnusedDeclaration" ) public String dumpDestination ( URI uri ) { } }

implementation: Destination destination = httpClient . getDestination ( uri . getScheme ( ) , uri . getHost ( ) , uri . getPort ( ) ) ; if ( destination == null ) { return null ; } return dumpDestination ( destination ) ;


signature:
public class SparseHll { /** * Returns a index of the entry if found . Otherwise , it returns - ( insertionPoint + 1) */
private int searchBucket ( int bucketIndex ) { } }

implementation: int low = 0 ; int high = numberOfEntries - 1 ; while ( low <= high ) { int middle = ( low + high ) >>> 1 ; int middleBucketIndex = decodeBucketIndex ( entries [ middle ] ) ; if ( bucketIndex > middleBucketIndex ) { low = middle + 1 ; } else if ( bucketIndex < middleBucketIndex ) { high = middle - 1 ; } else { return middle ; } } return - ( low + 1 ) ; // not found . . . return insertion point


signature:
public class ExponentialDecay { /** * Compute the alpha decay factor such that the weight of an entry with age ' targetAgeInSeconds ' is targetWeight ' */
public static double computeAlpha ( double targetWeight , long targetAgeInSeconds ) { } }

implementation: checkArgument ( targetAgeInSeconds > 0 , "targetAgeInSeconds must be > 0" ) ; checkArgument ( targetWeight > 0 && targetWeight < 1 , "targetWeight must be in range (0, 1)" ) ; return - Math . log ( targetWeight ) / targetAgeInSeconds ;


signature:
public class MoreFutures { /** * Cancels the destination Future if the source Future is cancelled . */
public static < X , Y > void propagateCancellation ( ListenableFuture < ? extends X > source , Future < ? extends Y > destination , boolean mayInterruptIfRunning ) { } }

implementation: source . addListener ( ( ) -> { if ( source . isCancelled ( ) ) { destination . cancel ( mayInterruptIfRunning ) ; } } , directExecutor ( ) ) ;


signature:
public class MoreFutures { /** * Mirrors all results of the source Future to the destination Future .
 * This also propagates cancellations from the destination Future back to the source Future . */
public static < T > void mirror ( ListenableFuture < ? extends T > source , SettableFuture < ? super T > destination , boolean mayInterruptIfRunning ) { } }

implementation: FutureCallback < T > callback = new FutureCallback < T > ( ) { @ Override public void onSuccess ( @ Nullable T result ) { destination . set ( result ) ; } @ Override public void onFailure ( Throwable t ) { destination . setException ( t ) ; } } ; Futures . addCallback ( source , callback , directExecutor ( ) ) ; propagateCancellation ( destination , source , mayInterruptIfRunning ) ;


signature:
public class MoreFutures { /** * Attempts to unwrap a throwable that has been wrapped in a { @ link CompletionException } . */
public static Throwable unwrapCompletionException ( Throwable throwable ) { } }

implementation: if ( throwable instanceof CompletionException ) { return firstNonNull ( throwable . getCause ( ) , throwable ) ; } return throwable ;


signature:
public class MoreFutures { /** * Returns a future that can not be completed or canceled . */
@ Deprecated public static < V > CompletableFuture < V > unmodifiableFuture ( CompletableFuture < V > future ) { } }

implementation: return unmodifiableFuture ( future , false ) ;


signature:
public class MoreFutures { /** * Returns a future that can not be completed or optionally canceled . */
@ Deprecated public static < V > CompletableFuture < V > unmodifiableFuture ( CompletableFuture < V > future , boolean propagateCancel ) { } }

implementation: requireNonNull ( future , "future is null" ) ; Function < Boolean , Boolean > onCancelFunction ; if ( propagateCancel ) { onCancelFunction = future :: cancel ; } else { onCancelFunction = mayInterrupt -> false ; } UnmodifiableCompletableFuture < V > unmodifiableFuture = new UnmodifiableCompletableFuture < > ( onCancelFunction ) ; future . whenComplete ( ( value , exception ) -> { if ( exception != null ) { unmodifiableFuture . internalCompleteExceptionally ( exception ) ; } else { unmodifiableFuture . internalComplete ( value ) ; } } ) ; return unmodifiableFuture ;


signature:
public class MoreFutures { /** * Returns a failed future containing the specified throwable . */
@ Deprecated public static < V > CompletableFuture < V > failedFuture ( Throwable throwable ) { } }

implementation: requireNonNull ( throwable , "throwable is null" ) ; CompletableFuture < V > future = new CompletableFuture < > ( ) ; future . completeExceptionally ( throwable ) ; return future ;


signature:
public class MoreFutures { /** * Waits for the value from the future . If the future is failed , the exception
 * is thrown directly if it is an instance of the specified exception type or
 * unchecked , or it is wrapped in a RuntimeException . If the thread is
 * interrupted , the thread interruption flag is set and the original
 * InterruptedException is wrapped in a RuntimeException and thrown . */
public static < V , E extends Exception > V getFutureValue ( Future < V > future , Class < E > exceptionType ) throws E { } }

implementation: requireNonNull ( future , "future is null" ) ; requireNonNull ( exceptionType , "exceptionType is null" ) ; try { return future . get ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw new RuntimeException ( "interrupted" , e ) ; } catch ( ExecutionException e ) { Throwable cause = e . getCause ( ) == null ? e : e . getCause ( ) ; propagateIfPossible ( cause , exceptionType ) ; throw new RuntimeException ( cause ) ; }


signature:
public class MoreFutures { /** * Gets the current value of the future without waiting . If the future
 * value is null , an empty Optional is still returned , and in this case the caller
 * must check the future directly for the null value . */
public static < T > Optional < T > tryGetFutureValue ( Future < T > future ) { } }

implementation: requireNonNull ( future , "future is null" ) ; if ( ! future . isDone ( ) ) { return Optional . empty ( ) ; } return tryGetFutureValue ( future , 0 , MILLISECONDS ) ;


signature:
public class MoreFutures { /** * Waits for the the value from the future for the specified time . If the future
 * value is null , an empty Optional is still returned , and in this case the caller
 * must check the future directly for the null value . If the future is failed ,
 * the exception is thrown directly if unchecked or wrapped in a RuntimeException .
 * If the thread is interrupted , the thread interruption flag is set and the original
 * InterruptedException is wrapped in a RuntimeException and thrown . */
public static < V > Optional < V > tryGetFutureValue ( Future < V > future , int timeout , TimeUnit timeUnit ) { } }

implementation: return tryGetFutureValue ( future , timeout , timeUnit , RuntimeException . class ) ;


signature:
public class MoreFutures { /** * Waits for the the value from the future for the specified time . If the future
 * value is null , an empty Optional is still returned , and in this case the caller
 * must check the future directly for the null value . If the future is failed ,
 * the exception is thrown directly if it is an instance of the specified exception
 * type or unchecked , or it is wrapped in a RuntimeException . If the thread is
 * interrupted , the thread interruption flag is set and the original
 * InterruptedException is wrapped in a RuntimeException and thrown . */
public static < V , E extends Exception > Optional < V > tryGetFutureValue ( Future < V > future , int timeout , TimeUnit timeUnit , Class < E > exceptionType ) throws E { } }

implementation:
requireNonNull ( future , "future is null" ) ; checkArgument ( timeout >= 0 , "timeout is negative" ) ; requireNonNull ( timeUnit , "timeUnit is null" ) ; requireNonNull ( exceptionType , "exceptionType is null" ) ; try { return Optional . ofNullable ( future . get ( timeout , timeUnit ) ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw new RuntimeException ( "interrupted" , e ) ; } catch ( ExecutionException e ) { Throwable cause = e . getCause ( ) == null ? e : e . getCause ( ) ; propagateIfPossible ( cause , exceptionType ) ; throw new RuntimeException ( cause ) ; } catch ( TimeoutException expected ) { // expected
} return Optional . empty ( ) ;


signature:
public class MoreFutures { /** * Returns the result of the input { @ link Future } , which must have already completed .
 * Similar to Futures { @ link Futures # getDone ( Future ) } , but does not throw checked exceptions . */
public static < T > T getDone ( Future < T > future ) { } }

implementation: requireNonNull ( future , "future is null" ) ; checkArgument ( future . isDone ( ) , "future not done yet" ) ; return getFutureValue ( future ) ;


signature:
public class MoreFutures { /** * Checks that the completed future completed successfully . */
public static void checkSuccess ( Future < ? > future , String errorMessage ) { } }

implementation: requireNonNull ( future , "future is null" ) ; requireNonNull ( errorMessage , "errorMessage is null" ) ; checkArgument ( future . isDone ( ) , "future not done yet" ) ; try { getFutureValue ( future ) ; } catch ( RuntimeException e ) { throw new IllegalArgumentException ( errorMessage , e ) ; }


signature:
public class MoreFutures { /** * Creates a future that completes when the first future completes either normally
 * or exceptionally . Cancellation of the future propagates to the supplied futures . */
public static < V > ListenableFuture < V > whenAnyComplete ( Iterable < ? extends ListenableFuture < ? extends V > > futures ) { } }

implementation: requireNonNull ( futures , "futures is null" ) ; checkArgument ( ! isEmpty ( futures ) , "futures is empty" ) ; ExtendedSettableFuture < V > firstCompletedFuture = ExtendedSettableFuture . create ( ) ; for ( ListenableFuture < ? extends V > future : futures ) { firstCompletedFuture . setAsync ( future ) ; } return firstCompletedFuture ;


signature:
public class MoreFutures { /** * Creates a future that completes when the first future completes either normally
 * or exceptionally . All other futures are cancelled when one completes .
 * Cancellation of the returned future propagates to the supplied futures .
 * It is critical for the performance of this function that
 * { @ code guava . concurrent . generate _ cancellation _ cause } is false ,
 * which is the default since Guava v20. */
public static < V > ListenableFuture < V > whenAnyCompleteCancelOthers ( Iterable < ? extends ListenableFuture < ? extends V > > futures ) { } }

implementation:
requireNonNull ( futures , "futures is null" ) ; checkArgument ( ! isEmpty ( futures ) , "futures is empty" ) ; // wait for the first task to unblock and then cancel all futures to free up resources
ListenableFuture < V > anyComplete = whenAnyComplete ( futures ) ; anyComplete . addListener ( ( ) -> { for ( ListenableFuture < ? > future : futures ) { future . cancel ( true ) ; } } , directExecutor ( ) ) ; return anyComplete ;


signature:
public class MoreFutures { /** * Creates a future that completes when the first future completes either normally
 * or exceptionally . Cancellation of the future does not propagate to the supplied
 * futures . */
@ Deprecated public static < V > CompletableFuture < V > firstCompletedFuture ( Iterable < ? extends CompletionStage < ? extends V > > futures ) { } }

implementation: return firstCompletedFuture ( futures , false ) ;


signature:
public class MoreFutures { /** * Creates a future that completes when the first future completes either normally
 * or exceptionally . Cancellation of the future will optionally propagate to the
 * supplied futures . */
@ Deprecated public static < V > CompletableFuture < V > firstCompletedFuture ( Iterable < ? extends CompletionStage < ? extends V > > futures , boolean propagateCancel ) { } }

implementation: requireNonNull ( futures , "futures is null" ) ; checkArgument ( ! isEmpty ( futures ) , "futures is empty" ) ; CompletableFuture < V > future = new CompletableFuture < > ( ) ; for ( CompletionStage < ? extends V > stage : futures ) { stage . whenComplete ( ( value , exception ) -> { if ( exception != null ) { future . completeExceptionally ( exception ) ; } else { future . complete ( value ) ; } } ) ; } if ( propagateCancel ) { future . exceptionally ( throwable -> { if ( throwable instanceof CancellationException ) { for ( CompletionStage < ? extends V > sourceFuture : futures ) { if ( sourceFuture instanceof Future ) { ( ( Future < ? > ) sourceFuture ) . cancel ( true ) ; } } } return null ; } ) ; } return future ;


signature:
public class MoreFutures { /** * Returns an unmodifiable future that is completed when all of the given
 * futures complete . If any of the given futures complete exceptionally , then the
 * returned future also does so immediately , with a CompletionException holding this exception
 * as its cause . Otherwise , the results of the given futures are reflected in the
 * returned future as a list of results matching the input order . If no futures are
 * provided , returns a future completed with an empty list . */
@ Deprecated public static < V > CompletableFuture < List < V > > allAsList ( List < CompletableFuture < ? extends V > > futures ) { } }

implementation:
CompletableFuture < Void > allDoneFuture = CompletableFuture . allOf ( futures . toArray ( new CompletableFuture [ futures . size ( ) ] ) ) ; // Eagerly propagate exceptions , rather than waiting for all the futures to complete first ( default behavior )
for ( CompletableFuture < ? extends V > future : futures ) { future . whenComplete ( ( v , throwable ) -> { if ( throwable != null ) { allDoneFuture . completeExceptionally ( throwable ) ; } } ) ; } return unmodifiableFuture ( allDoneFuture . thenApply ( v -> futures . stream ( ) . map ( CompletableFuture :: join ) . collect ( Collectors . < V > toList ( ) ) ) ) ;


signature:
public class MoreFutures { /** * Returns a new future that is completed when the supplied future completes or
 * when the timeout expires . If the timeout occurs or the returned CompletableFuture
 * is canceled , the supplied future will be canceled . */
public static < T > ListenableFuture < T > addTimeout ( ListenableFuture < T > future , Callable < T > onTimeout , Duration timeout , ScheduledExecutorService executorService ) { } }

implementation: AsyncFunction < TimeoutException , T > timeoutHandler = timeoutException -> { try { return immediateFuture ( onTimeout . call ( ) ) ; } catch ( Throwable throwable ) { return immediateFailedFuture ( throwable ) ; } } ; return FluentFuture . from ( future ) . withTimeout ( timeout . toMillis ( ) , MILLISECONDS , executorService ) . catchingAsync ( TimeoutException . class , timeoutHandler , directExecutor ( ) ) ;


signature:
public class MoreFutures { /** * Returns a new future that is completed when the supplied future completes or
 * when the timeout expires . If the timeout occurs or the returned CompletableFuture
 * is canceled , the supplied future will be canceled . */
@ Deprecated public static < T > CompletableFuture < T > addTimeout ( CompletableFuture < T > future , Callable < T > onTimeout , Duration timeout , ScheduledExecutorService executorService ) { } }

implementation:
requireNonNull ( future , "future is null" ) ; requireNonNull ( onTimeout , "timeoutValue is null" ) ; requireNonNull ( timeout , "timeout is null" ) ; requireNonNull ( executorService , "executorService is null" ) ; // if the future is already complete , just return it
if ( future . isDone ( ) ) { return future ; } // create an unmodifiable future that propagates cancel
// down cast is safe because this is our code
UnmodifiableCompletableFuture < T > futureWithTimeout = ( UnmodifiableCompletableFuture < T > ) unmodifiableFuture ( future , true ) ; // schedule a task to complete the future when the time expires
ScheduledFuture < ? > timeoutTaskFuture = executorService . schedule ( new TimeoutFutureTask < > ( futureWithTimeout , onTimeout , future ) , timeout . toMillis ( ) , MILLISECONDS ) ; // when future completes , cancel the timeout task
future . whenCompleteAsync ( ( value , exception ) -> timeoutTaskFuture . cancel ( false ) , executorService ) ; return futureWithTimeout ;


signature:
public class MoreFutures { /** * Converts a ListenableFuture to a CompletableFuture . Cancellation of the
 * CompletableFuture will be propagated to the ListenableFuture . */
public static < V > CompletableFuture < V > toCompletableFuture ( ListenableFuture < V > listenableFuture ) { } }

implementation: requireNonNull ( listenableFuture , "listenableFuture is null" ) ; CompletableFuture < V > future = new CompletableFuture < > ( ) ; future . exceptionally ( throwable -> { if ( throwable instanceof CancellationException ) { listenableFuture . cancel ( true ) ; } return null ; } ) ; FutureCallback < V > callback = new FutureCallback < V > ( ) { @ Override public void onSuccess ( V result ) { future . complete ( result ) ; } @ Override public void onFailure ( Throwable t ) { future . completeExceptionally ( t ) ; } } ; Futures . addCallback ( listenableFuture , callback , directExecutor ( ) ) ; return future ;


signature:
public class MoreFutures { /** * Converts a CompletableFuture to a ListenableFuture . Cancellation of the
 * ListenableFuture will be propagated to the CompletableFuture . */
public static < V > ListenableFuture < V > toListenableFuture ( CompletableFuture < V > completableFuture ) { } }

implementation: requireNonNull ( completableFuture , "completableFuture is null" ) ; SettableFuture < V > future = SettableFuture . create ( ) ; propagateCancellation ( future , completableFuture , true ) ; completableFuture . whenComplete ( ( value , exception ) -> { if ( exception != null ) { future . setException ( exception ) ; } else { future . set ( value ) ; } } ) ; return future ;


signature:
public class MoreFutures { /** * Invokes the callback if the future completes successfully . Note , this uses the direct
 * executor , so the callback should not be resource intensive . */
public static < T > void addSuccessCallback ( ListenableFuture < T > future , Consumer < T > successCallback ) { } }

implementation: addSuccessCallback ( future , successCallback , directExecutor ( ) ) ;


signature:
public class MoreFutures { /** * Invokes the callback , using the specified executor , if the future completes successfully . */
public static < T > void addSuccessCallback ( ListenableFuture < T > future , Consumer < T > successCallback , Executor executor ) { } }

implementation: requireNonNull ( future , "future is null" ) ; requireNonNull ( successCallback , "successCallback is null" ) ; FutureCallback < T > callback = new FutureCallback < T > ( ) { @ Override public void onSuccess ( @ Nullable T result ) { successCallback . accept ( result ) ; } @ Override public void onFailure ( Throwable t ) { } } ; Futures . addCallback ( future , callback , executor ) ;


signature:
public class MoreFutures { /** * Invokes the callback if the future completes successfully . Note , this uses the direct
 * executor , so the callback should not be resource intensive . */
public static < T > void addSuccessCallback ( ListenableFuture < T > future , Runnable successCallback ) { } }


signature:
public class MoreFutures { /** * Invokes the callback , using the specified executor , if the future completes successfully . */
public static < T > void addSuccessCallback ( ListenableFuture < T > future , Runnable successCallback , Executor executor ) { } }

implementation: requireNonNull ( successCallback , "successCallback is null" ) ; addSuccessCallback ( future , t -> successCallback . run ( ) , executor ) ;


signature:
public class MoreFutures { /** * Invokes the callback if the future fails . Note , this uses the direct
 * executor , so the callback should not be resource intensive . */
public static < T > void addExceptionCallback ( ListenableFuture < T > future , Consumer < Throwable > exceptionCallback ) { } }

implementation: addExceptionCallback ( future , exceptionCallback , directExecutor ( ) ) ;


signature:
public class MoreFutures { /** * Invokes the callback if the future fails . Note , this uses the direct
 * executor , so the callback should not be resource intensive . */
public static < T > void addExceptionCallback ( ListenableFuture < T > future , Runnable exceptionCallback ) { } }


signature:
public class MoreFutures { /** * Invokes the callback , using the specified executor , if the future fails . */
public static < T > void addExceptionCallback ( ListenableFuture < T > future , Runnable exceptionCallback , Executor executor ) { } }

implementation: requireNonNull ( exceptionCallback , "exceptionCallback is null" ) ; addExceptionCallback ( future , t -> exceptionCallback . run ( ) , executor ) ;


signature:
public class QuantileDigest { /** * Adds a value to this digest . The value must be { @ code > = 0} */
public void add ( long value , long count ) { } }

implementation:
checkArgument ( count > 0 , "count must be > 0" ) ; boolean needsCompression = false ; double weight = count ; if ( alpha > 0.0 ) { long nowInSeconds = TimeUnit . NANOSECONDS . toSeconds ( ticker . read ( ) ) ; if ( nowInSeconds - landmarkInSeconds >= RESCALE_THRESHOLD_SECONDS ) { rescale ( nowInSeconds ) ; needsCompression = true ; // rescale affects weights globally , so force compression
} weight = weight ( nowInSeconds ) * count ; } max = Math . max ( max , value ) ; min = Math . min ( min , value ) ; double previousCount = weightedCount ; insert ( longToBits ( value ) , weight ) ; // When totalCount crosses the next multiple of k ( compression factor ) , the compression
// equation changes for every node in the tree , so we need to compress globally .
// Otherwise , only node along the insertion path are affected - - TODO : implement this .
int compressionFactor = calculateCompressionFactor ( ) ; if ( needsCompression || ( ( long ) previousCount ) / compressionFactor != ( ( long ) weightedCount ) / compressionFactor ) { compress ( ) ; }


signature:
public class QuantileDigest { /** * Get a lower bound on the quantiles for the given proportions . A returned q quantile is guaranteed to be within
 * the q - maxError and q quantiles .
 * The input list of quantile proportions must be sorted in increasing order , and each value must be in the range [ 0 , 1] */
public List < Long > getQuantilesLowerBound ( List < Double > quantiles ) { } }

implementation:
checkArgument ( Ordering . natural ( ) . isOrdered ( quantiles ) , "quantiles must be sorted in increasing order" ) ; for ( double quantile : quantiles ) { checkArgument ( quantile >= 0 && quantile <= 1 , "quantile must be between [0,1]" ) ; } List < Double > reversedQuantiles = ImmutableList . copyOf ( quantiles ) . reverse ( ) ; ImmutableList . Builder < Long > builder = ImmutableList . builder ( ) ; PeekingIterator < Double > iterator = Iterators . peekingIterator ( reversedQuantiles . iterator ( ) ) ; postOrderTraversal ( root , new Callback ( ) { private double sum ; @ Override public boolean process ( int node ) { sum += counts [ node ] ; while ( iterator . hasNext ( ) && sum > ( 1.0 - iterator . peek ( ) ) * weightedCount ) { iterator . next ( ) ; // we know the min value ever seen , so cap the percentile to provide better error
// bounds in this case
long value = Math . max ( lowerBound ( node ) , min ) ; builder . add ( value ) ; } return iterator . hasNext ( ) ; } } , TraversalOrder . REVERSE ) ; // we finished the traversal without consuming all quantiles . This means the remaining quantiles
// correspond to the max known value
while ( iterator . hasNext ( ) ) { builder . add ( min ) ; iterator . next ( ) ; } return builder . build ( ) . reverse ( ) ;


signature:
public class QuantileDigest { /** * Get an upper bound on the quantiles for the given proportions . A returned q quantile is guaranteed to be within
 * the q and q + maxError quantiles .
 * The input list of quantile proportions must be sorted in increasing order , and each value must be in the range [ 0 , 1] */
public List < Long > getQuantilesUpperBound ( List < Double > quantiles ) { } }

implementation:
checkArgument ( Ordering . natural ( ) . isOrdered ( quantiles ) , "quantiles must be sorted in increasing order" ) ; for ( double quantile : quantiles ) { checkArgument ( quantile >= 0 && quantile <= 1 , "quantile must be between [0,1]" ) ; } final ImmutableList . Builder < Long > builder = ImmutableList . builder ( ) ; final PeekingIterator < Double > iterator = Iterators . peekingIterator ( quantiles . iterator ( ) ) ; postOrderTraversal ( root , new Callback ( ) { private double sum ; public boolean process ( int node ) { sum += counts [ node ] ; while ( iterator . hasNext ( ) && sum > iterator . peek ( ) * weightedCount ) { iterator . next ( ) ; // we know the max value ever seen , so cap the percentile to provide better error
// bounds in this case
long value = Math . min ( upperBound ( node ) , max ) ; builder . add ( value ) ; } return iterator . hasNext ( ) ; } } ) ; // we finished the traversal without consuming all quantiles . This means the remaining quantiles
// correspond to the max known value
while ( iterator . hasNext ( ) ) { builder . add ( max ) ; iterator . next ( ) ; } return builder . build ( ) ;


signature:
public class QuantileDigest { /** * is calculated . */
public List < Bucket > getHistogram ( List < Long > bucketUpperBounds , MiddleFunction middleFunction ) { } }

implementation: checkArgument ( Ordering . natural ( ) . isOrdered ( bucketUpperBounds ) , "buckets must be sorted in increasing order" ) ; ImmutableList . Builder < Bucket > builder = ImmutableList . builder ( ) ; PeekingIterator < Long > iterator = Iterators . peekingIterator ( bucketUpperBounds . iterator ( ) ) ; HistogramBuilderStateHolder holder = new HistogramBuilderStateHolder ( ) ; double normalizationFactor = weight ( TimeUnit . NANOSECONDS . toSeconds ( ticker . read ( ) ) ) ; postOrderTraversal ( root , node -> { while ( iterator . hasNext ( ) && iterator . peek ( ) <= upperBound ( node ) ) { double bucketCount = holder . sum - holder . lastSum ; Bucket bucket = new Bucket ( bucketCount / normalizationFactor , holder . bucketWeightedSum / bucketCount ) ; builder . add ( bucket ) ; holder . lastSum = holder . sum ; holder . bucketWeightedSum = 0 ; iterator . next ( ) ; } holder . bucketWeightedSum += middleFunction . middle ( lowerBound ( node ) , upperBound ( node ) ) * counts [ node ] ; holder . sum += counts [ node ] ; return iterator . hasNext ( ) ; } ) ; while ( iterator . hasNext ( ) ) { double bucketCount = holder . sum - holder . lastSum ; Bucket bucket = new Bucket ( bucketCount / normalizationFactor , holder . bucketWeightedSum / bucketCount ) ; builder . add ( bucket ) ; iterator . next ( ) ; } return builder . build ( ) ;


signature:
public class QuantileDigest { /** * Remove the node if possible or set its count to 0 if it has children and
 * it needs to be kept around */
private int tryRemove ( int node ) { } }

implementation:
checkArgument ( node != - 1 , "node is -1" ) ; int left = lefts [ node ] ; int right = rights [ node ] ; if ( left == - 1 && right == - 1 ) { // leaf , just remove it
remove ( node ) ; return - 1 ; } if ( left != - 1 && right != - 1 ) { // node has both children so we can ' t physically remove it
counts [ node ] = 0 ; return node ; } // node has a single child , so remove it and return the child
remove ( node ) ; if ( left != - 1 ) { return left ; } else { return right ; }


signature:
public class QuantileDigest { /** * Computes the max " weight " of any path starting at node and ending at a leaf in the
 * hypothetical complete tree . The weight is the sum of counts in the ancestors of a given node */
private double computeMaxPathWeight ( int node ) { } }

implementation: if ( node == - 1 || levels [ node ] == 0 ) { return 0 ; } double leftMaxWeight = computeMaxPathWeight ( lefts [ node ] ) ; double rightMaxWeight = computeMaxPathWeight ( rights [ node ] ) ; return Math . max ( leftMaxWeight , rightMaxWeight ) + counts [ node ] ;


signature:
public class Threads { /** * Creates a { @ link ThreadFactory } that creates named threads
 * using the specified naming format .
 * @ param nameFormat a { @ link String # format ( String , Object . . . ) } - compatible
 * format string , to which a string will be supplied as the single
 * parameter . This string will be unique to this instance of the
 * ThreadFactory and will be assigned sequentially .
 * @ return the created ThreadFactory */
public static ThreadFactory threadsNamed ( String nameFormat ) { } }

implementation: return new ThreadFactoryBuilder ( ) . setNameFormat ( nameFormat ) . setThreadFactory ( new ContextClassLoaderThreadFactory ( Thread . currentThread ( ) . getContextClassLoader ( ) , defaultThreadFactory ( ) ) ) . build ( ) ;


signature:
public class Threads { /** * Creates a { @ link ThreadFactory } that creates named daemon threads .
 * using the specified naming format .
 * @ param nameFormat see { @ link # threadsNamed ( String ) }
 * @ return the created ThreadFactory */
public static ThreadFactory daemonThreadsNamed ( String nameFormat ) { } }

implementation: return new ThreadFactoryBuilder ( ) . setNameFormat ( nameFormat ) . setDaemon ( true ) . setThreadFactory ( new ContextClassLoaderThreadFactory ( Thread . currentThread ( ) . getContextClassLoader ( ) , defaultThreadFactory ( ) ) ) . build ( ) ;


signature:
public class CounterStat { /** * This is a hack to work around limitations in Jmxutils . */
@ Deprecated public void resetTo ( CounterStat counterStat ) { } }

implementation: oneMinute . resetTo ( counterStat . getOneMinute ( ) ) ; fiveMinute . resetTo ( counterStat . getFiveMinute ( ) ) ; fifteenMinute . resetTo ( counterStat . getFifteenMinute ( ) ) ; count . set ( counterStat . getTotalCount ( ) ) ;


signature:
public class HyperLogLog { /** * Adds a value that has already been hashed to the set of values tracked by this HyperLogLog instance .
 * @ param hash The hash should be the 64 least significant bits of the murmur3_128 hash of the value .
 * For example : io . airlift . slice . Murmur3 . hash64 ( value ) . */
public void addHash ( long hash ) { } }

implementation: instance . insertHash ( hash ) ; if ( instance instanceof SparseHll ) { instance = makeDenseIfNecessary ( ( SparseHll ) instance ) ; }


signature:
public class ConfigurationLoader { /** * Loads properties from the given file
 * @ param path file path
 * @ return properties
 * @ throws IOException errors */
public static Map < String , String > loadPropertiesFrom ( String path ) throws IOException { } }

implementation: Properties properties = new Properties ( ) ; try ( InputStream inputStream = new FileInputStream ( path ) ) { properties . load ( inputStream ) ; } return fromProperties ( properties ) ;


signature:
public class ConfigBinder { /** * Binds default values for all the instances of given config class for the current binder */
public < T > void bindConfigGlobalDefaults ( Class < T > configClass , ConfigDefaults < T > configDefaults ) { } }

implementation: Key < T > key = Key . get ( configClass , GlobalDefaults . class ) ; binder . bindConfigDefaults ( new ConfigDefaultsHolder < > ( key , configDefaults ) ) ;


signature:
public class CheckedExceptionRethrower { /** * < p > safeRethrow . < / p >
 * @ param t a { @ link java . lang . Throwable } object .
 * @ param < T > a T object .
 * @ return a T object . */
public static < T > T safeRethrow ( Throwable t ) { } }

implementation: CheckedExceptionRethrower . < RuntimeException > safeRethrow0 ( t ) ; return null ;


signature:
public class InternalExecutorServiceFactory { /** * Creates an executor service that creates thread ' s based on the < code > thread supplier < / code >
 * @ param threadSupplier The thread supplier
 * @ return An executor service that will use the thread created by the < code > threadSupplier < / code > when polling */
public static ExecutorService create ( final Function < Runnable , Thread > threadSupplier ) { } }

implementation: if ( threadSupplier == null ) { throw new IllegalArgumentException ( "Condition evaluation thread supplier cannot be null" ) ; } return create ( new BiFunction < Runnable , String , Thread > ( ) { @ Override public Thread apply ( Runnable runnable , String __ ) { return threadSupplier . apply ( runnable ) ; } } , null ) ;


signature:
public class InternalExecutorServiceFactory { /** * Creates an executor services that creates thread ' s based on the < code > thread supplier < / code > .
 * The first argument to the < code > threadSupplier < / code > is the Runnable ( the condition that will be evaluated ) .
 * The second argument is the default thread name generated by Awaitility .
 * @ param threadSupplier The thread supplier
 * @ return An executor service that will use the thread created by the < code > threadSupplier < / code > when polling */
public static ExecutorService create ( final BiFunction < Runnable , String , Thread > threadSupplier , final String alias ) { } }

implementation: if ( threadSupplier == null ) { throw new IllegalArgumentException ( "Condition evaluation thread supplier cannot be null" ) ; } return Executors . newSingleThreadExecutor ( new ThreadFactory ( ) { public Thread newThread ( Runnable r ) { final String threadName = generateDefaultThreadName ( alias ) ; return threadSupplier . apply ( r , threadName ) ; } } ) ;


signature:
public class FibonacciPollInterval { /** * Generate the next duration
 * @ param pollCount The number of times the condition has been polled ( evaluated )
 * @ param previousDuration The duration of the previously returned poll interval
 * @ return The next duration in the fibonacci sequence . */
public Duration next ( int pollCount , Duration previousDuration ) { } }

implementation: return new Duration ( fibonacci ( offset + pollCount ) , timeUnit ) ;


signature:
public class FibonacciPollInterval { /** * Tail recursive implementation of fibonacci */
private int fib ( int value , int current , int previous ) { } }

implementation: if ( value == 0 ) { return previous ; } else if ( value == 1 ) { return current ; } return fib ( value - 1 , current + previous , current ) ;


signature:
public class FieldAnnotationMatcherStrategy { /** * { @ inheritDoc } */
@ Override public void notFound ( Class < ? > type , boolean isInstanceField ) throws FieldNotFoundException { } }

implementation: throw new FieldNotFoundException ( "No field with annotation of type \"" + annotation . getName ( ) + "\" could be found in the class hierarchy of " + type . getName ( ) + "." ) ;


signature:
public class Duration { /** * Add a amount ( with the same time unit as the current duration )
 * @ param amount The amount to add
 * @ return A new amount */
public Duration plus ( long amount ) { } }

implementation: return new Plus ( ) . apply ( this , unit == null ? FOREVER : new Duration ( amount , unit ) ) ;


signature:
public class Duration { /** * Add a amount with the given time unit . For example :
 * < pre >
 * new Duration ( 2 , SECONDS ) . plus ( 4 , MILLISECONDS )
 * < / pre >
 * will return a Duration of 2004 { @ link TimeUnit # MILLISECONDS } .
 * < pre >
 * new Duration ( 2 , SECONDS ) . plus ( 1 , MINUTES )
 * < / pre >
 * will return a Duration of 62 { @ link TimeUnit # SECONDS } .
 * @ param amount The amount to add
 * @ param timeUnit The time unit to add
 * @ return A new amount */
public Duration plus ( long amount , TimeUnit timeUnit ) { } }

implementation: if ( timeUnit == null ) { throw new IllegalArgumentException ( "Time unit cannot be null" ) ; } return new Plus ( ) . apply ( this , new Duration ( amount , timeUnit ) ) ;


signature:
public class Duration { /** * Multiply this amount with the given amount
 * @ param amount The amount
 * @ return A new amount */
public Duration multiply ( long amount ) { } }

implementation: return new Multiply ( ) . apply ( this , unit == null ? FOREVER : new Duration ( amount , unit ) ) ;


signature:
public class Duration { /** * Divide this duration amount with the given amount
 * @ param amount The amount
 * @ return A new amount */
public Duration divide ( long amount ) { } }

implementation: return new Divide ( ) . apply ( this , unit == null ? FOREVER : new Duration ( amount , unit ) ) ;


signature:
public class Duration { /** * Subtract an amount ( with the same time unit as the current amount )
 * @ param amount The amount to add
 * @ return A new amount */
public Duration minus ( long amount ) { } }

implementation: return new Minus ( ) . apply ( this , unit == null ? FOREVER : new Duration ( amount , unit ) ) ;


signature:
public class Duration { /** * Subtract an amount with the given time unit . For example :
 * < pre >
 * new Duration ( 2 , SECONDS ) . minus ( 4 , MILLISECONDS )
 * < / pre >
 * will return a Duration of 1996 { @ link TimeUnit # MILLISECONDS } .
 * < pre >
 * new Duration ( 2 , MINUTES ) . minus ( 1 , SECONDS )
 * < / pre >
 * will return a Duration of 119 { @ link TimeUnit # SECONDS } .
 * @ param amount The amount to add
 * @ param timeUnit The time unit to add
 * @ return A new amount */
public Duration minus ( long amount , TimeUnit timeUnit ) { } }

implementation: if ( timeUnit == null ) { throw new IllegalArgumentException ( "Time unit cannot be null" ) ; } return new Minus ( ) . apply ( this , new Duration ( amount , timeUnit ) ) ;


signature:
public class WhiteboxImpl { /** * Find single field using strategy .
 * @ param strategy the strategy
 * @ param object the object
 * @ param checkHierarchy the check hierarchy
 * @ param startClass the start class
 * @ return the field */
private static Field findSingleFieldUsingStrategy ( FieldMatcherStrategy strategy , Object object , boolean checkHierarchy , Class < ? > startClass ) { } }

implementation: assertObjectInGetInternalStateIsNotNull ( object ) ; Field foundField = null ; final Class < ? > originalStartClass = startClass ; while ( startClass != null ) { final Field [ ] declaredFields = startClass . getDeclaredFields ( ) ; for ( Field field : declaredFields ) { if ( strategy . matches ( field ) && hasFieldProperModifier ( object , field ) ) { if ( foundField != null ) { throw new TooManyFieldsFoundException ( "Two or more fields matching " + strategy + "." ) ; } foundField = field ; } } if ( foundField != null ) { break ; } else if ( ! checkHierarchy ) { break ; } startClass = startClass . getSuperclass ( ) ; } if ( foundField == null ) { strategy . notFound ( originalStartClass , ! isClass ( object ) ) ; return null ; } foundField . setAccessible ( true ) ; return foundField ;


signature:
public class WhiteboxImpl { /** * Checks for field proper modifier .
 * @ param object the object
 * @ param field the field
 * @ return true , if successful */
private static boolean hasFieldProperModifier ( Object object , Field field ) { } }

implementation: return ( ( object instanceof Class < ? > && Modifier . isStatic ( field . getModifiers ( ) ) ) || ! ( object instanceof Class < ? > || Modifier . isStatic ( field . getModifiers ( ) ) ) ) ;


signature:
public class WhiteboxImpl { /** * Throw exception if field was not found .
 * @ param type the type
 * @ param fieldName the field name
 * @ param field the field */
public static void throwExceptionIfFieldWasNotFound ( Class < ? > type , String fieldName , Field field ) { } }

implementation: if ( field == null ) { throw new FieldNotFoundException ( "No field was found with name '" + fieldName + "' in class " + type . getName ( ) + "." ) ; }


signature:
public class WhiteboxImpl { /** * Get field annotated with a particular annotation . This method traverses
 * the class hierarchy when checking for the annotation .
 * @ param object The object to look for annotations . Note that if ' re you ' re
 * passing an object only instance fields are checked , passing a
 * class will only check static fields .
 * @ param annotationType The annotation types to look for
 * @ return A set of all fields containing the particular annotation ( s ) .
 * @ since 1.3 */
public static Field getFieldAnnotatedWith ( Object object , Class < ? extends Annotation > annotationType ) { } }

implementation: return findSingleFieldUsingStrategy ( new FieldAnnotationMatcherStrategy ( annotationType ) , object , true , getType ( object ) ) ;


signature:
public class WhiteboxImpl { /** * < p > getByNameAndType . < / p >
 * @ param object a { @ link java . lang . Object } object .
 * @ param fieldName a { @ link java . lang . String } object .
 * @ param expectedFieldType a { @ link java . lang . Class } object .
 * @ param < T > a T object .
 * @ return a T object . */
@ SuppressWarnings ( "unchecked" ) public static < T > T getByNameAndType ( Object object , String fieldName , Class < T > expectedFieldType ) { } }

implementation: Field foundField = findSingleFieldUsingStrategy ( new FieldNameAndTypeMatcherStrategy ( fieldName , expectedFieldType ) , object , true , getType ( object ) ) ; try { return ( T ) foundField . get ( object ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( "Internal error: Failed to get field in method getInternalState." , e ) ; }


signature:
public class HamcrestToStringFilter { /** * Filter words from the < code > matcher . toString ( ) < / code > so it looks nicer
 * when printed out . E . g . " not not " is removed and " is " are removed .
 * @ param matcher
 * the matcher
 * @ return A filtered version of the { @ link Matcher # toString ( ) } . */
static String filter ( Matcher < ? > matcher ) { } }

implementation: String matcherToString = matcher . toString ( ) ; for ( String wordToRemove : wordsToRemove ) { matcherToString = matcherToString . replaceAll ( wordToRemove , "" ) ; } return matcherToString ;


signature:
public class MethodCaller { /** * ( non - Javadoc )
 * @ see java . util . concurrent . Callable # call ( ) */
@ SuppressWarnings ( "unchecked" ) public T call ( ) throws InvocationTargetException , IllegalAccessException { } }

implementation: try { return ( T ) method . invoke ( target , args ) ; } catch ( IllegalAccessException e ) { return CheckedExceptionRethrower . safeRethrow ( e ) ; } catch ( InvocationTargetException e ) { return CheckedExceptionRethrower . safeRethrow ( e . getCause ( ) ) ; }


signature:
public class ConditionAwaiter { /** * < p > await . < / p >
 * @ param conditionEvaluationHandler The conditionEvaluationHandler */
@ SuppressWarnings ( "deprecation" ) public < T > void await ( final ConditionEvaluationHandler < T > conditionEvaluationHandler ) { } }

implementation:
final Duration pollDelay = conditionSettings . getPollDelay ( ) ; final Duration maxWaitTime = conditionSettings . getMaxWaitTime ( ) ; final Duration minWaitTime = conditionSettings . getMinWaitTime ( ) ; final long maxTimeout = maxWaitTime . getValue ( ) ; long pollingStartedNanos = System . nanoTime ( ) - pollDelay . getValueInNS ( ) ; int pollCount = 0 ; boolean succeededBeforeTimeout = false ; ConditionEvaluationResult lastResult = null ; Duration evaluationDuration = new Duration ( 0 , MILLISECONDS ) ; Future < ConditionEvaluationResult > currentConditionEvaluation = null ; try { if ( executor . isShutdown ( ) || executor . isTerminated ( ) ) { throw new IllegalStateException ( "The executor service that Awaitility is instructed to use has been shutdown so condition evaluation cannot be performed. Is there something wrong the thread or executor configuration?" ) ; } conditionEvaluationHandler . start ( ) ; if ( ! pollDelay . isZero ( ) ) { Thread . sleep ( pollDelay . getValueInMS ( ) ) ; } Duration pollInterval = pollDelay ; while ( maxWaitTime . compareTo ( evaluationDuration ) > 0 ) { pollCount = pollCount + 1 ; // Only wait for the next condition evaluation for at most what ' s remaining of
Duration maxWaitTimeForThisCondition = maxWaitTime . minus ( evaluationDuration ) ; currentConditionEvaluation = executor . submit ( new ConditionPoller ( pollInterval ) ) ; // Wait for condition evaluation to complete with " maxWaitTimeForThisCondition " or else throw TimeoutException
lastResult = currentConditionEvaluation . get ( maxWaitTimeForThisCondition . getValue ( ) , maxWaitTimeForThisCondition . getTimeUnit ( ) ) ; if ( lastResult . isSuccessful ( ) || lastResult . hasThrowable ( ) ) { break ; } pollInterval = conditionSettings . getPollInterval ( ) . next ( pollCount , pollInterval ) ; Thread . sleep ( pollInterval . getValueInMS ( ) ) ; evaluationDuration = calculateConditionEvaluationDuration ( pollDelay , pollingStartedNanos ) ; } evaluationDuration = calculateConditionEvaluationDuration ( pollDelay , pollingStartedNanos ) ; succeededBeforeTimeout = maxWaitTime . compareTo ( evaluationDuration ) > 0 ; } catch ( TimeoutException e ) { lastResult = new ConditionEvaluationResult ( false , null , e ) ; } catch ( ExecutionException e ) { lastResult = new ConditionEvaluationResult ( false , e . getCause ( ) , null ) ; } catch ( Throwable e ) { lastResult = new ConditionEvaluationResult ( false , e , null ) ; } finally { if ( currentConditionEvaluation != null ) { // Cancelling future in order to avoid race - condition with last result for Hamcrest matchers
// See https : / / github . com / awaitility / awaitility / issues / 109
currentConditionEvaluation . cancel ( true ) ; } } try { if ( uncaughtThrowable . get ( ) != null ) { throw uncaughtThrowable . get ( ) ; } else if ( lastResult != null && lastResult . hasThrowable ( ) ) { throw lastResult . getThrowable ( ) ; } else if ( ! succeededBeforeTimeout ) { final String maxWaitTimeLowerCase = maxWaitTime . getTimeUnitAsString ( ) ; final String message ; String timeoutMessage = getTimeoutMessage ( ) ; if ( conditionSettings . hasAlias ( ) ) { message = String . format ( "Condition with alias '%s' didn't complete within %s %s because %s." , conditionSettings . getAlias ( ) , maxTimeout , maxWaitTimeLowerCase , decapitalize ( timeoutMessage ) ) ; } else { message = String . format ( "%s within %s %s." , timeoutMessage , maxTimeout , maxWaitTimeLowerCase ) ; } Throwable cause = lastResult != null && lastResult . hasTrace ( ) ? lastResult . getTrace ( ) : null ; // Not all systems support deadlock detection so ignore if ThreadMXBean & ManagementFactory is not in classpath
if ( existInCP ( "java.lang.management.ThreadMXBean" ) && existInCP ( "java.lang.management.ManagementFactory" ) ) { java . lang . management . ThreadMXBean bean = java . lang . management . ManagementFactory . getThreadMXBean ( ) ; try { long [ ] threadIds = bean . findDeadlockedThreads ( ) ; if ( threadIds != null ) { cause = new DeadlockException ( threadIds ) ; } } catch ( UnsupportedOperationException ignored ) { // findDeadLockedThreads ( ) not supported on this VM ,
// don ' t init trace and move on .
} } throw new ConditionTimeoutException ( message , cause ) ; } else if ( evaluationDuration . compareTo ( minWaitTime ) < 0 ) { String message = String . format ( "Condition was evaluated in %s %s which is earlier than expected " + "minimum timeout %s %s" , evaluationDuration . getValue ( ) , evaluationDuration . getTimeUnit ( ) , minWaitTime . getValue ( ) , minWaitTime . getTimeUnit ( ) ) ; throw new ConditionTimeoutException ( message ) ; } } catch ( Throwable e ) { CheckedExceptionRethrower . safeRethrow ( e ) ; } finally { uncaughtThrowable . set ( null ) ; conditionSettings . getExecutorLifecycle ( ) . executeNormalCleanupBehavior ( executor ) ; }


signature:
public class ConditionAwaiter { /** * { @ inheritDoc } */
@ Override public void uncaughtException ( Thread thread , Throwable throwable ) { } }

implementation:
if ( ! conditionSettings . shouldExceptionBeIgnored ( throwable ) ) { uncaughtThrowable . set ( throwable ) ; // We shutdown the executor " now " in order to fail the test immediately
conditionSettings . getExecutorLifecycle ( ) . executeUnexpectedCleanupBehavior ( executor ) ; }


signature:
public class IterativePollInterval { /** * Generate the next Duration based on the supplied function . If you ' ve specified a start duration explicitly then
 * this start duration will override the value of < code > previousDuration < / code > when < code > pollCount < / code > is 1 ( i . e . the poll delay ) .
 * @ param pollCount The number of times the condition has been polled ( evaluated ) . Always a positive integer .
 * @ param previousDuration The duration of the previously returned poll interval .
 * @ return The duration of the next poll interval */
public Duration next ( int pollCount , Duration previousDuration ) { } }

implementation: final Duration durationToUse ; if ( pollCount == 1 && startDuration != null ) { durationToUse = startDuration ; } else { durationToUse = previousDuration ; } return function . apply ( durationToUse ) ;


signature:
public class IterativePollInterval { /** * Syntactic sugar for creating a { @ link IterativePollInterval } .
 * @ param function The function to use
 * @ param startDuration The start duration ( initial function value )
 * @ return A new instance of { @ link IterativePollInterval } */
public static IterativePollInterval iterative ( Function < Duration , Duration > function , Duration startDuration ) { } }

implementation: return new IterativePollInterval ( function , startDuration ) ;


signature:
public class MethodCallRecorder { /** * < p > createProxy . < / p >
 * @ param target a { @ link java . lang . Object } object .
 * @ return a { @ link java . lang . Object } object . */
public static Object createProxy ( Object target ) { } }

implementation: Object proxy = ByteBuddyProxyCreator . create ( target . getClass ( ) , MethodCallInterceptor . class ) ; lastTarget . set ( target ) ; return proxy ;


signature:
public class MethodCallRecorder { /** * < p > Getter for the field < code > lastTarget < / code > . < / p >
 * @ return a { @ link java . lang . Object } object . */
static Object getLastTarget ( ) { } }

implementation: Object target = lastTarget . get ( ) ; if ( target == null ) { throw new IllegalStateException ( NO_METHOD_CALL_RECORDED_MESSAGE ) ; } return target ;


signature:
public class MethodCallRecorder { /** * < p > Getter for the field < code > lastMethod < / code > . < / p >
 * @ return a { @ link java . lang . reflect . Method } object . */
static Method getLastMethod ( ) { } }

implementation: Method method = lastMethod . get ( ) ; if ( method == null ) { throw new IllegalStateException ( NO_METHOD_CALL_RECORDED_MESSAGE ) ; } return method ;


signature:
public class MethodCallRecorder { /** * < p > Getter for the field < code > lastArgs < / code > . < / p >
 * @ return an array of { @ link java . lang . Object } objects . */
static Object [ ] getLastArgs ( ) { } }

implementation: Object target = lastTarget . get ( ) ; if ( target == null ) { throw new IllegalStateException ( NO_METHOD_CALL_RECORDED_MESSAGE ) ; } return lastArgs . get ( ) ;


signature:
public class FieldNameAndTypeMatcherStrategy { /** * { @ inheritDoc } */
@ Override public boolean matches ( Field field ) { } }

implementation: return fieldName . equals ( field . getName ( ) ) && fieldType . equals ( field . getType ( ) ) ;


signature:
public class FieldNameAndTypeMatcherStrategy { /** * { @ inheritDoc } */
@ Override public void notFound ( Class < ? > type , boolean isInstanceField ) throws FieldNotFoundException { } }

implementation: throw new FieldNotFoundException ( String . format ( "No %s field with name \"%s\" and type \"%s\" could be found in the class hierarchy of %s." , isInstanceField ? "instance" : "static" , fieldName , fieldType . getName ( ) , type . getName ( ) ) ) ;


signature:
public class AwaitilityClassProxy { /** * Await until a specific method invocation returns something . E . g .
 * < pre >
 * await ( ) . until ( callTo ( service ) . getCount ( ) , greaterThan ( 2 ) ) ;
 * < / pre >
 * Here we tell Awaitility to wait until the < code > service . getCount ( ) < / code >
 * method returns a value that is greater than 2.
 * @ param < S > The type of the service .
 * @ param object the object that contains the method of interest .
 * @ return A proxy of the service */
@ SuppressWarnings ( "unchecked" ) public static < S > S to ( S object ) { } }

implementation: return ( S ) MethodCallRecorder . createProxy ( object ) ;


signature:
public class FieldSupplierBuilder { /** * Find a field based on a type . E . g .
 * < p > & nbsp ; < / p >
 * < code >
 * await ( ) . until ( fieldIn ( object ) . ofType ( int . class ) , equalTo ( 2 ) ) ;
 * < / code >
 * < p > & nbsp ; < / p >
 * You can also specify the field more accurately by continuing the statement :
 * E . g .
 * < code >
 * await ( ) . until ( fieldIn ( object ) . ofType ( int . class ) . andWithName ( " fieldName " ) , equalTo ( 2 ) ) ;
 * < / code >
 * < p > & nbsp ; < / p >
 * or
 * < p > & nbsp ; < / p >
 * < code >
 * await ( ) . until ( fieldIn ( object ) . ofType ( int . class ) . andAnnotatedWith ( MyAnnotation . class ) . andWithName ( " fieldName " ) , equalTo ( 2 ) ) ;
 * < / code >
 * @ param fieldType The type of the field .
 * @ param < T > The type of the field
 * @ return The field supplier */
public < T > NameAndAnnotationFieldSupplier < T > ofType ( Class < T > fieldType ) { } }

implementation: this . expectedFieldType = fieldType ; return new NameAndAnnotationFieldSupplier < T > ( ) ;


signature:
public class ConditionFactory { /** * Handle condition evaluation results each time evaluation of a condition occurs . Works only with a Hamcrest matcher - based condition .
 * @ param conditionEvaluationListener the condition evaluation listener
 * @ return the condition factory */
public ConditionFactory conditionEvaluationListener ( ConditionEvaluationListener conditionEvaluationListener ) { } }

implementation: return new ConditionFactory ( alias , timeoutConstraint , pollInterval , pollDelay , catchUncaughtExceptions , exceptionsIgnorer , conditionEvaluationListener , executorLifecycle ) ;


signature:
public class ConditionFactory { /** * Await at most < code > timeout < / code > before throwing a timeout exception .
 * @ param timeout the timeout
 * @ return the condition factory */
public ConditionFactory atMost ( Duration timeout ) { } }

implementation: return new ConditionFactory ( alias , timeoutConstraint . withMaxWaitTime ( timeout ) , pollInterval , pollDelay , catchUncaughtExceptions , exceptionsIgnorer , conditionEvaluationListener , executorLifecycle ) ;


signature:
public class ConditionFactory { /** * Condition has to be evaluated not earlier than < code > timeout < / code > before throwing a timeout exception .
 * @ param timeout the timeout
 * @ return the condition factory */
public ConditionFactory atLeast ( Duration timeout ) { } }

implementation: return new ConditionFactory ( alias , timeoutConstraint . withMinWaitTime ( timeout ) , pollInterval , pollDelay , catchUncaughtExceptions , exceptionsIgnorer , conditionEvaluationListener , executorLifecycle ) ;


signature:
public class ConditionFactory { /** * Specifies the duration window which has to be satisfied during operation execution . In case operation is executed
 * before < code > atLeast < / code > or after < code > atMost < / code > timeout exception is thrown .
 * @ param atLeast lower part of execution window
 * @ param atMost upper part of execution window
 * @ return the condition factory */
public ConditionFactory between ( Duration atLeast , Duration atMost ) { } }

implementation: return atLeast ( atLeast ) . and ( ) . atMost ( atMost ) ;


signature:
public class ConditionFactory { /** * Specifies the duration window which has to be satisfied during operation execution . In case operation is executed
 * before < code > atLeastDuration < / code > or after < code > atMostDuration < / code > timeout exception is thrown .
 * @ param atLeastDuration lower part of execution window
 * @ param atMostDuration upper part of execution window
 * @ return the condition factory */
public ConditionFactory between ( long atLeastDuration , TimeUnit atLeastTimeUnit , long atMostDuration , TimeUnit atMostTimeUnit ) { } }

implementation: return between ( new Duration ( atLeastDuration , atLeastTimeUnit ) , new Duration ( atMostDuration , atMostTimeUnit ) ) ;


signature:
public class ConditionFactory { /** * Await forever until the condition is satisfied . Caution : You can block
 * subsequent tests and the entire build can hang indefinitely , it ' s
 * recommended to always use a timeout .
 * @ return the condition factory */
public ConditionFactory forever ( ) { } }

implementation: return new ConditionFactory ( alias , AtMostWaitConstraint . FOREVER , pollInterval , pollDelay , catchUncaughtExceptions , exceptionsIgnorer , conditionEvaluationListener , executorLifecycle ) ;


signature:
public class ConditionFactory { /** * Specify the polling interval Awaitility will use for this await
 * statement . This means the frequency in which the condition is checked for
 * completion .
 * Note that the poll delay will be automatically set as to the same value
 * as the interval ( if using a { @ link FixedPollInterval } ) unless it ' s specified explicitly using
 * { @ link # pollDelay ( Duration ) } , { @ link # pollDelay ( long , TimeUnit ) } or
 * { @ link org . awaitility . core . ConditionFactory # pollDelay ( org . awaitility . Duration ) } .
 * @ param pollInterval the poll interval
 * @ return the condition factory */
public ConditionFactory pollInterval ( Duration pollInterval ) { } }

implementation: return new ConditionFactory ( alias , timeoutConstraint , new FixedPollInterval ( pollInterval ) , pollDelay , catchUncaughtExceptions , exceptionsIgnorer , conditionEvaluationListener , executorLifecycle ) ;


signature:
public class ConditionFactory { /** * Specify the delay that will be used before Awaitility starts polling for
 * the result the first time . If you don ' t specify a poll delay explicitly
 * it ' ll be the same as the poll interval .
 * @ param delay the delay
 * @ param unit the unit
 * @ return the condition factory */
public ConditionFactory pollDelay ( long delay , TimeUnit unit ) { } }

implementation: return new ConditionFactory ( alias , timeoutConstraint , pollInterval , new Duration ( delay , unit ) , catchUncaughtExceptions , exceptionsIgnorer , conditionEvaluationListener , executorLifecycle ) ;


signature:
public class ConditionFactory { /** * Specify the delay that will be used before Awaitility starts polling for
 * the result the first time . If you don ' t specify a poll delay explicitly
 * it ' ll be the same as the poll interval .
 * @ param pollDelay the poll delay
 * @ return the condition factory */
public ConditionFactory pollDelay ( Duration pollDelay ) { } }

implementation: if ( pollDelay == null ) { throw new IllegalArgumentException ( "pollDelay cannot be null" ) ; } return new ConditionFactory ( alias , timeoutConstraint , pollInterval , pollDelay , catchUncaughtExceptions , exceptionsIgnorer , conditionEvaluationListener , executorLifecycle ) ;


signature:
public class ConditionFactory { /** * Specify the polling interval Awaitility will use for this await
 * statement . This means the frequency in which the condition is checked for
 * completion .
 * < p > & nbsp ; < / p >
 * Note that the poll delay will be automatically set as to the same value
 * as the interval unless it ' s specified explicitly using
 * { @ link # pollDelay ( Duration ) } , { @ link # pollDelay ( long , TimeUnit ) } or
 * { @ link org . awaitility . core . ConditionFactory # pollDelay ( org . awaitility . Duration ) } , or
 * ConditionFactory # andWithPollDelay ( long , TimeUnit ) } . This is the same as creating a { @ link FixedPollInterval } .
 * @ param pollInterval the poll interval
 * @ param unit the unit
 * @ return the condition factory
 * @ see FixedPollInterval */
public ConditionFactory pollInterval ( long pollInterval , TimeUnit unit ) { } }

implementation: PollInterval fixedPollInterval = new FixedPollInterval ( new Duration ( pollInterval , unit ) ) ; return new ConditionFactory ( alias , timeoutConstraint , fixedPollInterval , definePollDelay ( pollDelay , fixedPollInterval ) , catchUncaughtExceptions , exceptionsIgnorer , conditionEvaluationListener , executorLifecycle ) ;


signature:
public class ConditionFactory { /** * Instruct Awaitility to ignore a specific exception and < i > no < / i > subclasses of this exception .
 * Exceptions will be treated as evaluating to < code > false < / code > .
 * This is useful in situations where the evaluated conditions may temporarily throw exceptions .
 * < p > If you want to ignore a subtypes of this exception then use { @ link # ignoreExceptionsInstanceOf ( Class ) } } < / p >
 * @ param exceptionType The exception type to ignore
 * @ return the condition factory */
public ConditionFactory ignoreException ( final Class < ? extends Throwable > exceptionType ) { } }

implementation: if ( exceptionType == null ) { throw new IllegalArgumentException ( "exception cannot be null" ) ; } return new ConditionFactory ( alias , timeoutConstraint , pollInterval , pollDelay , catchUncaughtExceptions , new PredicateExceptionIgnorer ( new Predicate < Throwable > ( ) { public boolean matches ( Throwable e ) { return e . getClass ( ) . equals ( exceptionType ) ; } } ) , conditionEvaluationListener , executorLifecycle ) ;


signature:
public class ConditionFactory { /** * Instruct Awaitility to ignore exceptions that occur during evaluation and matches the supplied Hamcrest matcher .
 * Exceptions will be treated as evaluating to
 * < code > false < / code > . This is useful in situations where the evaluated conditions may temporarily throw exceptions .
 * @ return the condition factory . */
public ConditionFactory ignoreExceptionsMatching ( Matcher < ? super Throwable > matcher ) { } }

implementation: return new ConditionFactory ( alias , timeoutConstraint , pollInterval , pollDelay , catchUncaughtExceptions , new HamcrestExceptionIgnorer ( matcher ) , conditionEvaluationListener , executorLifecycle ) ;


signature:
public class ConditionFactory { /** * Instruct Awaitility to ignore exceptions that occur during evaluation and matches the supplied < code > predicate < / code > .
 * Exceptions will be treated as evaluating to
 * < code > false < / code > . This is useful in situations where the evaluated conditions may temporarily throw exceptions .
 * @ return the condition factory . */
public ConditionFactory ignoreExceptionsMatching ( Predicate < ? super Throwable > predicate ) { } }

implementation: return new ConditionFactory ( alias , timeoutConstraint , pollInterval , pollDelay , catchUncaughtExceptions , new PredicateExceptionIgnorer ( predicate ) , conditionEvaluationListener , executorLifecycle ) ;


signature:
public class ConditionFactory { /** * Don ' t catch uncaught exceptions in other threads . This will < i > not < / i >
 * make the await statement fail if exceptions occur in other threads .
 * @ return the condition factory */
public ConditionFactory dontCatchUncaughtExceptions ( ) { } }

implementation: return new ConditionFactory ( alias , timeoutConstraint , pollInterval , pollDelay , false , exceptionsIgnorer , conditionEvaluationListener , executorLifecycle ) ;


signature:
public class ConditionFactory { /** * Specify the executor service whose threads will be used to evaluate the poll condition in Awaitility .
 * Note that the executor service must be shutdown manually !
 * This is an advanced feature and it should only be used sparingly .
 * @ param executorService The executor service that Awaitility will use when polling condition evaluations
 * @ return the condition factory */
public ConditionFactory pollExecutorService ( ExecutorService executorService ) { } }

implementation: if ( executorService != null && executorService instanceof ScheduledExecutorService ) { throw new IllegalArgumentException ( "Poll executor service cannot be an instance of " + ScheduledExecutorService . class . getName ( ) ) ; } return new ConditionFactory ( alias , timeoutConstraint , pollInterval , pollDelay , false , exceptionsIgnorer , conditionEvaluationListener , ExecutorLifecycle . withoutCleanup ( executorService ) ) ;


signature:
public class ConditionFactory { /** * Specify a thread supplier whose thread will be used to evaluate the poll condition in Awaitility .
 * The supplier will be called only once and the thread it returns will be reused during all condition evaluations .
 * This is an advanced feature and it should only be used sparingly .
 * @ param threadSupplier A supplier of the thread that Awaitility will use when polling
 * @ return the condition factory */
public ConditionFactory pollThread ( final Function < Runnable , Thread > threadSupplier ) { } }

implementation: return new ConditionFactory ( alias , timeoutConstraint , pollInterval , pollDelay , false , exceptionsIgnorer , conditionEvaluationListener , ExecutorLifecycle . withNormalCleanupBehavior ( new Supplier < ExecutorService > ( ) { @ Override public ExecutorService get ( ) { return InternalExecutorServiceFactory . create ( threadSupplier ) ; } } ) ) ;


signature:
public class ConditionFactory { /** * Instructs Awaitility to execute the polling of the condition from the same as the test .
 * This is an advanced feature and you should be careful when combining this with conditions that
 * wait forever ( or a long time ) since Awaitility cannot interrupt the thread when it ' s using the same
 * thread as the test . For safety you should always combine tests using this feature with a test framework specific timeout ,
 * for example in JUnit :
 * < pre >
 * @ Test ( timeout = 2000L )
 * public void myTest ( ) {
 * Awaitility . pollInSameThread ( ) ;
 * await ( ) . forever ( ) . until ( . . . ) ;
 * < / pre >
 * @ return the condition factory */
public ConditionFactory pollInSameThread ( ) { } }

implementation: return new ConditionFactory ( alias , timeoutConstraint , pollInterval , pollDelay , false , exceptionsIgnorer , conditionEvaluationListener , ExecutorLifecycle . withNormalCleanupBehavior ( new Supplier < ExecutorService > ( ) { @ Override public ExecutorService get ( ) { return InternalExecutorServiceFactory . sameThreadExecutorService ( ) ; } } ) ) ;


signature:
public class ConditionFactory { /** * Specify the condition that must be met when waiting for a method call .
 * E . g .
 * < p > & nbsp ; < / p >
 * < pre >
 * await ( ) . untilCall ( to ( orderService ) . size ( ) , is ( greaterThan ( 2 ) ) ) ;
 * < / pre >
 * @ param < T > the generic type
 * @ param proxyMethodReturnValue the return value of the method call
 * @ param matcher The condition that must be met when
 * @ return a T object .
 * @ throws org . awaitility . core . ConditionTimeoutException If condition was not fulfilled within the given time period . */
public < T > T untilCall ( T proxyMethodReturnValue , final Matcher < ? super T > matcher ) { } }

implementation: if ( ! existInCP ( "java.util.ServiceLoader" ) ) { throw new UnsupportedOperationException ( "java.util.ServiceLoader not found in classpath so cannot create condition" ) ; } ClassLoader cl = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( cl == null ) { cl = ClassLoader . getSystemClassLoader ( ) ; } Iterator < ProxyConditionFactory > iterator = java . util . ServiceLoader . load ( ProxyConditionFactory . class , cl ) . iterator ( ) ; if ( ! iterator . hasNext ( ) ) { throw new UnsupportedOperationException ( "There's currently no plugin installed that can handle proxy conditions, please consider adding 'awaitility-proxy' to the classpath. If using Maven you can do:" + "<dependency>\n" + "\t<groupId>org.awaitility</groupId>\n" + "\t<artifactId>awaitility-proxy</artifactId>\n" + "\t<version>${awaitility.version}</version>\n" + "</dependency>\n" ) ; } @ SuppressWarnings ( "unchecked" ) ProxyConditionFactory < T > factory = iterator . next ( ) ; if ( factory == null ) { throw new IllegalArgumentException ( "Internal error: Proxy condition plugin initialization returned null, please report an issue." ) ; } return until ( factory . createProxyCondition ( proxyMethodReturnValue , matcher , generateConditionSettings ( ) ) ) ;


signature:
public class ConditionFactory { /** * Await until a { @ link java . util . concurrent . Callable } supplies a value matching the specified
 * { @ link org . hamcrest . Matcher } . E . g .
 * < p > & nbsp ; < / p >
 * < pre >
 * await ( ) . until ( numberOfPersons ( ) , is ( greaterThan ( 2 ) ) ) ;
 * < / pre >
 * < p > & nbsp ; < / p >
 * where " numberOfPersons ( ) " returns a standard { @ link java . util . concurrent . Callable } :
 * < p > & nbsp ; < / p >
 * < pre >
 * private Callable & lt ; Integer & gt ; numberOfPersons ( ) {
 * return new Callable & lt ; Integer & gt ; ( ) {
 * public Integer call ( ) {
 * return personRepository . size ( ) ;
 * < / pre >
 * < p > & nbsp ; < / p >
 * Using a generic { @ link java . util . concurrent . Callable } as done by using this version of " until "
 * allows you to reuse the " numberOfPersons ( ) " definition in multiple await
 * statements . I . e . you can easily create another await statement ( perhaps
 * in a different test case ) using e . g .
 * < p > & nbsp ; < / p >
 * < pre >
 * await ( ) . until ( numberOfPersons ( ) , is ( equalTo ( 6 ) ) ) ;
 * < / pre >
 * @ param < T > the generic type
 * @ param supplier the supplier that is responsible for getting the value that
 * should be matched .
 * @ param matcher the matcher The hamcrest matcher that checks whether the
 * condition is fulfilled .
 * @ return a T object .
 * @ throws org . awaitility . core . ConditionTimeoutException If condition was not fulfilled within the given time period . */
public < T > T until ( final Callable < T > supplier , final Matcher < ? super T > matcher ) { } }

implementation: return until ( new CallableHamcrestCondition < T > ( supplier , matcher , generateConditionSettings ( ) ) ) ;


signature:
public class ConditionFactory { /** * Wait until the given supplier matches the supplied predicate . For example :
 * < pre >
 * await ( ) . until ( myRepository : : count , cnt - > cnt = = 2 ) ;
 * < / pre >
 * @ param supplier The supplier that returns the object that will be evaluated by the predicate .
 * @ param predicate The predicate that must match
 * @ param < T > the generic type
 * @ since 3.1.1
 * @ return a T object . */
public < T > T until ( final Callable < T > supplier , final Predicate < ? super T > predicate ) { } }

implementation: return until ( supplier , new TypeSafeMatcher < T > ( ) { @ Override protected void describeMismatchSafely ( T item , Description description ) { description . appendText ( "it returned <false> for input of " ) . appendValue ( item ) ; } @ Override public void describeTo ( Description description ) { description . appendText ( "the predicate to return <true>" ) ; } @ Override protected boolean matchesSafely ( T item ) { return predicate . matches ( item ) ; } } ) ;