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

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


signature:
public class AbstractSortedSetMultimap { /** * Returns a collection view of all values associated with a key . If no mappings in the multimap
 * have the provided key , an empty collection is returned .
 * < p > Changes to the returned collection will update the underlying multimap , and vice versa .
 * < p > Because a { @ code SortedSetMultimap } has unique sorted values for a given key , this method
 * returns a { @ link SortedSet } , instead of the { @ link Collection } specified in the { @ link
 * Multimap } interface . */
@ Override public SortedSet < V > get ( @ Nullable K key ) { } }

implementation: return ( SortedSet < V > ) super . get ( key ) ;


signature:
public class AbstractSortedSetMultimap { /** * Removes all values associated with a given key . The returned collection is immutable .
 * < p > Because a { @ code SortedSetMultimap } has unique sorted values for a given key , this method
 * returns a { @ link SortedSet } , instead of the { @ link Collection } specified in the { @ link
 * Multimap } interface . */
@ CanIgnoreReturnValue @ Override public SortedSet < V > removeAll ( @ Nullable Object key ) { } }

implementation: return ( SortedSet < V > ) super . removeAll ( key ) ;


signature:
public class Equivalence { /** * Returns { @ code true } if the given objects are considered equivalent .
 * < p > This method describes an < i > equivalence relation < / i > on object references , meaning that for
 * all references { @ code x } , { @ code y } , and { @ code z } ( any of which may be null ) :
 * < ul >
 * < li > { @ code equivalent ( x , x ) } is true ( < i > reflexive < / i > property )
 * < li > { @ code equivalent ( x , y ) } and { @ code equivalent ( y , x ) } each return the same result
 * ( < i > symmetric < / i > property )
 * < li > If { @ code equivalent ( x , y ) } and { @ code equivalent ( y , z ) } are both true , then { @ code
 * equivalent ( x , z ) } is also true ( < i > transitive < / i > property )
 * < / ul >
 * < p > Note that all calls to { @ code equivalent ( x , y ) } are expected to return the same result as
 * long as neither { @ code x } nor { @ code y } is modified . */
public final boolean equivalent ( @ Nullable T a , @ Nullable T b ) { } }

implementation: if ( a == b ) { return true ; } if ( a == null || b == null ) { return false ; } return doEquivalent ( a , b ) ;


signature:
public class Equivalence { /** * Returns a wrapper of { @ code reference } that implements { @ link Wrapper # equals ( Object )
 * Object . equals ( ) } such that { @ code wrap ( a ) . equals ( wrap ( b ) ) } if and only if { @ code equivalent ( a ,
 * @ since 10.0 */
public final < S extends T > Wrapper < S > wrap ( @ Nullable S reference ) { } }

implementation: return new Wrapper < S > ( this , reference ) ;


signature:
public class ContiguousSet { /** * Returns a { @ code ContiguousSet } containing the same values in the given domain { @ linkplain
 * Range # contains contained } by the range .
 * @ throws IllegalArgumentException if neither range nor the domain has a lower bound , or if
 * neither has an upper bound
 * @ since 13.0 */
public static < C extends Comparable > ContiguousSet < C > create ( Range < C > range , DiscreteDomain < C > domain ) { } }

implementation:
checkNotNull ( range ) ; checkNotNull ( domain ) ; Range < C > effectiveRange = range ; try { if ( ! range . hasLowerBound ( ) ) { effectiveRange = effectiveRange . intersection ( Range . atLeast ( domain . minValue ( ) ) ) ; } if ( ! range . hasUpperBound ( ) ) { effectiveRange = effectiveRange . intersection ( Range . atMost ( domain . maxValue ( ) ) ) ; } } catch ( NoSuchElementException e ) { throw new IllegalArgumentException ( e ) ; } // Per class spec , we are allowed to throw CCE if necessary
boolean empty = effectiveRange . isEmpty ( ) || Range . compareOrThrow ( range . lowerBound . leastValueAbove ( domain ) , range . upperBound . greatestValueBelow ( domain ) ) > 0 ; return empty ? new EmptyContiguousSet < C > ( domain ) : new RegularContiguousSet < C > ( effectiveRange , domain ) ;


signature:
public class ContiguousSet { /** * Returns a nonempty contiguous set containing all { @ code int } values from { @ code lower }
 * ( inclusive ) to { @ code upper } ( inclusive ) . ( These are the same values contained in { @ code
 * Range . closed ( lower , upper ) } . )
 * @ throws IllegalArgumentException if { @ code lower } is greater than { @ code upper }
 * @ since 23.0 */
@ Beta public static ContiguousSet < Integer > closed ( int lower , int upper ) { } }

implementation: return create ( Range . closed ( lower , upper ) , DiscreteDomain . integers ( ) ) ;


signature:
public class ContiguousSet { /** * Returns a nonempty contiguous set containing all { @ code long } values from { @ code lower }
 * ( inclusive ) to { @ code upper } ( inclusive ) . ( These are the same values contained in { @ code
 * Range . closed ( lower , upper ) } . )
 * @ throws IllegalArgumentException if { @ code lower } is greater than { @ code upper }
 * @ since 23.0 */
@ Beta public static ContiguousSet < Long > closed ( long lower , long upper ) { } }

implementation: return create ( Range . closed ( lower , upper ) , DiscreteDomain . longs ( ) ) ;


signature:
public class ImmutableBiMap { /** * Returns an immutable bimap containing a single entry . */
public static < K , V > ImmutableBiMap < K , V > of ( K k1 , V v1 ) { } }

implementation: checkEntryNotNull ( k1 , v1 ) ; return new RegularImmutableBiMap < > ( new Object [ ] { k1 , v1 } , 1 ) ;


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

implementation: checkEntryNotNull ( k1 , v1 ) ; checkEntryNotNull ( k2 , v2 ) ; return new RegularImmutableBiMap < K , V > ( new Object [ ] { k1 , v1 , k2 , v2 } , 2 ) ;


signature:
public class ImmutableBiMap { /** * Returns an immutable bimap containing the given entries . The returned bimap iterates over
 * entries in the same order as the original iterable .
 * @ throws IllegalArgumentException if two keys have the same value or two values have the same
 * key
 * @ throws NullPointerException if any key , value , or entry is null
 * @ since 19.0 */
@ Beta public static < K , V > ImmutableBiMap < K , V > copyOf ( Iterable < ? extends Entry < ? extends K , ? extends V > > entries ) { } }

implementation: int estimatedSize = ( entries instanceof Collection ) ? ( ( Collection < ? > ) entries ) . size ( ) : ImmutableCollection . Builder . DEFAULT_INITIAL_CAPACITY ; return new Builder < K , V > ( estimatedSize ) . putAll ( entries ) . build ( ) ;


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

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


signature:
public class MultimapBuilder { /** * Uses a hash table to map keys to value collections , initialized to expect the specified number
 * of keys .
 * @ throws IllegalArgumentException if { @ code expectedKeys < 0} */
public static MultimapBuilderWithKeys < Object > hashKeys ( final int expectedKeys ) { } }

implementation: checkNonnegative ( expectedKeys , "expectedKeys" ) ; return new MultimapBuilderWithKeys < Object > ( ) { @ Override < K , V > Map < K , Collection < V > > createMap ( ) { return Platform . newHashMapWithExpectedSize ( expectedKeys ) ; } } ;


signature:
public class MultimapBuilder { /** * Uses an hash table to map keys to value collections , initialized to expect the specified number
 * of keys .
 * < p > The collections returned by { @ link Multimap # keySet ( ) } , { @ link Multimap # keys ( ) } , and { @ link
 * Multimap # asMap ( ) } will iterate through the keys in the order that they were first added to the
 * multimap , save that if all values associated with a key are removed and then the key is added
 * back into the multimap , that key will come last in the key iteration order . */
public static MultimapBuilderWithKeys < Object > linkedHashKeys ( final int expectedKeys ) { } }

implementation: checkNonnegative ( expectedKeys , "expectedKeys" ) ; return new MultimapBuilderWithKeys < Object > ( ) { @ Override < K , V > Map < K , Collection < V > > createMap ( ) { return Platform . newLinkedHashMapWithExpectedSize ( expectedKeys ) ; } } ;


signature:
public class MultimapBuilder { /** * Uses a { @ link TreeMap } sorted by the specified comparator to map keys to value collections .
 * < p > The collections returned by { @ link Multimap # keySet ( ) } , { @ link Multimap # keys ( ) } , and { @ link
 * Multimap # asMap ( ) } will iterate through the keys in sorted order .
 * < p > For all multimaps generated by the resulting builder , the { @ link Multimap # keySet ( ) } can be
 * safely cast to a { @ link java . util . SortedSet } , and the { @ link Multimap # asMap ( ) } can safely be
 * cast to a { @ link java . util . SortedMap } .
 * < p > Multimaps generated by the resulting builder will not be serializable if { @ code comparator }
 * is not serializable . */
public static < K0 > MultimapBuilderWithKeys < K0 > treeKeys ( final Comparator < K0 > comparator ) { } }

implementation: checkNotNull ( comparator ) ; return new MultimapBuilderWithKeys < K0 > ( ) { @ Override < K extends K0 , V > Map < K , Collection < V > > createMap ( ) { return new TreeMap < > ( comparator ) ; } } ;


signature:
public class MultimapBuilder { /** * Uses an { @ link EnumMap } to map keys to value collections .
 * @ since 16.0 */
public static < K0 extends Enum < K0 > > MultimapBuilderWithKeys < K0 > enumKeys ( final Class < K0 > keyClass ) { } }

implementation:
checkNotNull ( keyClass ) ; return new MultimapBuilderWithKeys < K0 > ( ) { @ SuppressWarnings ( "unchecked" ) @ Override < K extends K0 , V > Map < K , Collection < V > > createMap ( ) { // K must actually be K0 , since enums are effectively final
// ( their subclasses are inaccessible )
return ( Map < K , Collection < V > > ) new EnumMap < K0 , Collection < V > > ( keyClass ) ; } } ;


signature:
public class MultimapBuilder { /** * Returns a { @ code Multimap } with the specified implementation , initialized with the entries of
 * { @ code multimap } . */
public < K extends K0 , V extends V0 > Multimap < K , V > build ( Multimap < ? extends K , ? extends V > multimap ) { } }

implementation: Multimap < K , V > result = build ( ) ; result . putAll ( multimap ) ; return result ;


signature:
public class Functions { /** * implementation is " fully variant " ; E has become a " pass - through " type */
@ SuppressWarnings ( "unchecked" ) public static < E > Function < E , E > identity ( ) { } }

implementation: return ( Function < E , E > ) IdentityFunction . INSTANCE ;


signature:
public class Functions { /** * Returns the composition of two functions . For { @ code f : A - > B } and { @ code g : B - > C } , composition
 * is defined as the function h such that { @ code h ( a ) = = g ( f ( a ) ) } for each { @ code a } .
 * < p > < b > Java 8 users : < / b > use { @ code g . compose ( f ) } or ( probably clearer ) { @ code f . andThen ( g ) }
 * instead .
 * @ param g the second function to apply
 * @ param f the first function to apply
 * @ return the composition of { @ code f } and { @ code g }
 * @ see < a href = " / / en . wikipedia . org / wiki / Function _ composition " > function composition < / a > */
public static < A , B , C > Function < A , C > compose ( Function < B , C > g , Function < A , ? extends B > f ) { } }

implementation: return new FunctionComposition < > ( g , f ) ;


signature:
public class Functions { /** * Creates a function that returns the same boolean output as the given predicate for all inputs .
 * < p > The returned function is < i > consistent with equals < / i > ( as documented at { @ link
 * Function # apply } ) if and only if { @ code predicate } is itself consistent with equals .
 * < p > < b > Java 8 users : < / b > use the method reference { @ code predicate : : test } instead . */
public static < T > Function < T , Boolean > forPredicate ( Predicate < T > predicate ) { } }

implementation: return new PredicateFunction < T > ( predicate ) ;


signature:
public class Functions { /** * Returns a function that ignores its input and always returns { @ code value } .
 * < p > < b > Java 8 users : < / b > use the lambda expression { @ code o - > value } instead .
 * @ param value the constant value for the function to return
 * @ return a function that always returns { @ code value } */
public static < E > Function < Object , E > constant ( @ NullableDecl E value ) { } }

implementation: return new ConstantFunction < E > ( value ) ;


signature:
public class Functions { /** * Returns a function that ignores its input and returns the result of { @ code supplier . get ( ) } .
 * < p > < b > Java 8 users : < / b > use the lambda expression { @ code o - > supplier . get ( ) } instead .
 * @ since 10.0 */
public static < T > Function < Object , T > forSupplier ( Supplier < T > supplier ) { } }

implementation: return new SupplierFunction < T > ( supplier ) ;


signature:
public class LocalCache { /** * Singleton placeholder that indicates a value is being loaded . */
@ SuppressWarnings ( "unchecked" ) // impl never uses a parameter or returns any non - null value
static < K , V > ValueReference < K , V > unset ( ) { } }

implementation: return ( ValueReference < K , V > ) UNSET ;


signature:
public class LocalCache { /** * Guarded By Segment . this */
@ VisibleForTesting ReferenceEntry < K , V > copyEntry ( ReferenceEntry < K , V > original , ReferenceEntry < K , V > newNext ) { } }

implementation: int hash = original . getHash ( ) ; return segmentFor ( hash ) . copyEntry ( original , newNext ) ;


signature:
public class LocalCache { /** * This method is a convenience for testing . Code should call { @ link Segment # getLiveValue }
 * instead . */
@ VisibleForTesting boolean isLive ( ReferenceEntry < K , V > entry , long now ) { } }

implementation: return segmentFor ( entry . getHash ( ) ) . getLiveValue ( entry , now ) != null ;


signature:
public class LocalCache { /** * Gets the value from an entry . Returns null if the entry is invalid , partially - collected ,
 * loading , or expired . Unlike { @ link Segment # getLiveValue } this method does not attempt to
 * cleanup stale entries . As such it should only be called outside of a segment context , such as
 * during iteration . */
@ Nullable V getLiveValue ( ReferenceEntry < K , V > entry , long now ) { } }

implementation: if ( entry . getKey ( ) == null ) { return null ; } V value = entry . getValueReference ( ) . get ( ) ; if ( value == null ) { return null ; } if ( isExpired ( entry , now ) ) { return null ; } return value ;


signature:
public class LocalCache { /** * Returns true if the entry has expired . */
boolean isExpired ( ReferenceEntry < K , V > entry , long now ) { } }

implementation: checkNotNull ( entry ) ; if ( expiresAfterAccess ( ) && ( now - entry . getAccessTime ( ) >= expireAfterAccessNanos ) ) { return true ; } if ( expiresAfterWrite ( ) && ( now - entry . getWriteTime ( ) >= expireAfterWriteNanos ) ) { return true ; } return false ;


signature:
public class LocalCache { /** * Guarded By Segment . this */
static < K , V > void connectAccessOrder ( ReferenceEntry < K , V > previous , ReferenceEntry < K , V > next ) { } }

implementation: previous . setNextInAccessQueue ( next ) ; next . setPreviousInAccessQueue ( previous ) ;


signature:
public class LocalCache { /** * Guarded By Segment . this */
static < K , V > void nullifyAccessOrder ( ReferenceEntry < K , V > nulled ) { } }

implementation: ReferenceEntry < K , V > nullEntry = nullEntry ( ) ; nulled . setNextInAccessQueue ( nullEntry ) ; nulled . setPreviousInAccessQueue ( nullEntry ) ;


signature:
public class LocalCache { /** * Guarded By Segment . this */
static < K , V > void connectWriteOrder ( ReferenceEntry < K , V > previous , ReferenceEntry < K , V > next ) { } }

implementation: previous . setNextInWriteQueue ( next ) ; next . setPreviousInWriteQueue ( previous ) ;


signature:
public class LocalCache { /** * Guarded By Segment . this */
static < K , V > void nullifyWriteOrder ( ReferenceEntry < K , V > nulled ) { } }

implementation: ReferenceEntry < K , V > nullEntry = nullEntry ( ) ; nulled . setNextInWriteQueue ( nullEntry ) ; nulled . setPreviousInWriteQueue ( nullEntry ) ;


signature:
public class LocalCache { /** * Notifies listeners that an entry has been automatically removed due to expiration , eviction , or
 * eligibility for garbage collection . This should be called every time expireEntries or
 * evictEntry is called ( once the lock is released ) . */
void processPendingNotifications ( ) { } }

implementation: RemovalNotification < K , V > notification ; while ( ( notification = removalNotificationQueue . poll ( ) ) != null ) { try { removalListener . onRemoval ( notification ) ; } catch ( Throwable e ) { logger . log ( Level . WARNING , "Exception thrown by removal listener" , e ) ; } }


signature:
public class LocalCache { /** * ConcurrentMap methods */
@ Override public boolean isEmpty ( ) { } }

implementation:
/* * Sum per - segment modCounts to avoid mis - reporting when elements are concurrently added and
 * removed in one segment while checking another , in which case the table was never actually
 * empty at any point . ( The sum ensures accuracy up through at least 1 < < 31 per - segment
 * modifications before recheck . ) Method containsValue ( ) uses similar constructions for
 * stability checks . */
long sum = 0L ; Segment < K , V > [ ] segments = this . segments ; for ( int i = 0 ; i < segments . length ; ++ i ) { if ( segments [ i ] . count != 0 ) { return false ; } sum += segments [ i ] . modCount ; } if ( sum != 0L ) { // recheck unless no modifications
for ( int i = 0 ; i < segments . length ; ++ i ) { if ( segments [ i ] . count != 0 ) { return false ; } sum -= segments [ i ] . modCount ; } if ( sum != 0L ) { return false ; } } return true ;


signature:
public class LocalCache { /** * Returns the internal entry for the specified key . The entry may be loading , expired , or
 * partially collected . */
ReferenceEntry < K , V > getEntry ( @ Nullable Object key ) { } }

implementation:
// does not impact recency ordering
if ( key == null ) { return null ; } int hash = hash ( key ) ; return segmentFor ( hash ) . getEntry ( key , hash ) ;


signature:
public class CacheStats { /** * Returns a new { @ code CacheStats } representing the difference between this { @ code CacheStats }
 * and { @ code other } . Negative values , which aren ' t supported by { @ code CacheStats } will be
 * rounded up to zero . */
public CacheStats minus ( CacheStats other ) { } }

implementation: return new CacheStats ( Math . max ( 0 , hitCount - other . hitCount ) , Math . max ( 0 , missCount - other . missCount ) , Math . max ( 0 , loadSuccessCount - other . loadSuccessCount ) , Math . max ( 0 , loadExceptionCount - other . loadExceptionCount ) , Math . max ( 0 , totalLoadTime - other . totalLoadTime ) , Math . max ( 0 , evictionCount - other . evictionCount ) ) ;


signature:
public class CacheStats { /** * Returns a new { @ code CacheStats } representing the sum of this { @ code CacheStats } and { @ code
 * other } .
 * @ since 11.0 */
public CacheStats plus ( CacheStats other ) { } }

implementation: return new CacheStats ( hitCount + other . hitCount , missCount + other . missCount , loadSuccessCount + other . loadSuccessCount , loadExceptionCount + other . loadExceptionCount , totalLoadTime + other . totalLoadTime , evictionCount + other . evictionCount ) ;


signature:
public class ImmutableMultiset { /** * Returns an immutable multiset containing the given elements , in the " grouped iteration order "
 * described in the class documentation .
 * @ throws NullPointerException if any of { @ code elements } is null */
public static < E > ImmutableMultiset < E > copyOf ( Iterable < ? extends E > elements ) { } }

implementation:
if ( elements instanceof ImmutableMultiset ) { @ SuppressWarnings ( "unchecked" ) // all supported methods are covariant
ImmutableMultiset < E > result = ( ImmutableMultiset < E > ) elements ; if ( ! result . isPartialView ( ) ) { return result ; } } ImmutableMultiset . Builder < E > builder = new ImmutableMultiset . Builder < E > ( Multisets . inferDistinctElements ( elements ) ) ; builder . addAll ( elements ) ; return builder . build ( ) ;


signature:
public class ImmutableMultiset { /** * Returns an immutable multiset containing the given elements , in the " grouped iteration order "
 * described in the class documentation .
 * @ throws NullPointerException if any of { @ code elements } is null */
public static < E > ImmutableMultiset < E > copyOf ( Iterator < ? extends E > elements ) { } }

implementation: return new ImmutableMultiset . Builder < E > ( ) . addAll ( elements ) . build ( ) ;


signature:
public class RateLimiter { /** * Updates the stable rate of this { @ code RateLimiter } , that is , the { @ code permitsPerSecond }
 * argument provided in the factory method that constructed the { @ code RateLimiter } . Currently
 * throttled threads will < b > not < / b > be awakened as a result of this invocation , thus they do not
 * observe the new rate ; only subsequent requests will .
 * < p > Note though that , since each request repays ( by waiting , if necessary ) the cost of the
 * < i > previous < / i > request , this means that the very next request after an invocation to { @ code
 * setRate } will not be affected by the new rate ; it will pay the cost of the previous request ,
 * which is in terms of the previous rate .
 * < p > The behavior of the { @ code RateLimiter } is not modified in any other way , e . g . if the { @ code
 * RateLimiter } was configured with a warmup period of 20 seconds , it still has a warmup period of
 * 20 seconds after this method invocation .
 * @ param permitsPerSecond the new stable rate of this { @ code RateLimiter }
 * @ throws IllegalArgumentException if { @ code permitsPerSecond } is negative or zero */
public final void setRate ( double permitsPerSecond ) { } }

implementation: checkArgument ( permitsPerSecond > 0.0 && ! Double . isNaN ( permitsPerSecond ) , "rate must be positive" ) ; synchronized ( mutex ( ) ) { doSetRate ( permitsPerSecond , stopwatch . readMicros ( ) ) ; }


signature:
public class RateLimiter { /** * Acquires the given number of permits from this { @ code RateLimiter } , blocking until the request
 * can be granted . Tells the amount of time slept , if any .
 * @ param permits the number of permits to acquire
 * @ return time spent sleeping to enforce rate , in seconds ; 0.0 if not rate - limited
 * @ throws IllegalArgumentException if the requested number of permits is negative or zero
 * @ since 16.0 ( present in 13.0 with { @ code void } return type } ) */
@ CanIgnoreReturnValue public double acquire ( int permits ) { } }

implementation: long microsToWait = reserve ( permits ) ; stopwatch . sleepMicrosUninterruptibly ( microsToWait ) ; return 1.0 * microsToWait / SECONDS . toMicros ( 1L ) ;


signature:
public class RateLimiter { /** * Acquires the given number of permits from this { @ code RateLimiter } if it can be obtained
 * without exceeding the specified { @ code timeout } , or returns { @ code false } immediately ( without
 * waiting ) if the permits would not have been granted before the timeout expired .
 * @ param permits the number of permits to acquire
 * @ param timeout the maximum time to wait for the permits . Negative values are treated as zero .
 * @ param unit the time unit of the timeout argument
 * @ return { @ code true } if the permits were acquired , { @ code false } otherwise
 * @ throws IllegalArgumentException if the requested number of permits is negative or zero */
public boolean tryAcquire ( int permits , long timeout , TimeUnit unit ) { } }

implementation: long timeoutMicros = max ( unit . toMicros ( timeout ) , 0 ) ; checkPermits ( permits ) ; long microsToWait ; synchronized ( mutex ( ) ) { long nowMicros = stopwatch . readMicros ( ) ; if ( ! canAcquire ( nowMicros , timeoutMicros ) ) { return false ; } else { microsToWait = reserveAndGetWaitLength ( permits , nowMicros ) ; } } stopwatch . sleepMicrosUninterruptibly ( microsToWait ) ; return true ;


signature:
public class RateLimiter { /** * Reserves next ticket and returns the wait time that the caller must wait for .
 * @ return the required wait time , never negative */
final long reserveAndGetWaitLength ( int permits , long nowMicros ) { } }

implementation: long momentAvailable = reserveEarliestAvailable ( permits , nowMicros ) ; return max ( momentAvailable - nowMicros , 0 ) ;


signature:
public class LocalCache { /** * This method is a convenience for testing . Code should call { @ link Segment # newEntry } directly . */
@ VisibleForTesting ReferenceEntry < K , V > newEntry ( K key , int hash , @ NullableDecl ReferenceEntry < K , V > next ) { } }

implementation: Segment < K , V > segment = segmentFor ( hash ) ; segment . lock ( ) ; try { return segment . newEntry ( key , hash , next ) ; } finally { segment . unlock ( ) ; }


signature:
public class LocalCache { /** * Returns the result of calling { @ link CacheLoader # loadAll } , or null if { @ code loader } doesn ' t
 * implement { @ code loadAll } . */
@ NullableDecl Map < K , V > loadAll ( Set < ? extends K > keys , CacheLoader < ? super K , V > loader ) throws ExecutionException { } }

implementation:
checkNotNull ( loader ) ; checkNotNull ( keys ) ; Stopwatch stopwatch = Stopwatch . createStarted ( ) ; Map < K , V > result ; boolean success = false ; try { @ SuppressWarnings ( "unchecked" ) // safe since all keys extend K
Map < K , V > map = ( Map < K , V > ) loader . loadAll ( keys ) ; result = map ; success = true ; } catch ( UnsupportedLoadingOperationException e ) { success = true ; throw e ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw new ExecutionException ( e ) ; } catch ( RuntimeException e ) { throw new UncheckedExecutionException ( e ) ; } catch ( Exception e ) { throw new ExecutionException ( e ) ; } catch ( Error e ) { throw new ExecutionError ( e ) ; } finally { if ( ! success ) { globalStatsCounter . recordLoadException ( stopwatch . elapsed ( NANOSECONDS ) ) ; } } if ( result == null ) { globalStatsCounter . recordLoadException ( stopwatch . elapsed ( NANOSECONDS ) ) ; throw new InvalidCacheLoadException ( loader + " returned null map from loadAll" ) ; } stopwatch . stop ( ) ; // TODO ( fry ) : batch by segment
boolean nullsPresent = false ; for ( Entry < K , V > entry : result . entrySet ( ) ) { K key = entry . getKey ( ) ; V value = entry . getValue ( ) ; if ( key == null || value == null ) { // delay failure until non - null entries are stored
nullsPresent = true ; } else { put ( key , value ) ; } } if ( nullsPresent ) { globalStatsCounter . recordLoadException ( stopwatch . elapsed ( NANOSECONDS ) ) ; throw new InvalidCacheLoadException ( loader + " returned null keys or values from loadAll" ) ; } // TODO ( fry ) : record count of loaded entries
globalStatsCounter . recordLoadSuccess ( stopwatch . elapsed ( NANOSECONDS ) ) ; return result ;


signature:
public class UnicodeEscaper { /** * Scans a sub - sequence of characters from a given { @ link CharSequence } , returning the index of
 * the next character that requires escaping .
 * < p > < b > Note : < / b > When implementing an escaper , it is a good idea to override this method for
 * efficiency . The base class implementation determines successive Unicode code points and invokes
 * { @ link # escape ( int ) } for each of them . If the semantics of your escaper are such that code
 * points in the supplementary range are either all escaped or all unescaped , this method can be
 * implemented more efficiently using { @ link CharSequence # charAt ( int ) } .
 * < p > Note however that if your escaper does not escape characters in the supplementary range , you
 * should either continue to validate the correctness of any surrogate characters encountered or
 * provide a clear warning to users that your escaper does not validate its input .
 * < p > See { @ link com . google . common . net . PercentEscaper } for an example .
 * @ param csq a sequence of characters
 * @ param start the index of the first character to be scanned
 * @ param end the index immediately after the last character to be scanned
 * @ throws IllegalArgumentException if the scanned sub - sequence of { @ code csq } contains invalid
 * surrogate pairs */
protected int nextEscapeIndex ( CharSequence csq , int start , int end ) { } }

implementation: int index = start ; while ( index < end ) { int cp = codePointAt ( csq , index , end ) ; if ( cp < 0 || escape ( cp ) != null ) { break ; } index += Character . isSupplementaryCodePoint ( cp ) ? 2 : 1 ; } return index ;


signature:
public class UnicodeEscaper { /** * Returns the Unicode code point of the character at the given index .
 * < p > Unlike { @ link Character # codePointAt ( CharSequence , int ) } or { @ link String # codePointAt ( int ) }
 * this method will never fail silently when encountering an invalid surrogate pair .
 * < p > The behaviour of this method is as follows :
 * < ol >
 * < li > If { @ code index > = end } , { @ link IndexOutOfBoundsException } is thrown .
 * < li > < b > If the character at the specified index is not a surrogate , it is returned . < / b >
 * < li > If the first character was a high surrogate value , then an attempt is made to read the
 * next character .
 * < ol >
 * < li > < b > If the end of the sequence was reached , the negated value of the trailing high
 * surrogate is returned . < / b >
 * < li > < b > If the next character was a valid low surrogate , the code point value of the
 * high / low surrogate pair is returned . < / b >
 * < li > If the next character was not a low surrogate value , then { @ link
 * IllegalArgumentException } is thrown .
 * < / ol >
 * < li > If the first character was a low surrogate value , { @ link IllegalArgumentException } is
 * thrown .
 * < / ol >
 * @ param seq the sequence of characters from which to decode the code point
 * @ param index the index of the first character to decode
 * @ param end the index beyond the last valid character to decode
 * @ return the Unicode code point for the given index or the negated value of the trailing high
 * surrogate character at the end of the sequence */
protected static int codePointAt ( CharSequence seq , int index , int end ) { } }

implementation:
checkNotNull ( seq ) ; if ( index < end ) { char c1 = seq . charAt ( index ++ ) ; if ( c1 < Character . MIN_HIGH_SURROGATE || c1 > Character . MAX_LOW_SURROGATE ) { // Fast path ( first test is probably all we need to do )
return c1 ; } else if ( c1 <= Character . MAX_HIGH_SURROGATE ) { // If the high surrogate was the last character , return its inverse
if ( index == end ) { return - c1 ; } // Otherwise look for the low surrogate following it
char c2 = seq . charAt ( index ) ; if ( Character . isLowSurrogate ( c2 ) ) { return Character . toCodePoint ( c1 , c2 ) ; } throw new IllegalArgumentException ( "Expected low surrogate but got char '" + c2 + "' with value " + ( int ) c2 + " at index " + index + " in '" + seq + "'" ) ; } else { throw new IllegalArgumentException ( "Unexpected low surrogate character '" + c1 + "' with value " + ( int ) c1 + " at index " + ( index - 1 ) + " in '" + seq + "'" ) ; } } throw new IndexOutOfBoundsException ( "Index exceeds specified range" ) ;


signature:
public class Ints { /** * Returns the { @ code int } nearest in value to { @ code value } .
 * @ param value any { @ code long } value
 * @ return the same value cast to { @ code int } if it is in the range of the { @ code int } type ,
 * { @ link Integer # MAX _ VALUE } if it is too large , or { @ link Integer # MIN _ VALUE } if it is too
 * small */
public static int saturatedCast ( long value ) { } }

implementation: if ( value > Integer . MAX_VALUE ) { return Integer . MAX_VALUE ; } if ( value < Integer . MIN_VALUE ) { return Integer . MIN_VALUE ; } return ( int ) value ;


signature:
public class Ints { /** * Returns an array containing each value of { @ code collection } , converted to a { @ code int } value
 * in the manner of { @ link Number # intValue } .
 * < p > Elements are copied from the argument collection as if by { @ code collection . toArray ( ) } .
 * Calling this method is as thread - safe as calling that method .
 * @ param collection a collection of { @ code Number } instances
 * @ return an array containing the same values as { @ code collection } , in the same order , converted
 * to primitives
 * @ throws NullPointerException if { @ code collection } or any of its elements is null
 * @ since 1.0 ( parameter was { @ code Collection < Integer > } before 12.0) */
public static int [ ] toArray ( Collection < ? extends Number > collection ) { } }

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


signature:
public class Ints { /** * Returns a fixed - size list backed by the specified array , similar to { @ link
 * Arrays # asList ( Object [ ] ) } . The list supports { @ link List # set ( int , Object ) } , but any attempt to
 * set a value to { @ code null } will result in a { @ link NullPointerException } .
 * < p > The returned list maintains the values , but not the identities , of { @ code Integer } objects
 * written to or read from it . For example , whether { @ code list . get ( 0 ) = = list . get ( 0 ) } is true for
 * the returned list is unspecified .
 * < p > < b > Note : < / b > when possible , you should represent your data as an { @ link ImmutableIntArray }
 * instead , which has an { @ link ImmutableIntArray # asList asList } view .
 * @ param backingArray the array to back the list
 * @ return a list view of the array */
public static List < Integer > asList ( int ... backingArray ) { } }

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


signature:
public class Traverser { /** * Creates a new traverser for the given general { @ code graph } .
 * < p > Traversers created using this method are guaranteed to visit each node reachable from the
 * start node ( s ) at most once .
 * < p > If you know that no node in { @ code graph } is reachable by more than one path from the start
 * node ( s ) , consider using { @ link # forTree ( SuccessorsFunction ) } instead .
 * < p > < b > Performance notes < / b >
 * < ul >
 * < li > Traversals require < i > O ( n ) < / i > time ( where < i > n < / i > is the number of nodes reachable from
 * the start node ) , assuming that the node objects have < i > O ( 1 ) < / i > { @ code equals ( ) } and
 * { @ code hashCode ( ) } implementations . ( See the < a
 * href = " https : / / github . com / google / guava / wiki / GraphsExplained # elements - must - be - useable - as - map - keys " >
 * notes on element objects < / a > for more information . )
 * < li > While traversing , the traverser will use < i > O ( n ) < / i > space ( where < i > n < / i > is the number
 * of nodes that have thus far been visited ) , plus < i > O ( H ) < / i > space ( where < i > H < / i > is the
 * number of nodes that have been seen but not yet visited , that is , the " horizon " ) .
 * < / ul >
 * @ param graph { @ link SuccessorsFunction } representing a general graph that may have cycles . */
public static < N > Traverser < N > forGraph ( SuccessorsFunction < N > graph ) { } }

implementation: checkNotNull ( graph ) ; return new GraphTraverser < > ( graph ) ;


signature:
public class Traverser { /** * Creates a new traverser for a directed acyclic graph that has at most one path from the start
 * node ( s ) to any node reachable from the start node ( s ) , and has no paths from any start node to
 * any other start node , such as a tree or forest .
 * < p > { @ code forTree ( ) } is especially useful ( versus { @ code forGraph ( ) } ) in cases where the data
 * structure being traversed is , in addition to being a tree / forest , also defined < a
 * href = " https : / / github . com / google / guava / wiki / GraphsExplained # non - recursiveness " > recursively < / a > .
 * This is because the { @ code forTree ( ) } - based implementations don ' t keep track of visited nodes ,
 * and therefore don ' t need to call ` equals ( ) ` or ` hashCode ( ) ` on the node objects ; this saves
 * both time and space versus traversing the same graph using { @ code forGraph ( ) } .
 * < p > Providing a graph to be traversed for which there is more than one path from the start
 * node ( s ) to any node may lead to :
 * < ul >
 * < li > Traversal not terminating ( if the graph has cycles )
 * < li > Nodes being visited multiple times ( if multiple paths exist from any start node to any
 * node reachable from any start node )
 * < / ul >
 * < p > < b > Performance notes < / b >
 * < ul >
 * < li > Traversals require < i > O ( n ) < / i > time ( where < i > n < / i > is the number of nodes reachable from
 * the start node ) .
 * < li > While traversing , the traverser will use < i > O ( H ) < / i > space ( where < i > H < / i > is the number
 * of nodes that have been seen but not yet visited , that is , the " horizon " ) .
 * < / ul >
 * < p > < b > Examples < / b > ( all edges are directed facing downwards )
 * < p > The graph below would be valid input with start nodes of { @ code a , f , c } . However , if { @ code
 * b } were < i > also < / i > a start node , then there would be multiple paths to reach { @ code e } and
 * { @ code h } .
 * < pre > { @ code
 * a b c
 * d e f g
 * } < / pre >
 * < p > The graph below would be a valid input with start nodes of { @ code a , f } . However , if { @ code
 * b } were a start node , there would be multiple paths to { @ code f } .
 * < pre > { @ code
 * a b
 * c d e
 * } < / pre >
 * < p > < b > Note on binary trees < / b >
 * < p > This method can be used to traverse over a binary tree . Given methods { @ code
 * leftChild ( node ) } and { @ code rightChild ( node ) } , this method can be called as
 * < pre > { @ code
 * Traverser . forTree ( node - > ImmutableList . of ( leftChild ( node ) , rightChild ( node ) ) ) ;
 * } < / pre >
 * @ param tree { @ link SuccessorsFunction } representing a directed acyclic graph that has at most
 * one path between any two nodes */
public static < N > Traverser < N > forTree ( SuccessorsFunction < N > tree ) { } }

implementation: checkNotNull ( tree ) ; if ( tree instanceof BaseGraph ) { checkArgument ( ( ( BaseGraph < ? > ) tree ) . isDirected ( ) , "Undirected graphs can never be trees." ) ; } if ( tree instanceof Network ) { checkArgument ( ( ( Network < ? , ? > ) tree ) . isDirected ( ) , "Undirected networks can never be trees." ) ; } return new TreeTraverser < > ( tree ) ;


signature:
public class TrustedListenableFutureTask { /** * Creates a { @ code ListenableFutureTask } that will upon running , execute the given { @ code
 * Runnable } , and arrange that { @ code get } will return the given result on successful completion .
 * @ param runnable the runnable task
 * @ param result the result to return on successful completion . If you don ' t need a particular
 * result , consider using constructions of the form : { @ code ListenableFuture < ? > f =
 * ListenableFutureTask . create ( runnable , null ) } */
static < V > TrustedListenableFutureTask < V > create ( Runnable runnable , @ Nullable V result ) { } }

implementation: return new TrustedListenableFutureTask < V > ( Executors . callable ( runnable , result ) ) ;


signature:
public class ImmutableRangeSet { /** * Returns a { @ code Collector } that accumulates the input elements into a new { @ code
 * ImmutableRangeSet } . As in { @ link Builder } , overlapping ranges are not permitted and adjacent
 * ranges will be merged .
 * @ since 23.1 */
public static < E extends Comparable < ? super E > > Collector < Range < E > , ? , ImmutableRangeSet < E > > toImmutableRangeSet ( ) { } }

implementation: return CollectCollectors . toImmutableRangeSet ( ) ;


signature:
public class HashBiMap { /** * Equivalent to { @ code Arrays . copyOf ( array , newSize ) } , save that the new elements are ABSENT . */
private static int [ ] expandAndFillWithAbsent ( int [ ] array , int newSize ) { } }

implementation: int oldSize = array . length ; int [ ] result = Arrays . copyOf ( array , newSize ) ; Arrays . fill ( result , oldSize , newSize , ABSENT ) ; return result ;


signature:
public class HashBiMap { /** * Ensures that all of the internal structures in the HashBiMap are ready for this many elements . */
private void ensureCapacity ( int minCapacity ) { } }

implementation: if ( nextInBucketKToV . length < minCapacity ) { int oldCapacity = nextInBucketKToV . length ; int newCapacity = ImmutableCollection . Builder . expandedCapacity ( oldCapacity , minCapacity ) ; keys = Arrays . copyOf ( keys , newCapacity ) ; values = Arrays . copyOf ( values , newCapacity ) ; nextInBucketKToV = expandAndFillWithAbsent ( nextInBucketKToV , newCapacity ) ; nextInBucketVToK = expandAndFillWithAbsent ( nextInBucketVToK , newCapacity ) ; prevInInsertionOrder = expandAndFillWithAbsent ( prevInInsertionOrder , newCapacity ) ; nextInInsertionOrder = expandAndFillWithAbsent ( nextInInsertionOrder , newCapacity ) ; } if ( hashTableKToV . length < minCapacity ) { int newTableSize = Hashing . closedTableSize ( minCapacity , 1.0 ) ; hashTableKToV = createFilledWithAbsent ( newTableSize ) ; hashTableVToK = createFilledWithAbsent ( newTableSize ) ; for ( int entryToRehash = 0 ; entryToRehash < size ; entryToRehash ++ ) { int keyHash = Hashing . smearedHash ( keys [ entryToRehash ] ) ; int keyBucket = bucket ( keyHash ) ; nextInBucketKToV [ entryToRehash ] = hashTableKToV [ keyBucket ] ; hashTableKToV [ keyBucket ] = entryToRehash ; int valueHash = Hashing . smearedHash ( values [ entryToRehash ] ) ; int valueBucket = bucket ( valueHash ) ; nextInBucketVToK [ entryToRehash ] = hashTableVToK [ valueBucket ] ; hashTableVToK [ valueBucket ] = entryToRehash ; } }


signature:
public class HashBiMap { /** * Given a key and its hash , returns the index of the entry in the tables , or ABSENT if not found . */
int findEntryByKey ( @ NullableDecl Object key , int keyHash ) { } }

implementation: return findEntry ( key , keyHash , hashTableKToV , nextInBucketKToV , keys ) ;


signature:
public class HashBiMap { /** * Given a value and its hash , returns the index of the entry in the tables , or ABSENT if not
 * found . */
int findEntryByValue ( @ NullableDecl Object value , int valueHash ) { } }

implementation: return findEntry ( value , valueHash , hashTableVToK , nextInBucketVToK , values ) ;


signature:
public class HashBiMap { /** * Updates the pointers of the insertion order linked list so that { @ code next } follows { @ code
 * prev } . { @ code ENDPOINT } represents either the first or last entry in the entire map ( as
 * appropriate ) . */
private void setSucceeds ( int prev , int next ) { } }

implementation: if ( prev == ENDPOINT ) { firstInInsertionOrder = next ; } else { nextInInsertionOrder [ prev ] = next ; } if ( next == ENDPOINT ) { lastInInsertionOrder = prev ; } else { prevInInsertionOrder [ next ] = prev ; }


signature:
public class HashBiMap { /** * Updates the K - to - V hash table to include the entry at the specified index , which is assumed to
 * have not yet been added . */
private void insertIntoTableKToV ( int entry , int keyHash ) { } }

implementation: checkArgument ( entry != ABSENT ) ; int keyBucket = bucket ( keyHash ) ; nextInBucketKToV [ entry ] = hashTableKToV [ keyBucket ] ; hashTableKToV [ keyBucket ] = entry ;


signature:
public class HashBiMap { /** * Updates the V - to - K hash table to include the entry at the specified index , which is assumed to
 * have not yet been added . */
private void insertIntoTableVToK ( int entry , int valueHash ) { } }

implementation: checkArgument ( entry != ABSENT ) ; int valueBucket = bucket ( valueHash ) ; nextInBucketVToK [ entry ] = hashTableVToK [ valueBucket ] ; hashTableVToK [ valueBucket ] = entry ;


signature:
public class HashBiMap { /** * Updates the K - to - V hash table to remove the entry at the specified index , which is assumed to
 * be present . Does not update any other data structures . */
private void deleteFromTableKToV ( int entry , int keyHash ) { } }

implementation: checkArgument ( entry != ABSENT ) ; int keyBucket = bucket ( keyHash ) ; if ( hashTableKToV [ keyBucket ] == entry ) { hashTableKToV [ keyBucket ] = nextInBucketKToV [ entry ] ; nextInBucketKToV [ entry ] = ABSENT ; return ; } int prevInBucket = hashTableKToV [ keyBucket ] ; for ( int entryInBucket = nextInBucketKToV [ prevInBucket ] ; entryInBucket != ABSENT ; entryInBucket = nextInBucketKToV [ entryInBucket ] ) { if ( entryInBucket == entry ) { nextInBucketKToV [ prevInBucket ] = nextInBucketKToV [ entry ] ; nextInBucketKToV [ entry ] = ABSENT ; return ; } prevInBucket = entryInBucket ; } throw new AssertionError ( "Expected to find entry with key " + keys [ entry ] ) ;


signature:
public class HashBiMap { /** * Updates the V - to - K hash table to remove the entry at the specified index , which is assumed to
 * be present . Does not update any other data structures . */
private void deleteFromTableVToK ( int entry , int valueHash ) { } }

implementation: checkArgument ( entry != ABSENT ) ; int valueBucket = bucket ( valueHash ) ; if ( hashTableVToK [ valueBucket ] == entry ) { hashTableVToK [ valueBucket ] = nextInBucketVToK [ entry ] ; nextInBucketVToK [ entry ] = ABSENT ; return ; } int prevInBucket = hashTableVToK [ valueBucket ] ; for ( int entryInBucket = nextInBucketVToK [ prevInBucket ] ; entryInBucket != ABSENT ; entryInBucket = nextInBucketVToK [ entryInBucket ] ) { if ( entryInBucket == entry ) { nextInBucketVToK [ prevInBucket ] = nextInBucketVToK [ entry ] ; nextInBucketVToK [ entry ] = ABSENT ; return ; } prevInBucket = entryInBucket ; } throw new AssertionError ( "Expected to find entry with value " + values [ entry ] ) ;


signature:
public class HashBiMap { /** * Updates the specified entry to point to the new value : removes the old value from the V - to - K
 * mapping and puts the new one in . The entry does not move in the insertion order of the bimap . */
private void replaceValueInEntry ( int entry , @ NullableDecl V newValue , boolean force ) { } }

implementation:
checkArgument ( entry != ABSENT ) ; int newValueHash = Hashing . smearedHash ( newValue ) ; int newValueIndex = findEntryByValue ( newValue , newValueHash ) ; if ( newValueIndex != ABSENT ) { if ( force ) { removeEntryValueHashKnown ( newValueIndex , newValueHash ) ; if ( entry == size ) { // this entry got moved to newValueIndex
entry = newValueIndex ; } } else { throw new IllegalArgumentException ( "Value already present in map: " + newValue ) ; } } // we do * not * update insertion order , and it isn ' t a structural modification !
deleteFromTableVToK ( entry , Hashing . smearedHash ( values [ entry ] ) ) ; values [ entry ] = newValue ; insertIntoTableVToK ( entry , newValueHash ) ;


signature:
public class HashBiMap { /** * Updates the specified entry to point to the new value : removes the old value from the V - to - K
 * mapping and puts the new one in . The entry is moved to the end of the insertion order , or to
 * the position of the new key if it was previously present . */
private void replaceKeyInEntry ( int entry , @ NullableDecl K newKey , boolean force ) { } }

implementation:
checkArgument ( entry != ABSENT ) ; int newKeyHash = Hashing . smearedHash ( newKey ) ; int newKeyIndex = findEntryByKey ( newKey , newKeyHash ) ; int newPredecessor = lastInInsertionOrder ; int newSuccessor = ENDPOINT ; if ( newKeyIndex != ABSENT ) { if ( force ) { newPredecessor = prevInInsertionOrder [ newKeyIndex ] ; newSuccessor = nextInInsertionOrder [ newKeyIndex ] ; removeEntryKeyHashKnown ( newKeyIndex , newKeyHash ) ; if ( entry == size ) { // this entry got moved to newKeyIndex
entry = newKeyIndex ; } } else { throw new IllegalArgumentException ( "Key already present in map: " + newKey ) ; } } if ( newPredecessor == entry ) { newPredecessor = prevInInsertionOrder [ entry ] ; } else if ( newPredecessor == size ) { newPredecessor = newKeyIndex ; } if ( newSuccessor == entry ) { newSuccessor = nextInInsertionOrder [ entry ] ; } else if ( newSuccessor == size ) { newSuccessor = newKeyIndex ; } int oldPredecessor = prevInInsertionOrder [ entry ] ; int oldSuccessor = nextInInsertionOrder [ entry ] ; setSucceeds ( oldPredecessor , oldSuccessor ) ; // remove from insertion order linked list
deleteFromTableKToV ( entry , Hashing . smearedHash ( keys [ entry ] ) ) ; keys [ entry ] = newKey ; insertIntoTableKToV ( entry , Hashing . smearedHash ( newKey ) ) ; // insert into insertion order linked list , usually at the end
setSucceeds ( newPredecessor , entry ) ; setSucceeds ( entry , newSuccessor ) ;


signature:
public class HashBiMap { /** * Removes the entry at the specified index , given the hash of its key and value . */
private void removeEntry ( int entry , int keyHash , int valueHash ) { } }

implementation: checkArgument ( entry != ABSENT ) ; deleteFromTableKToV ( entry , keyHash ) ; deleteFromTableVToK ( entry , valueHash ) ; int oldPredecessor = prevInInsertionOrder [ entry ] ; int oldSuccessor = nextInInsertionOrder [ entry ] ; setSucceeds ( oldPredecessor , oldSuccessor ) ; moveEntryToIndex ( size - 1 , entry ) ; keys [ size - 1 ] = null ; values [ size - 1 ] = null ; size -- ; modCount ++ ;


signature:
public class HashBiMap { /** * Removes the entry at the specified index , given the hash of its key . */
void removeEntryKeyHashKnown ( int entry , int keyHash ) { } }

implementation: removeEntry ( entry , keyHash , Hashing . smearedHash ( values [ entry ] ) ) ;


signature:
public class HashBiMap { /** * Removes the entry at the specified index , given the hash of its value . */
void removeEntryValueHashKnown ( int entry , int valueHash ) { } }

implementation: removeEntry ( entry , Hashing . smearedHash ( keys [ entry ] ) , valueHash ) ;


signature:
public class HashBiMap { /** * Moves the entry previously positioned at { @ code src } to { @ code dest } . Assumes the entry
 * previously at { @ code src } has already been removed from the data structures . */
private void moveEntryToIndex ( int src , int dest ) { } }

implementation:
if ( src == dest ) { return ; } int predecessor = prevInInsertionOrder [ src ] ; int successor = nextInInsertionOrder [ src ] ; setSucceeds ( predecessor , dest ) ; setSucceeds ( dest , successor ) ; K key = keys [ src ] ; V value = values [ src ] ; keys [ dest ] = key ; values [ dest ] = value ; // update pointers in hashTableKToV
int keyHash = Hashing . smearedHash ( key ) ; int keyBucket = bucket ( keyHash ) ; if ( hashTableKToV [ keyBucket ] == src ) { hashTableKToV [ keyBucket ] = dest ; } else { int prevInBucket = hashTableKToV [ keyBucket ] ; for ( int entryInBucket = nextInBucketKToV [ prevInBucket ] ; /* should never reach end */
; entryInBucket = nextInBucketKToV [ entryInBucket ] ) { if ( entryInBucket == src ) { nextInBucketKToV [ prevInBucket ] = dest ; break ; } prevInBucket = entryInBucket ; } } nextInBucketKToV [ dest ] = nextInBucketKToV [ src ] ; nextInBucketKToV [ src ] = ABSENT ; // update pointers in hashTableVToK
int valueHash = Hashing . smearedHash ( value ) ; int valueBucket = bucket ( valueHash ) ; if ( hashTableVToK [ valueBucket ] == src ) { hashTableVToK [ valueBucket ] = dest ; } else { int prevInBucket = hashTableVToK [ valueBucket ] ; for ( int entryInBucket = nextInBucketVToK [ prevInBucket ] ; /* should never reach end */
; entryInBucket = nextInBucketVToK [ entryInBucket ] ) { if ( entryInBucket == src ) { nextInBucketVToK [ prevInBucket ] = dest ; break ; } prevInBucket = entryInBucket ; } } nextInBucketVToK [ dest ] = nextInBucketVToK [ src ] ; nextInBucketVToK [ src ] = ABSENT ;


signature:
public class ImmutableSortedSet { /** * Constructs an { @ code ImmutableSortedSet } from the first { @ code n } elements of { @ code contents } .
 * If { @ code k } is the size of the returned { @ code ImmutableSortedSet } , then the sorted unique
 * elements are in the first { @ code k } positions of { @ code contents } , and { @ code contents [ i ] = =
 * null } for { @ code k < = i < n } .
 * < p > This method takes ownership of { @ code contents } ; do not modify { @ code contents } after this
 * returns .
 * @ throws NullPointerException if any of the first { @ code n } elements of { @ code contents } is null */
static < E > ImmutableSortedSet < E > construct ( Comparator < ? super E > comparator , int n , E ... contents ) { } }

implementation:
if ( n == 0 ) { return emptySet ( comparator ) ; } checkElementsNotNull ( contents , n ) ; Arrays . sort ( contents , 0 , n , comparator ) ; int uniques = 1 ; for ( int i = 1 ; i < n ; i ++ ) { E cur = contents [ i ] ; E prev = contents [ uniques - 1 ] ; if ( comparator . compare ( cur , prev ) != 0 ) { contents [ uniques ++ ] = cur ; } } Arrays . fill ( contents , uniques , n , null ) ; if ( uniques < contents . length / 2 ) { // Deduplication eliminated many of the elements . We don ' t want to retain an arbitrarily
// large array relative to the number of elements , so we cap the ratio .
contents = Arrays . copyOf ( contents , uniques ) ; } return new RegularImmutableSortedSet < E > ( ImmutableList . < E > asImmutableList ( contents , uniques ) , comparator ) ;


signature:
public class Multisets { /** * Returns an immutable multiset entry with the specified element and count . The entry will be
 * serializable if { @ code e } is .
 * @ param e the element to be associated with the returned entry
 * @ param n the count to be associated with the returned entry
 * @ throws IllegalArgumentException if { @ code n } is negative */
public static < E > Multiset . Entry < E > immutableEntry ( @ NullableDecl E e , int n ) { } }

implementation: return new ImmutableEntry < E > ( e , n ) ;


signature:
public class Multisets { /** * An implementation of { @ link Multiset # equals } . */
static boolean equalsImpl ( Multiset < ? > multiset , @ NullableDecl Object object ) { } }

implementation:
if ( object == multiset ) { return true ; } if ( object instanceof Multiset ) { Multiset < ? > that = ( Multiset < ? > ) object ; /* * We can ' t simply check whether the entry sets are equal , since that
 * approach fails when a TreeMultiset has a comparator that returns 0
 * when passed unequal elements . */
if ( multiset . size ( ) != that . size ( ) || multiset . entrySet ( ) . size ( ) != that . entrySet ( ) . size ( ) ) { return false ; } for ( Entry < ? > entry : that . entrySet ( ) ) { if ( multiset . count ( entry . getElement ( ) ) != entry . getCount ( ) ) { return false ; } } return true ; } return false ;


signature:
public class Multisets { /** * A specialization of { @ code addAllImpl } for when { @ code elements } is itself a Multiset . */
private static < E > boolean addAllImpl ( Multiset < E > self , Multiset < ? extends E > elements ) { } }

implementation:
// It ' d be nice if we could specialize for ImmutableMultiset here without also retaining
// its code when it ' s not in scope . . .
if ( elements instanceof AbstractMapBasedMultiset ) { return addAllImpl ( self , ( AbstractMapBasedMultiset < ? extends E > ) elements ) ; } else if ( elements . isEmpty ( ) ) { return false ; } else { for ( Multiset . Entry < ? extends E > entry : elements . entrySet ( ) ) { self . add ( entry . getElement ( ) , entry . getCount ( ) ) ; } return true ; }


signature:
public class Multisets { /** * A specialization of { @ code addAllImpl } for when { @ code elements } is an
 * AbstractMapBasedMultiset . */
private static < E > boolean addAllImpl ( Multiset < E > self , AbstractMapBasedMultiset < ? extends E > elements ) { } }

implementation: if ( elements . isEmpty ( ) ) { return false ; } elements . addTo ( self ) ; return true ;


signature:
public class MapMakerInternalMap { /** * Returns the internal entry for the specified key . The entry may be computing or partially
 * collected . Does not impact recency ordering . */
E getEntry ( @ NullableDecl Object key ) { } }

implementation: if ( key == null ) { return null ; } int hash = hash ( key ) ; return segmentFor ( hash ) . getEntry ( key , hash ) ;


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

implementation: return new Builder < K , V > ( NATURAL_ORDER ) . build ( ) ;


signature:
public class ImmutableSortedMap { /** * We don ' t permit nulls , but we wrap every comparator with nullsFirst ( ) .
 * Why ? We want for queries like containsKey ( null ) to return false , but the
 * GWT SortedMap implementation that we delegate to throws
 * NullPointerException if the comparator does . Since our construction
 * methods ensure that null is never present in the map , it ' s OK for the
 * comparator to look for it wherever it wants .
 * Note that we do NOT touch the comparator returned by comparator ( ) , which
 * should be identical to the one the user passed in . We touch only the
 * " secret " comparator used by the delegate implementation . */
private static < K , V > SortedMap < K , V > newModifiableDelegate ( Comparator < ? super K > comparator ) { } }

implementation: return newTreeMap ( nullAccepting ( comparator ) ) ;


signature:
public class NetworkBuilder { /** * Returns a { @ link NetworkBuilder } initialized with all properties queryable from { @ code
 * network } .
 * < p > The " queryable " properties are those that are exposed through the { @ link Network } interface ,
 * such as { @ link Network # isDirected ( ) } . Other properties , such as { @ link
 * # expectedNodeCount ( int ) } , are not set in the new builder . */
public static < N , E > NetworkBuilder < N , E > from ( Network < N , E > network ) { } }

implementation: return new NetworkBuilder < N , E > ( network . isDirected ( ) ) . allowsParallelEdges ( network . allowsParallelEdges ( ) ) . allowsSelfLoops ( network . allowsSelfLoops ( ) ) . nodeOrder ( network . nodeOrder ( ) ) . edgeOrder ( network . edgeOrder ( ) ) ;


signature:
public class NetworkBuilder { /** * Returns an { @ link ImmutableNetwork # Builder } with the properties of this { @ link NetworkBuilder } .
 * < p > The returned builder can be used for populating an { @ link ImmutableNetwork } .
 * @ since NEXT */
public < N1 extends N , E1 extends E > ImmutableNetwork . Builder < N1 , E1 > immutable ( ) { } }

implementation: NetworkBuilder < N1 , E1 > castBuilder = cast ( ) ; return new ImmutableNetwork . Builder < > ( castBuilder ) ;


signature:
public class NetworkBuilder { /** * Specifies the expected number of nodes in the network .
 * @ throws IllegalArgumentException if { @ code expectedNodeCount } is negative */
public NetworkBuilder < N , E > expectedNodeCount ( int expectedNodeCount ) { } }

implementation: this . expectedNodeCount = Optional . of ( checkNonNegative ( expectedNodeCount ) ) ; return this ;


signature:
public class NetworkBuilder { /** * Specifies the expected number of edges in the network .
 * @ throws IllegalArgumentException if { @ code expectedEdgeCount } is negative */
public NetworkBuilder < N , E > expectedEdgeCount ( int expectedEdgeCount ) { } }

implementation: this . expectedEdgeCount = Optional . of ( checkNonNegative ( expectedEdgeCount ) ) ; return this ;


signature:
public class NetworkBuilder { /** * Specifies the order of iteration for the elements of { @ link Network # nodes ( ) } . */
public < N1 extends N > NetworkBuilder < N1 , E > nodeOrder ( ElementOrder < N1 > nodeOrder ) { } }

implementation: NetworkBuilder < N1 , E > newBuilder = cast ( ) ; newBuilder . nodeOrder = checkNotNull ( nodeOrder ) ; return newBuilder ;


signature:
public class NetworkBuilder { /** * Specifies the order of iteration for the elements of { @ link Network # edges ( ) } . */
public < E1 extends E > NetworkBuilder < N , E1 > edgeOrder ( ElementOrder < E1 > edgeOrder ) { } }

implementation: NetworkBuilder < N , E1 > newBuilder = cast ( ) ; newBuilder . edgeOrder = checkNotNull ( edgeOrder ) ; return newBuilder ;


signature:
public class Monitor { /** * Creates a new { @ linkplain Guard guard } for this monitor .
 * @ param isSatisfied the new guard ' s boolean condition ( see { @ link Guard # isSatisfied
 * isSatisfied ( ) } )
 * @ since 21.0 */
public Guard newGuard ( final BooleanSupplier isSatisfied ) { } }

implementation: checkNotNull ( isSatisfied , "isSatisfied" ) ; return new Guard ( this ) { @ Override public boolean isSatisfied ( ) { return isSatisfied . getAsBoolean ( ) ; } } ;


signature:
public class AbstractSortedSetMultimap { /** * Returns a collection view of all values associated with a key . If no mappings in the multimap
 * have the provided key , an empty collection is returned .
 * < p > Changes to the returned collection will update the underlying multimap , and vice versa .
 * < p > Because a { @ code SortedSetMultimap } has unique sorted values for a given key , this method
 * returns a { @ link SortedSet } , instead of the { @ link Collection } specified in the { @ link
 * Multimap } interface . */
@ Override public SortedSet < V > get ( @ NullableDecl K key ) { } }

implementation: return ( SortedSet < V > ) super . get ( key ) ;


signature:
public class AbstractSortedSetMultimap { /** * Removes all values associated with a given key . The returned collection is immutable .
 * < p > Because a { @ code SortedSetMultimap } has unique sorted values for a given key , this method
 * returns a { @ link SortedSet } , instead of the { @ link Collection } specified in the { @ link
 * Multimap } interface . */
@ CanIgnoreReturnValue @ Override public SortedSet < V > removeAll ( @ NullableDecl Object key ) { } }

implementation: return ( SortedSet < V > ) super . removeAll ( key ) ;


signature:
public class AutoTMClusterEngine { /** * 准备搜索TM
 * @ return true 搜索结束 */
private boolean prepareToResearchTMCluster ( ) { } }

implementation: int count = tryConnectCount . incrementAndGet ( ) ; int size = txClientConfig . getManagerAddress ( ) . size ( ) ; if ( count == size ) { TMSearcher . search ( ) ; return false ; } else if ( count > size ) { return ! TMSearcher . searchedOne ( ) ; } return true ;


signature:
public class AdminController { /** * 获取补偿信息
 * @ param page 页码
 * @ param limit 记录数
 * @ param extState extState
 * @ param registrar registrar
 * @ return ExceptionList */
@ GetMapping ( { } }

implementation: "/exceptions/{page}" , "/exceptions" , "/exceptions/{page}/{limit}" } ) public ExceptionList exceptionList ( @ RequestParam ( value = "page" , required = false ) @ PathVariable ( value = "page" , required = false ) Integer page , @ RequestParam ( value = "limit" , required = false ) @ PathVariable ( value = "limit" , required = false ) Integer limit , @ RequestParam ( value = "extState" , required = false ) Integer extState , @ RequestParam ( value = "registrar" , required = false ) Integer registrar ) { return txExceptionService . exceptionList ( page , limit , extState , null , registrar ) ;


signature:
public class AdminController { /** * 删除异常信息
 * @ param deleteExceptions 异常信息标示
 * @ return 操作结果
 * @ throws TxManagerException TxManagerException */
@ PostMapping ( "/exceptions" ) public boolean deleteExceptions ( @ RequestBody DeleteExceptions deleteExceptions ) throws TxManagerException { } }

implementation: txExceptionService . deleteExceptions ( deleteExceptions . getId ( ) ) ; return true ;


signature:
public class AdminController { /** * 获取某个事务组某个节点具体补偿信息
 * @ param groupId groupId
 * @ param unitId unitId
 * @ return transaction info
 * @ throws TxManagerException TxManagerException */
@ GetMapping ( "/log/transaction-info" ) public JSONObject transactionInfo ( @ RequestParam ( "groupId" ) String groupId , @ RequestParam ( "unitId" ) String unitId ) throws TxManagerException { } }

implementation: try { return txExceptionService . getTransactionInfo ( groupId , unitId ) ; } catch ( TransactionStateException e ) { throw new TxManagerException ( e ) ; }


signature:
public class AdminController { /** * 日志信息
 * @ param page 页码
 * @ param limit 记录数
 * @ param groupId groupId
 * @ param tag tag
 * @ param lTime lTime
 * @ param rTime rtime
 * @ param timeOrder timeOrder
 * @ return TxLogList
 * @ throws TxManagerException TxManagerException */
@ GetMapping ( { } }

implementation: "/logs/{page}" , "/logs/{page}/{limit}" , "/logs" } ) public TxLogList txLogList ( @ RequestParam ( value = "page" , required = false ) @ PathVariable ( value = "page" , required = false ) Integer page , @ RequestParam ( value = "limit" , required = false ) @ PathVariable ( value = "limit" , required = false ) Integer limit , @ RequestParam ( value = "groupId" , required = false ) String groupId , @ RequestParam ( value = "tag" , required = false ) String tag , @ RequestParam ( value = "ld" , required = false ) String lTime , @ RequestParam ( value = "rd" , required = false ) String rTime , @ RequestParam ( value = "timeOrder" , required = false ) Integer timeOrder ) throws TxManagerException { return adminService . txLogList ( page , limit , groupId , tag , lTime , rTime , timeOrder ) ;


signature:
public class AdminController { /** * 删除日志
 * @ param deleteLogsReq deleteLogsReq
 * @ return bool
 * @ throws TxManagerException TxManagerException */
@ DeleteMapping ( "/logs" ) public boolean deleteLogs ( @ RequestBody DeleteLogsReq deleteLogsReq ) throws TxManagerException { } }

implementation: adminService . deleteLogs ( deleteLogsReq ) ; return true ;


signature:
public class AdminController { /** * 删除异常事务信息
 * @ param groupId groupId
 * @ param unitId unitId
 * @ param modId modId
 * @ return result always true if non exception
 * @ throws TxManagerException TxManagerException */
@ DeleteMapping ( "/transaction-info" ) public boolean deleteTransactionInfo ( @ RequestParam ( "groupId" ) String groupId , @ RequestParam ( "unitId" ) String unitId , @ RequestParam ( "modId" ) String modId ) throws TxManagerException { } }

implementation: txExceptionService . deleteTransactionInfo ( groupId , unitId , modId ) ; return true ;


signature:
public class LoopMessenger { /** * 强通讯
 * @ param messageDto 通讯数据
 * @ param whenNonManagerMessage 异常提示
 * @ return MessageDto
 * @ throws RpcException RpcException */
private MessageDto request ( MessageDto messageDto , long timeout , String whenNonManagerMessage ) throws RpcException { } }

implementation: for ( int i = 0 ; i < rpcClient . loadAllRemoteKey ( ) . size ( ) + 1 ; i ++ ) { try { String remoteKey = rpcClient . loadRemoteKey ( ) ; MessageDto result = rpcClient . request ( remoteKey , messageDto , timeout ) ; log . debug ( "request action: {}. TM[{}]" , messageDto . getAction ( ) , remoteKey ) ; return result ; } catch ( RpcException e ) { if ( e . getCode ( ) == RpcException . NON_TX_MANAGER ) { throw new RpcException ( e . getCode ( ) , whenNonManagerMessage + ". non tx-manager is alive." ) ; } } } throw new RpcException ( RpcException . NON_TX_MANAGER , whenNonManagerMessage + ". non tx-manager is alive." ) ;


signature:
public class SnowFlakeGenerator { /** * 产生下一个ID
 * @ return id */
public synchronized long nextId ( ) { } }

implementation: long currentStamp = getTimeMill ( ) ; if ( currentStamp < lastStamp ) { throw new RuntimeException ( "Clock moved backwards." ) ; } if ( currentStamp == lastStamp ) { sequence = ( sequence + 1 ) & this . maxSequenceValue ; if ( sequence == 0L ) { lastStamp = tilNextMillis ( ) ; } } else { sequence = 0L ; } lastStamp = currentStamp ; return ( currentStamp - START_STAMP ) << timestampBitLeftOffset | idcId << idcBitLeftOffset | machineId << machineBitLeftOffset | sequence ;


signature:
public class Tracings { /** * 传输Tracing信息
 * @ param tracingSetter Tracing信息设置器 */
public static void transmit ( TracingSetter tracingSetter ) { } }

implementation: if ( TracingContext . tracing ( ) . hasGroup ( ) ) { log . debug ( "tracing transmit group:{}" , TracingContext . tracing ( ) . groupId ( ) ) ; tracingSetter . set ( TracingConstants . HEADER_KEY_GROUP_ID , TracingContext . tracing ( ) . groupId ( ) ) ; tracingSetter . set ( TracingConstants . HEADER_KEY_APP_MAP , Base64Utils . encodeToString ( TracingContext . tracing ( ) . appMapString ( ) . getBytes ( StandardCharsets . UTF_8 ) ) ) ; }


signature:
public class Tracings { /** * 获取传输的Tracing信息
 * @ param tracingGetter Tracing信息获取器 */
public static void apply ( TracingGetter tracingGetter ) { } }

implementation: String groupId = Optional . ofNullable ( tracingGetter . get ( TracingConstants . HEADER_KEY_GROUP_ID ) ) . orElse ( "" ) ; String appList = Optional . ofNullable ( tracingGetter . get ( TracingConstants . HEADER_KEY_APP_MAP ) ) . orElse ( "" ) ; TracingContext . init ( Maps . newHashMap ( TracingConstants . GROUP_ID , groupId , TracingConstants . APP_MAP , StringUtils . isEmpty ( appList ) ? appList : new String ( Base64Utils . decodeFromString ( appList ) , StandardCharsets . UTF_8 ) ) ) ; if ( TracingContext . tracing ( ) . hasGroup ( ) ) { log . debug ( "tracing apply group:{}, app map:{}" , groupId , appList ) ; }


signature:
public class MessageCreator { /** * 创建事务组
 * @ param groupId groupId
 * @ return MessageDto */
public static MessageDto createGroup ( String groupId ) { } }

implementation: MessageDto msg = new MessageDto ( ) ; msg . setGroupId ( groupId ) ; msg . setAction ( MessageConstants . ACTION_CREATE_GROUP ) ; return msg ;


signature:
public class MessageCreator { /** * 加入事务组
 * @ param joinGroupParams joinGroupParams
 * @ return MessageDto */
public static MessageDto joinGroup ( JoinGroupParams joinGroupParams ) { } }

implementation: MessageDto msg = new MessageDto ( ) ; msg . setGroupId ( joinGroupParams . getGroupId ( ) ) ; msg . setAction ( MessageConstants . ACTION_JOIN_GROUP ) ; msg . setData ( joinGroupParams ) ; return msg ;


signature:
public class MessageCreator { /** * 关闭事务组
 * @ param notifyGroupParams notifyGroupParams
 * @ return MessageDto */
public static MessageDto notifyGroup ( NotifyGroupParams notifyGroupParams ) { } }

implementation: MessageDto msg = new MessageDto ( ) ; msg . setGroupId ( notifyGroupParams . getGroupId ( ) ) ; msg . setAction ( MessageConstants . ACTION_NOTIFY_GROUP ) ; msg . setData ( notifyGroupParams ) ; return msg ;


signature:
public class MessageCreator { /** * 申请锁消息
 * @ param groupId groupId
 * @ param locks locks
 * @ param lockType lockType
 * @ return message */
public static MessageDto acquireLocks ( String groupId , Set < String > locks , int lockType ) { } }

implementation: DTXLockParams dtxLockParams = new DTXLockParams ( ) ; dtxLockParams . setGroupId ( groupId ) ; dtxLockParams . setContextId ( Transactions . APPLICATION_ID_WHEN_RUNNING ) ; dtxLockParams . setLocks ( locks ) ; dtxLockParams . setLockType ( lockType ) ; MessageDto messageDto = new MessageDto ( ) ; messageDto . setAction ( MessageConstants . ACTION_ACQUIRE_DTX_LOCK ) ; messageDto . setData ( dtxLockParams ) ; return messageDto ;


signature:
public class MessageCreator { /** * 释放锁消息
 * @ param locks locks
 * @ return message */
public static MessageDto releaseLocks ( Set < String > locks ) { } }

implementation: DTXLockParams dtxLockParams = new DTXLockParams ( ) ; dtxLockParams . setContextId ( Transactions . APPLICATION_ID_WHEN_RUNNING ) ; dtxLockParams . setLocks ( locks ) ; MessageDto messageDto = new MessageDto ( ) ; messageDto . setAction ( MessageConstants . ACTION_RELEASE_DTX_LOCK ) ; messageDto . setData ( dtxLockParams ) ; return messageDto ;


signature:
public class MessageCreator { /** * 通知事务单元成功
 * @ param message message
 * @ param action action
 * @ return MessageDto */
public static MessageDto notifyUnitOkResponse ( Serializable message , String action ) { } }

implementation: MessageDto messageDto = new MessageDto ( ) ; messageDto . setAction ( action ) ; messageDto . setState ( MessageConstants . STATE_OK ) ; messageDto . setData ( message ) ; return messageDto ;


signature:
public class MessageCreator { /** * 通知事务单元失败
 * @ param message message
 * @ param action action
 * @ return MessageDto */
public static MessageDto notifyUnitFailResponse ( Serializable message , String action ) { } }

implementation: MessageDto messageDto = new MessageDto ( ) ; messageDto . setState ( MessageConstants . STATE_EXCEPTION ) ; messageDto . setAction ( action ) ; messageDto . setData ( message ) ; return messageDto ;


signature:
public class MessageCreator { /** * 询问事务状态指令
 * @ param groupId groupId
 * @ param unitId unitId
 * @ return MessageDto */
public static MessageDto askTransactionState ( String groupId , String unitId ) { } }

implementation: MessageDto messageDto = new MessageDto ( ) ; messageDto . setGroupId ( groupId ) ; messageDto . setAction ( MessageConstants . ACTION_ASK_TRANSACTION_STATE ) ; messageDto . setData ( new AskTransactionStateParams ( groupId , unitId ) ) ; return messageDto ;


signature:
public class MessageCreator { /** * 写异常信息指令
 * @ param txExceptionParams txExceptionParams
 * @ return MessageDto */
public static MessageDto writeTxException ( TxExceptionParams txExceptionParams ) { } }

implementation: MessageDto messageDto = new MessageDto ( ) ; messageDto . setAction ( MessageConstants . ACTION_WRITE_EXCEPTION ) ; messageDto . setGroupId ( txExceptionParams . getGroupId ( ) ) ; messageDto . setData ( txExceptionParams ) ; return messageDto ;


signature:
public class MessageCreator { /** * 初始化客户端请求
 * @ param appName appName
 * @ param labelName labelName
 * @ return MessageDto */
public static MessageDto initClient ( String appName , String labelName ) { } }

implementation: InitClientParams initClientParams = new InitClientParams ( ) ; initClientParams . setAppName ( appName ) ; initClientParams . setLabelName ( labelName ) ; MessageDto messageDto = new MessageDto ( ) ; messageDto . setData ( initClientParams ) ; messageDto . setAction ( MessageConstants . ACTION_INIT_CLIENT ) ; return messageDto ;


signature:
public class IdGenInit { /** * 原版雪花算法 , 生成一个long类型的ID
 * @ param machineLen 机器位长度
 * @ param machineId 机器ID */
public static void applySnowFlakeIdGen ( int machineLen , long machineId ) { } }

implementation: SnowFlakeGenerator . Factory factory = new SnowFlakeGenerator . Factory ( machineLen , 0 ) ; SnowFlakeGenerator snowFlakeGenerator = factory . create ( 0 , machineId ) ; RandomUtils . init ( ( ) -> String . valueOf ( snowFlakeGenerator . nextId ( ) ) ) ;


signature:
public class CallableStatementInformation { /** * Generates the query for the callable statement with all parameter placeholders
 * replaced with the actual parameter values
 * @ return the SQL */
@ Override public String getSqlWithValues ( ) { } }

implementation:
if ( namedParameterValues . size ( ) == 0 ) { return super . getSqlWithValues ( ) ; } /* If named parameters were used , it is no longer possible to simply replace the placeholders in the
 original statement with the values of the bind variables . The only way it could be done is if the names
 could be resolved by to the ordinal positions which is not possible on all databases .
 New log format : < original statement > name : value , name : value
 Example : { ? = call test _ proc ( ? , ? ) } param1 : value1 , param2 : value2 , param3 : value3
 In the event that ordinal and named parameters are both used , the original position will be used as the name .
 Example : { ? = call test _ proc ( ? , ? ) } 1 : value1 , 3 : value3 , param2 : value2 */
final StringBuilder result = new StringBuilder ( ) ; final String statementQuery = getStatementQuery ( ) ; // first append the original statement
result . append ( statementQuery ) ; result . append ( " " ) ; StringBuilder parameters = new StringBuilder ( ) ; // add parameters set with ordinal positions
for ( Map . Entry < Integer , Value > entry : getParameterValues ( ) . entrySet ( ) ) { appendParameter ( parameters , entry . getKey ( ) . toString ( ) , entry . getValue ( ) ) ; } // add named parameters
for ( Map . Entry < String , Value > entry : namedParameterValues . entrySet ( ) ) { appendParameter ( parameters , entry . getKey ( ) , entry . getValue ( ) ) ; } result . append ( parameters ) ; return result . toString ( ) ;


signature:
public class CallableStatementInformation { /** * Records the value of a parameter .
 * @ param name the name of the parameter
 * @ param value the value of the parameter */
public void setParameterValue ( final String name , final Object value ) { } }

implementation: namedParameterValues . put ( name , new Value ( value ) ) ;


signature:
public class TMReporter { /** * Manager 记录事务状态
 * @ param groupId groupId
 * @ param unitId unitId
 * @ param registrar registrar
 * @ param state transactionState */
public void reportTransactionState ( String groupId , String unitId , Short registrar , int state ) { } }

implementation: TxExceptionParams txExceptionParams = new TxExceptionParams ( ) ; txExceptionParams . setGroupId ( groupId ) ; txExceptionParams . setRegistrar ( registrar ) ; txExceptionParams . setTransactionState ( state ) ; txExceptionParams . setUnitId ( unitId ) ; report ( txExceptionParams ) ;


signature:
public class TMReporter { /** * Manager 记录TCC清理事务失败
 * @ param groupId groupId
 * @ param unitId unitId
 * @ param state state */
public void reportTccCleanException ( String groupId , String unitId , int state ) { } }

implementation: TxExceptionParams txExceptionParams = new TxExceptionParams ( ) ; txExceptionParams . setGroupId ( groupId ) ; txExceptionParams . setRegistrar ( TxExceptionParams . TCC_CLEAN_ERROR ) ; txExceptionParams . setTransactionState ( state ) ; txExceptionParams . setUnitId ( unitId ) ; report ( txExceptionParams ) ;


signature:
public class TransactionCleanTemplate { /** * 清理事务
 * @ param groupId groupId
 * @ param unitId unitId
 * @ param unitType unitType
 * @ param state transactionState
 * @ throws TransactionClearException TransactionClearException */
public void clean ( String groupId , String unitId , String unitType , int state ) throws TransactionClearException { } }

implementation: txLogger . txTrace ( groupId , unitId , "clean transaction" ) ; try { cleanWithoutAspectLog ( groupId , unitId , unitType , state ) ; aspectLogger . clearLog ( groupId , unitId ) ; } catch ( TransactionClearException e ) { if ( ! e . isNeedCompensation ( ) ) { aspectLogger . clearLog ( groupId , unitId ) ; } } catch ( Throwable throwable ) { aspectLogger . clearLog ( groupId , unitId ) ; } txLogger . txTrace ( groupId , unitId , "clean transaction over" ) ;


signature:
public class TransactionCleanTemplate { /** * 清理事务 ( 不清理切面日志 )
 * @ param groupId groupId
 * @ param unitId unitId
 * @ param unitType unitType
 * @ param state transactionState
 * @ throws TransactionClearException TransactionClearException */
public void cleanWithoutAspectLog ( String groupId , String unitId , String unitType , int state ) throws TransactionClearException { } }

implementation: try { transactionBeanHelper . loadTransactionCleanService ( unitType ) . clear ( groupId , state , unitId , unitType ) ; } finally { globalContext . clearGroup ( groupId ) ; dtxChecking . stopDelayChecking ( groupId , unitId ) ; }


signature:
public class MessageCreator { /** * 通知TxClient连接
 * @ param notifyConnectParams notifyConnectParams
 * @ return MessageDto */
public static MessageDto newTxManager ( NotifyConnectParams notifyConnectParams ) { } }

implementation: MessageDto msg = new MessageDto ( ) ; msg . setAction ( MessageConstants . ACTION_NEW_TXMANAGER ) ; msg . setData ( notifyConnectParams ) ; return msg ;


signature:
public class MessageCreator { /** * 提交事务组
 * @ param notifyUnitParams notifyUnitParams
 * @ return MessageDto */
public static MessageDto notifyUnit ( NotifyUnitParams notifyUnitParams ) { } }

implementation: MessageDto msg = new MessageDto ( ) ; msg . setGroupId ( notifyUnitParams . getGroupId ( ) ) ; msg . setAction ( MessageConstants . ACTION_NOTIFY_UNIT ) ; msg . setData ( notifyUnitParams ) ; return msg ;


signature:
public class MessageCreator { /** * 服务器错误
 * @ param action action
 * @ return MessageDto */
public static MessageDto serverException ( String action ) { } }

implementation: MessageDto messageDto = new MessageDto ( ) ; messageDto . setAction ( action ) ; messageDto . setState ( MessageConstants . STATE_EXCEPTION ) ; return messageDto ;


signature:
public class MessageCreator { /** * 获取切面日志
 * @ param groupId groupId
 * @ param unitId unitId
 * @ return aspect log */
public static MessageDto getAspectLog ( String groupId , String unitId ) { } }

implementation: GetAspectLogParams getAspectLogParams = new GetAspectLogParams ( ) ; getAspectLogParams . setGroupId ( groupId ) ; getAspectLogParams . setUnitId ( unitId ) ; MessageDto messageDto = new MessageDto ( ) ; messageDto . setGroupId ( groupId ) ; messageDto . setAction ( MessageConstants . ACTION_GET_ASPECT_LOG ) ; messageDto . setData ( getAspectLogParams ) ; return messageDto ;


signature:
public class MessageCreator { /** * 删除切面日志
 * @ param groupId groupId
 * @ param unitId unitId
 * @ return result */
public static MessageDto deleteAspectLog ( String groupId , String unitId ) { } }

implementation: DeleteAspectLogParams deleteAspectLogParams = new DeleteAspectLogParams ( ) ; deleteAspectLogParams . setGroupId ( groupId ) ; deleteAspectLogParams . setUnitId ( unitId ) ; MessageDto messageDto = new MessageDto ( ) ; messageDto . setData ( deleteAspectLogParams ) ; messageDto . setAction ( MessageConstants . ACTION_DELETE_ASPECT_LOG ) ; messageDto . setGroupId ( groupId ) ; return messageDto ;


signature:
public class RpcCmdContext { /** * 并发可能会出重复添加
 * @ param key key
 * @ return RpcContent */
public synchronized RpcContent addKey ( String key ) { } }

implementation: RpcContent rpcContent = createRpcContent ( ) ; map . put ( key , rpcContent ) ; return rpcContent ;


signature:
public class RpcCmdContext { /** * 空闲队列处理
 * @ return RpcContent */
private RpcContent findRpcContent ( ) { } }

implementation: synchronized ( freeList ) { RpcContent cacheContent = freeList . getFirst ( ) ; if ( ! cacheContent . isUsed ( ) ) { cacheContent . init ( ) ; freeList . remove ( cacheContent ) ; return cacheContent ; } } RpcContent rpcContent = new RpcContent ( getWaitTime ( ) ) ; rpcContent . init ( ) ; return rpcContent ;


signature:
public class TransactionControlTemplate { /** * Client创建事务组操作集合
 * @ param groupId groupId
 * @ param unitId unitId
 * @ param transactionInfo txTrace
 * @ param transactionType transactionType
 * @ throws TransactionException 创建group失败时抛出 */
public void createGroup ( String groupId , String unitId , TransactionInfo transactionInfo , String transactionType ) throws TransactionException { } }

implementation:
// 创建事务组
try { // 日志
txLogger . txTrace ( groupId , unitId , "create group > transaction type: {}" , transactionType ) ; // 创建事务组消息
reliableMessenger . createGroup ( groupId ) ; // 缓存发起方切面信息
aspectLogger . trace ( groupId , unitId , transactionInfo ) ; } catch ( RpcException e ) { // 通讯异常
dtxExceptionHandler . handleCreateGroupMessageException ( groupId , e ) ; } catch ( LcnBusinessException e ) { // 创建事务组业务失败
dtxExceptionHandler . handleCreateGroupBusinessException ( groupId , e . getCause ( ) ) ; } txLogger . txTrace ( groupId , unitId , "create group over" ) ;


signature:
public class TransactionControlTemplate { /** * Client加入事务组操作集合
 * @ param groupId groupId
 * @ param unitId unitId
 * @ param transactionType transactionType
 * @ param transactionInfo txTrace
 * @ throws TransactionException 加入事务组失败时抛出 */
public void joinGroup ( String groupId , String unitId , String transactionType , TransactionInfo transactionInfo ) throws TransactionException { } }

implementation:
try { txLogger . txTrace ( groupId , unitId , "join group > transaction type: {}" , transactionType ) ; reliableMessenger . joinGroup ( groupId , unitId , transactionType , DTXLocalContext . transactionState ( globalContext . dtxState ( groupId ) ) ) ; txLogger . txTrace ( groupId , unitId , "join group message over." ) ; // 异步检测
dtxChecking . startDelayCheckingAsync ( groupId , unitId , transactionType ) ; // 缓存参与方切面信息
aspectLogger . trace ( groupId , unitId , transactionInfo ) ; } catch ( RpcException e ) { dtxExceptionHandler . handleJoinGroupMessageException ( Arrays . asList ( groupId , unitId , transactionType ) , e ) ; } catch ( LcnBusinessException e ) { dtxExceptionHandler . handleJoinGroupBusinessException ( Arrays . asList ( groupId , unitId , transactionType ) , e ) ; } txLogger . txTrace ( groupId , unitId , "join group logic over" ) ;


signature:
public class TransactionControlTemplate { /** * Client通知事务组操作集合
 * @ param groupId groupId
 * @ param unitId unitId
 * @ param transactionType transactionType
 * @ param state transactionState */
public void notifyGroup ( String groupId , String unitId , String transactionType , int state ) { } }

implementation:
try { txLogger . txTrace ( groupId , unitId , "notify group > transaction type: {}, state: {}." , transactionType , state ) ; if ( globalContext . isDTXTimeout ( ) ) { throw new LcnBusinessException ( "dtx timeout." ) ; } state = reliableMessenger . notifyGroup ( groupId , state ) ; transactionCleanTemplate . clean ( groupId , unitId , transactionType , state ) ; } catch ( TransactionClearException e ) { txLogger . trace ( groupId , unitId , Transactions . TE , "clean transaction fail." ) ; } catch ( RpcException e ) { dtxExceptionHandler . handleNotifyGroupMessageException ( Arrays . asList ( groupId , state , unitId , transactionType ) , e ) ; } catch ( LcnBusinessException e ) { // 关闭事务组失败
dtxExceptionHandler . handleNotifyGroupBusinessException ( Arrays . asList ( groupId , state , unitId , transactionType ) , e . getCause ( ) ) ; } txLogger . txTrace ( groupId , unitId , "notify group exception state {}." , state ) ;


signature:
public class SqlUtils { /** * 从完全标识字段名获取表名
 * @ param fieldFullyQualifiedName fieldFullyQualifiedName
 * @ return tableName */
public static String tableName ( String fieldFullyQualifiedName ) { } }

implementation: if ( fieldFullyQualifiedName . contains ( "." ) ) { return fieldFullyQualifiedName . substring ( 0 , fieldFullyQualifiedName . indexOf ( "." ) ) ; } return null ;


signature:
public class SqlUtils { /** * 从字符串构造器剪掉结束符
 * @ param suffix suffix
 * @ param stringBuilder stringBuilder */
public static void cutSuffix ( String suffix , StringBuilder stringBuilder ) { } }

implementation: if ( stringBuilder . substring ( stringBuilder . length ( ) - suffix . length ( ) ) . equals ( suffix ) ) { stringBuilder . delete ( stringBuilder . length ( ) - suffix . length ( ) , stringBuilder . length ( ) ) ; }


signature:
public class SqlUtils { /** * 获取修改记录
 * @ param rs rs
 * @ param columns columns
 * @ return ModifiedRecord
 * @ throws SQLException SQLException */
public static ModifiedRecord recordByColumns ( ResultSet rs , List < String > columns ) throws SQLException { } }

implementation: ModifiedRecord record = new ModifiedRecord ( ) ; for ( String column : columns ) { FieldValue fieldValue = new FieldValue ( ) ; fieldValue . setFieldName ( column ) ; fieldValue . setTableName ( SqlUtils . tableName ( column ) ) ; fieldValue . setValue ( rs . getObject ( column ) ) ; fieldValue . setValueType ( Objects . isNull ( fieldValue . getValue ( ) ) ? Void . class : fieldValue . getValue ( ) . getClass ( ) ) ; if ( record . getFieldClusters ( ) . get ( fieldValue . getTableName ( ) ) != null ) { record . getFieldClusters ( ) . get ( fieldValue . getTableName ( ) ) . getFields ( ) . add ( fieldValue ) ; } else { FieldCluster fieldCluster = new FieldCluster ( ) ; fieldCluster . getFields ( ) . add ( fieldValue ) ; record . getFieldClusters ( ) . put ( fieldValue . getTableName ( ) , fieldCluster ) ; } } return record ;


signature:
public class SqlUtils { /** * java Object to bytes
 * @ param o o
 * @ return byte [ ] */
public static byte [ ] objectToBlob ( Object o ) { } }

implementation: try { return SerializerContext . getInstance ( ) . serialize ( o ) ; } catch ( SerializerException e ) { throw new RuntimeException ( e ) ; }


signature:
public class SqlUtils { /** * bytes to java object .
 * @ param blob blob
 * @ param type type
 * @ param < T > T
 * @ return T */
public static < T > T blobToObject ( byte [ ] blob , Class < T > type ) { } }

implementation: try { return SerializerContext . getInstance ( ) . deSerialize ( blob , type ) ; } catch ( SerializerException e ) { throw new IllegalStateException ( e ) ; }


signature:
public class TxcLogHelper { /** * 保存TXC撤销日志
 * @ param undoLogDO 撤销日志对象
 * @ throws SQLException 数据库操作失败 */
public void saveUndoLog ( UndoLogDO undoLogDO ) throws SQLException { } }

implementation: String sql = "INSERT INTO TXC_UNDO_LOG (UNIT_ID,GROUP_ID,SQL_TYPE,ROLLBACK_INFO,CREATE_TIME) VALUES(?,?,?,?,?)" ; h2DbHelper . queryRunner ( ) . update ( sql , undoLogDO . getUnitId ( ) , undoLogDO . getGroupId ( ) , undoLogDO . getSqlType ( ) , undoLogDO . getRollbackInfo ( ) , undoLogDO . getCreateTime ( ) ) ;


signature:
public class TxcLogHelper { /** * 获取某个事务下具体UNIT的TXC撤销日志
 * @ param groupId groupId
 * @ param unitId unitId
 * @ return undo log list
 * @ throws SQLException 数据库操作失败 */
public List < UndoLogDO > getUndoLogByGroupAndUnitId ( String groupId , String unitId ) throws SQLException { } }

implementation: String sql = "SELECT * FROM TXC_UNDO_LOG WHERE GROUP_ID = ? and UNIT_ID = ?" ; return h2DbHelper . queryRunner ( ) . query ( sql , rs -> { List < UndoLogDO > undoLogDOList = new ArrayList < > ( ) ; while ( rs . next ( ) ) { UndoLogDO undoLogDO = new UndoLogDO ( ) ; undoLogDO . setSqlType ( rs . getInt ( "SQL_TYPE" ) ) ; undoLogDO . setRollbackInfo ( rs . getBytes ( "ROLLBACK_INFO" ) ) ; undoLogDO . setUnitId ( rs . getString ( "UNIT_ID" ) ) ; undoLogDO . setGroupId ( "GROUP_ID" ) ; undoLogDO . setCreateTime ( rs . getString ( "CREATE_TIME" ) ) ; undoLogDOList . add ( undoLogDO ) ; } return undoLogDOList ; } , groupId , unitId ) ;


signature:
public class TxcLogHelper { /** * 删除TXC撤销日志
 * @ param groupId groupId
 * @ param unitId unitId
 * @ throws SQLException 数据库操作失败 */
public void deleteUndoLog ( String groupId , String unitId ) throws SQLException { } }

implementation: String sql = "DELETE FROM TXC_UNDO_LOG WHERE GROUP_ID=? AND UNIT_ID=?" ; h2DbHelper . queryRunner ( ) . update ( sql , groupId , unitId ) ;


signature:
public class TxcServiceImpl { /** * lock data line
 * @ param groupId groupId
 * @ param unitId unitId
 * @ param lockIdSet lockIdSet
 * @ param isXLock isXLock
 * @ throws TxcLogicException 业务异常 */
private void lockDataLine ( String groupId , String unitId , Set < String > lockIdSet , boolean isXLock ) throws TxcLogicException { } }

implementation: try { if ( ! reliableMessenger . acquireLocks ( groupId , lockIdSet , isXLock ? DTXLocks . X_LOCK : DTXLocks . S_LOCK ) ) { throw new TxcLogicException ( "resource is locked! place try again later." ) ; } globalContext . addTxcLockId ( groupId , unitId , lockIdSet ) ; } catch ( RpcException e ) { throw new TxcLogicException ( "can't contact to any TM for lock info. default error." ) ; }


signature:
public class TxcServiceImpl { /** * save sql undo log
 * @ param groupId groupId
 * @ param unitId unitId
 * @ param sqlType sqlType
 * @ param recordList recordList
 * @ throws TxcLogicException 业务异常 */
private void saveUndoLog ( String groupId , String unitId , int sqlType , TableRecordList recordList ) throws TxcLogicException { } }

implementation: UndoLogDO undoLogDO = new UndoLogDO ( ) ; undoLogDO . setRollbackInfo ( SqlUtils . objectToBlob ( recordList ) ) ; undoLogDO . setUnitId ( unitId ) ; undoLogDO . setGroupId ( groupId ) ; undoLogDO . setSqlType ( sqlType ) ; try { txcLogHelper . saveUndoLog ( undoLogDO ) ; } catch ( SQLException e ) { throw new TxcLogicException ( e ) ; }


signature:
public class TxcServiceImpl { /** * Hex String
 * @ param content origin string
 * @ return hex */
private String hex ( String content ) { } }

implementation: return DigestUtils . md5DigestAsHex ( content . getBytes ( StandardCharsets . UTF_8 ) ) ;


signature:
public class TxcServiceImpl { /** * 解决受影响数据
 * @ param modifiedRecords 受影响的数据
 * @ param sqlType SQL 类型
 * @ throws TxcLogicException 业务异常 */
private void resolveModifiedRecords ( List < ModifiedRecord > modifiedRecords , int sqlType ) throws TxcLogicException { } }

implementation:
TableRecordList tableRecords = new TableRecordList ( ) ; Set < String > lockIdSet = new HashSet < > ( ) ; // Build reverse sql
for ( ModifiedRecord modifiedRecord : modifiedRecords ) { for ( Map . Entry < String , FieldCluster > entry : modifiedRecord . getFieldClusters ( ) . entrySet ( ) ) { TableRecord tableRecord = new TableRecord ( ) ; tableRecord . setTableName ( entry . getKey ( ) ) ; tableRecord . setFieldCluster ( entry . getValue ( ) ) ; tableRecords . getTableRecords ( ) . add ( tableRecord ) ; lockIdSet . add ( hex ( tableRecord . getFieldCluster ( ) . getPrimaryKeys ( ) . toString ( ) ) ) ; } } // 受影响记录为0
if ( lockIdSet . isEmpty ( ) ) { return ; } String groupId = DTXLocalContext . cur ( ) . getGroupId ( ) ; String unitId = DTXLocalContext . cur ( ) . getUnitId ( ) ; // lock
lockDataLine ( groupId , unitId , lockIdSet , true ) ; // save to h2db
saveUndoLog ( groupId , unitId , sqlType , tableRecords ) ;


signature:
public class RedisConfiguration { /** * default configuration redis template when have RedisConnectionFactory */
@ Bean @ ConditionalOnClass ( name = "org.springframework.data.redis.connection.RedisConnectionFactory" ) public RedisTemplate < String , Object > functionDomainRedisTemplate ( RedisConnectionFactory redisConnectionFactory ) { } }

implementation: JdkSerializationRedisSerializer serializationRedisSerializer = new JdkSerializationRedisSerializer ( ) ; StringRedisSerializer stringRedisSerializer = new StringRedisSerializer ( ) ; RedisTemplate < String , Object > redisTemplate = new RedisTemplate < > ( ) ; redisTemplate . setKeySerializer ( stringRedisSerializer ) ; redisTemplate . setHashKeySerializer ( stringRedisSerializer ) ; redisTemplate . setHashValueSerializer ( serializationRedisSerializer ) ; redisTemplate . setValueSerializer ( serializationRedisSerializer ) ; redisTemplate . setConnectionFactory ( redisConnectionFactory ) ; return redisTemplate ;


signature:
public class TMSearcher { /** * 重新搜寻TM */
public static void search ( ) { } }

implementation: Objects . requireNonNull ( RPC_CLIENT_INITIALIZER ) ; log . info ( "Searching for more TM..." ) ; try { HashSet < String > cluster = RELIABLE_MESSENGER . queryTMCluster ( ) ; if ( cluster . isEmpty ( ) ) { log . info ( "No more TM." ) ; echoTMClusterSuccessful ( ) ; return ; } clusterCountLatch = new CountDownLatch ( cluster . size ( ) - knownTMClusterSize ) ; log . debug ( "wait connect size is {}" , cluster . size ( ) - knownTMClusterSize ) ; RPC_CLIENT_INITIALIZER . init ( TxManagerHost . parserList ( new ArrayList < > ( cluster ) ) , true ) ; clusterCountLatch . await ( 10 , TimeUnit . SECONDS ) ; echoTMClusterSuccessful ( ) ; } catch ( RpcException | InterruptedException e ) { throw new IllegalStateException ( "There is no normal TM." ) ; }


signature:
public class TMSearcher { /** * 搜索到一个
 * @ return is searched one */
public static boolean searchedOne ( ) { } }

implementation: if ( Objects . nonNull ( clusterCountLatch ) ) { if ( clusterCountLatch . getCount ( ) == 0 ) { return false ; } clusterCountLatch . countDown ( ) ; return true ; } return false ;


signature:
public class DependenciesImportSelector { /** * resolve the spi classes
 * @ param importingClassMetadata importingClassMetadata
 * @ return spi classes */
@ Override @ NonNull public String [ ] selectImports ( @ NonNull AnnotationMetadata importingClassMetadata ) { } }

implementation: boolean enabledTxc = Boolean . valueOf ( Objects . requireNonNull ( importingClassMetadata . getAnnotationAttributes ( EnableDistributedTransaction . class . getName ( ) ) ) . get ( "enableTxc" ) . toString ( ) ) ; List < String > importClasses = new ArrayList < > ( ) ; importClasses . add ( "com.codingapi.txlcn.txmsg.MessageConfiguration" ) ; if ( enabledTxc ) { importClasses . add ( TxcConfiguration . class . getName ( ) ) ; } return importClasses . toArray ( new String [ 0 ] ) ;


signature:
public class ApplicationInformation { /** * 模块标识
 * @ param environment Spring Env
 * @ param serverProperties serverProperties
 * @ return 标识 */
public static String modId ( ConfigurableEnvironment environment , ServerProperties serverProperties ) { } }

implementation: String applicationName = environment . getProperty ( "spring.application.name" ) ; applicationName = StringUtils . hasText ( applicationName ) ? applicationName : "application" ; return applicationName + ":" + serverPort ( serverProperties ) ;