signature:
public class API { /** * Asynchronously receive a response .
 * @ param consume if < code > true < / code > , will consume the service request
 * so it is not accessible with the same function call in
 * the future
 * @ return the response
 * @ throws InvalidInputException invalid input to internal function call
 * @ throws MessageDecodingException service messaging failure
 * @ throws TerminateException service execution must terminate */
public Response recv_async ( final boolean consume ) throws InvalidInputException , MessageDecodingException , TerminateException { } }

implementation: return recv_async ( this . timeout_sync , TransIdNull , consume ) ;


signature:
public class API { /** * Asynchronously receive a response .
 * @ param trans _ id the transaction ID to receive
 * @ param consume if < code > true < / code > , will consume the service request
 * so it is not accessible with the same function call in
 * the future
 * @ return the response
 * @ throws InvalidInputException invalid input to internal function call
 * @ throws MessageDecodingException service messaging failure
 * @ throws TerminateException service execution must terminate */
public Response recv_async ( final byte [ ] trans_id , final boolean consume ) throws InvalidInputException , MessageDecodingException , TerminateException { } }

implementation: return recv_async ( this . timeout_sync , trans_id , consume ) ;


signature:
public class API { /** * Asynchronously receive a response .
 * @ param timeout the receive timeout in milliseconds
 * @ param trans _ id the transaction ID to receive
 * @ param consume if < code > true < / code > , will consume the service request
 * so it is not accessible with the same function call in
 * the future
 * @ return the response
 * @ throws InvalidInputException invalid input to internal function call
 * @ throws MessageDecodingException service messaging failure
 * @ throws TerminateException service execution must terminate */
public Response recv_async ( final Integer timeout , final byte [ ] trans_id , final boolean consume ) throws InvalidInputException , MessageDecodingException , TerminateException { } }

implementation: try { OtpOutputStream recv_async = new OtpOutputStream ( ) ; recv_async . write ( OtpExternal . versionTag ) ; final OtpErlangObject [ ] tuple = { new OtpErlangAtom ( "recv_async" ) , new OtpErlangUInt ( timeout ) , new OtpErlangBinary ( trans_id ) , consume ? new OtpErlangAtom ( "true" ) : new OtpErlangAtom ( "false" ) } ; recv_async . write_any ( new OtpErlangTuple ( tuple ) ) ; send ( recv_async ) ; return ( Response ) poll_request ( null , false ) ; } catch ( OtpErlangRangeException e ) { e . printStackTrace ( API . err ) ; return null ; }


signature:
public class API { /** * Blocks to process incoming CloudI service requests
 * @ param timeout the block timeout in milliseconds ( - 1 is infinity )
 * @ return a boolean to determine if a timeout occurred
 * @ throws InvalidInputException invalid input to internal function call
 * @ throws MessageDecodingException service messaging failure
 * @ throws TerminateException service execution must terminate */
public boolean poll ( final int timeout ) throws InvalidInputException , MessageDecodingException , TerminateException { } }

implementation: if ( Boolean . TRUE == poll_request ( timeout , true ) ) return true ; return false ;


signature:
public class API { /** * Shutdown the service successfully
 * @ param reason the shutdown reason */
public void shutdown ( final String reason ) { } }

implementation: OtpOutputStream shutdown = new OtpOutputStream ( ) ; shutdown . write ( OtpExternal . versionTag ) ; final OtpErlangObject [ ] tuple = { new OtpErlangAtom ( "shutdown" ) , new OtpErlangString ( reason ) } ; shutdown . write_any ( new OtpErlangTuple ( tuple ) ) ; send ( shutdown ) ;


signature:
public class AExceptionFilter { /** * TODO make specific Throwables contributable ? */
public static boolean requiresNonLocalHandling ( Throwable th ) { } }

implementation: return th instanceof VirtualMachineError || th instanceof ThreadDeath || th instanceof InterruptedException || th instanceof LinkageError ;


signature:
public class AExceptionFilter { /** * This method checks if a given Throwable is fit for local handling , returning it if it is and
 * throwing it otherwise . */
public static < T extends Throwable > T forLocalHandling ( T th ) { } }

implementation: if ( requiresNonLocalHandling ( th ) ) { AUnchecker . throwUnchecked ( th ) ; } return th ;


signature:
public class ForkJoinPool { /** * Acquires the runState lock ; returns current ( locked ) runState . */
private int lockRunState ( ) { } }

implementation: int rs ; return ( ( ( ( rs = runState ) & RSLOCK ) != 0 || ! U . compareAndSwapInt ( this , RUNSTATE , rs , rs |= RSLOCK ) ) ? awaitRunStateLock ( ) : rs ) ;


signature:
public class ForkJoinPool { /** * Spins and / or blocks until runstate lock is available . See
 * above for explanation . */
private int awaitRunStateLock ( ) { } }

implementation:
Object lock ; boolean wasInterrupted = false ; for ( int spins = SPINS , r = 0 , rs , ns ; ; ) { if ( ( ( rs = runState ) & RSLOCK ) == 0 ) { if ( U . compareAndSwapInt ( this , RUNSTATE , rs , ns = rs | RSLOCK ) ) { if ( wasInterrupted ) { try { Thread . currentThread ( ) . interrupt ( ) ; } catch ( SecurityException ignore ) { } } return ns ; } } else if ( r == 0 ) r = ThreadLocalRandomHelper . nextSecondarySeed ( ) ; else if ( spins > 0 ) { r ^= r << 6 ; r ^= r >>> 21 ; r ^= r << 7 ; // xorshift
if ( r >= 0 ) -- spins ; } else if ( ( rs & STARTED ) == 0 || ( lock = stealCounter ) == null ) Thread . yield ( ) ; // initialization race
else if ( U . compareAndSwapInt ( this , RUNSTATE , rs , rs | RSIGNAL ) ) { synchronized ( lock ) { if ( ( runState & RSIGNAL ) != 0 ) { try { lock . wait ( ) ; } catch ( InterruptedException ie ) { if ( ! ( Thread . currentThread ( ) instanceof ForkJoinWorkerThread ) ) wasInterrupted = true ; } } else lock . notifyAll ( ) ; } } }


signature:
public class ForkJoinPool { /** * Unlocks and sets runState to newRunState .
 * @ param oldRunState a value returned from lockRunState
 * @ param newRunState the next value ( must have lock bit clear ) . */
private void unlockRunState ( int oldRunState , int newRunState ) { } }

implementation:
if ( ! U . compareAndSwapInt ( this , RUNSTATE , oldRunState , newRunState ) ) { Object lock = stealCounter ; runState = newRunState ; // clears RSIGNAL bit
if ( lock != null ) synchronized ( lock ) { lock . notifyAll ( ) ; } }


signature:
public class ForkJoinPool { /** * Tries to construct and start one worker . Assumes that total
 * count has already been incremented as a reservation . Invokes
 * deregisterWorker on any failure .
 * @ return true if successful */
private boolean createWorker ( ) { } }

implementation: ForkJoinWorkerThreadFactory fac = factory ; Throwable ex = null ; ForkJoinWorkerThread wt = null ; try { if ( fac != null && ( wt = fac . newThread ( this ) ) != null ) { wt . start ( ) ; return true ; } } catch ( Throwable rex ) { ex = rex ; } deregisterWorker ( wt , ex ) ; return false ;


signature:
public class ForkJoinPool { /** * Tries to add one worker , incrementing ctl counts before doing
 * so , relying on createWorker to back out on failure .
 * @ param c incoming ctl value , with total count negative and no
 * idle workers . On CAS failure , c is refreshed and retried if
 * this holds ( otherwise , a new worker is not needed ) . */
private void tryAddWorker ( long c ) { } }

implementation:
boolean add = false ; do { long nc = ( ( AC_MASK & ( c + AC_UNIT ) ) | ( TC_MASK & ( c + TC_UNIT ) ) ) ; if ( ctl == c ) { int rs , stop ; // check if terminating
if ( ( stop = ( rs = lockRunState ( ) ) & STOP ) == 0 ) add = U . compareAndSwapLong ( this , CTL , c , nc ) ; unlockRunState ( rs , rs & ~ RSLOCK ) ; if ( stop != 0 ) break ; if ( add ) { createWorker ( ) ; break ; } } } while ( ( ( c = ctl ) & ADD_WORKER ) != 0L && ( int ) c == 0 ) ;


signature:
public class ForkJoinPool { /** * Callback from ForkJoinWorkerThread constructor to establish and
 * record its WorkQueue .
 * @ param wt the worker thread
 * @ return the worker ' s queue */
final WorkQueue registerWorker ( ForkJoinWorkerThread wt ) { } }

implementation:
UncaughtExceptionHandler handler ; wt . setDaemon ( true ) ; // configure thread
if ( ( handler = ueh ) != null ) wt . setUncaughtExceptionHandler ( handler ) ; WorkQueue w = new WorkQueue ( this , wt ) ; int i = 0 ; // assign a pool index
int mode = config & MODE_MASK ; int rs = lockRunState ( ) ; try { WorkQueue [ ] ws ; int n ; // skip if no array
if ( ( ws = workQueues ) != null && ( n = ws . length ) > 0 ) { int s = indexSeed += SEED_INCREMENT ; // unlikely to collide
int m = n - 1 ; i = ( ( s << 1 ) | 1 ) & m ; // odd - numbered indices
if ( ws [ i ] != null ) { // collision
int probes = 0 ; // step by approx half n
int step = ( n <= 4 ) ? 2 : ( ( n >>> 1 ) & EVENMASK ) + 2 ; while ( ws [ i = ( i + step ) & m ] != null ) { if ( ++ probes >= n ) { workQueues = ws = Arrays . copyOf ( ws , n <<= 1 ) ; m = n - 1 ; probes = 0 ; } } } w . hint = s ; // use as random seed
w . config = i | mode ; w . scanState = i ; // publication fence
ws [ i ] = w ; } } finally { unlockRunState ( rs , rs & ~ RSLOCK ) ; } wt . setName ( workerNamePrefix . concat ( Integer . toString ( i >>> 1 ) ) ) ; return w ;


signature:
public class ForkJoinPool { /** * Final callback from terminating worker , as well as upon failure
 * to construct or start a worker . Removes record of worker from
 * array , and adjusts counts . If pool is shutting down , tries to
 * complete termination .
 * @ param wt the worker thread , or null if construction failed
 * @ param ex the exception causing failure , or null if none */
final void deregisterWorker ( ForkJoinWorkerThread wt , Throwable ex ) { } }

implementation:
WorkQueue w = null ; if ( wt != null && ( w = wt . workQueue ) != null ) { WorkQueue [ ] ws ; // remove index from array
int idx = w . config & SMASK ; int rs = lockRunState ( ) ; if ( ( ws = workQueues ) != null && ws . length > idx && ws [ idx ] == w ) ws [ idx ] = null ; unlockRunState ( rs , rs & ~ RSLOCK ) ; } long c ; // decrement counts
do { } while ( ! U . compareAndSwapLong ( this , CTL , c = ctl , ( ( AC_MASK & ( c - AC_UNIT ) ) | ( TC_MASK & ( c - TC_UNIT ) ) | ( SP_MASK & c ) ) ) ) ; if ( w != null ) { w . qlock = - 1 ; // ensure set
w . transferStealCount ( this ) ; w . cancelAll ( ) ; // cancel remaining tasks
} for ( ; ; ) { // possibly replace
WorkQueue [ ] ws ; int m , sp ; if ( tryTerminate ( false , false ) || w == null || w . array == null || ( runState & STOP ) != 0 || ( ws = workQueues ) == null || ( m = ws . length - 1 ) < 0 ) // already terminating
break ; if ( ( sp = ( int ) ( c = ctl ) ) != 0 ) { // wake up replacement
if ( tryRelease ( c , ws [ sp & m ] , AC_UNIT ) ) break ; } else if ( ex != null && ( c & ADD_WORKER ) != 0L ) { tryAddWorker ( c ) ; // create replacement
break ; } else // don ' t need replacement
break ; } if ( ex == null ) // help clean on way out
ForkJoinTask . helpExpungeStaleExceptions ( ) ; else // rethrow
ForkJoinTask . rethrow ( ex ) ;


signature:
public class ForkJoinPool { /** * Tries to create or activate a worker if too few are active .
 * @ param ws the worker array to use to find signallees
 * @ param q a WorkQueue - - if non - null , don ' t retry if now empty */
final void signalWork ( WorkQueue [ ] ws , WorkQueue q ) { } }

implementation:
long c ; int sp , i ; WorkQueue v ; Thread p ; while ( ( c = ctl ) < 0L ) { // too few active
if ( ( sp = ( int ) c ) == 0 ) { // no idle workers
if ( ( c & ADD_WORKER ) != 0L ) // too few workers
tryAddWorker ( c ) ; break ; } if ( ws == null ) // unstarted / terminated
break ; if ( ws . length <= ( i = sp & SMASK ) ) // terminated
break ; if ( ( v = ws [ i ] ) == null ) // terminating
break ; int vs = ( sp + SS_SEQ ) & ~ INACTIVE ; // next scanState
int d = sp - v . scanState ; // screen CAS
long nc = ( UC_MASK & ( c + AC_UNIT ) ) | ( SP_MASK & v . stackPred ) ; if ( d == 0 && U . compareAndSwapLong ( this , CTL , c , nc ) ) { v . scanState = vs ; // activate v
if ( ( p = v . parker ) != null ) U . unpark ( p ) ; break ; } if ( q != null && q . base == q . top ) // no more work
break ; }


signature:
public class ForkJoinPool { /** * Signals and releases worker v if it is top of idle worker
 * stack . This performs a one - shot version of signalWork only if
 * there is ( apparently ) at least one idle worker .
 * @ param c incoming ctl value
 * @ param v if non - null , a worker
 * @ param inc the increment to active count ( zero when compensating )
 * @ return true if successful */
private boolean tryRelease ( long c , WorkQueue v , long inc ) { } }

implementation:
int sp = ( int ) c , vs = ( sp + SS_SEQ ) & ~ INACTIVE ; Thread p ; if ( v != null && v . scanState == sp ) { // v is at top of stack
long nc = ( UC_MASK & ( c + inc ) ) | ( SP_MASK & v . stackPred ) ; if ( U . compareAndSwapLong ( this , CTL , c , nc ) ) { v . scanState = vs ; if ( ( p = v . parker ) != null ) U . unpark ( p ) ; return true ; } } return false ;


signature:
public class ForkJoinPool { /** * Top - level runloop for workers , called by ForkJoinWorkerThread . run . */
final void runWorker ( WorkQueue w ) { } }

implementation:
w . growArray ( ) ; // allocate queue
int seed = w . hint ; // initially holds randomization hint
int r = ( seed == 0 ) ? 1 : seed ; // avoid 0 for xorShift
for ( ForkJoinTask < ? > t ; ; ) { if ( ( t = scan ( w , r ) ) != null ) w . runTask ( t ) ; else if ( ! awaitWork ( w , r ) ) break ; r ^= r << 13 ; r ^= r >>> 17 ; r ^= r << 5 ; // xorshift
}


signature:
public class ForkJoinPool { /** * Scans for and tries to steal a top - level task . Scans start at a
 * random location , randomly moving on apparent contention ,
 * otherwise continuing linearly until reaching two consecutive
 * empty passes over all queues with the same checksum ( summing
 * each base index of each queue , that moves on each steal ) , at
 * which point the worker tries to inactivate and then re - scans ,
 * attempting to re - activate ( itself or some other worker ) if
 * finding a task ; otherwise returning null to await work . Scans
 * otherwise touch as little memory as possible , to reduce
 * disruption on other scanning threads .
 * @ param w the worker ( via its WorkQueue )
 * @ param r a random seed
 * @ return a task , or null if none found */
private ForkJoinTask < ? > scan ( WorkQueue w , int r ) { } }

implementation:
WorkQueue [ ] ws ; int m ; if ( ( ws = workQueues ) != null && ( m = ws . length - 1 ) > 0 && w != null ) { int ss = w . scanState ; // initially non - negative
for ( int origin = r & m , k = origin , oldSum = 0 , checkSum = 0 ; ; ) { WorkQueue q ; ForkJoinTask < ? > [ ] a ; ForkJoinTask < ? > t ; int b , n ; long c ; if ( ( q = ws [ k ] ) != null ) { if ( ( n = ( b = q . base ) - q . top ) < 0 && ( a = q . array ) != null ) { // non - empty
long i = ( ( ( a . length - 1 ) & b ) << ASHIFT ) + ABASE ; if ( ( t = ( ( ForkJoinTask < ? > ) U . getObjectVolatile ( a , i ) ) ) != null && q . base == b ) { if ( ss >= 0 ) { if ( U . compareAndSwapObject ( a , i , t , null ) ) { q . base = b + 1 ; if ( n < - 1 ) // signal others
signalWork ( ws , q ) ; return t ; } } else if ( oldSum == 0 && // try to activate
w . scanState < 0 ) tryRelease ( c = ctl , ws [ m & ( int ) c ] , AC_UNIT ) ; } if ( ss < 0 ) // refresh
ss = w . scanState ; r ^= r << 1 ; r ^= r >>> 3 ; r ^= r << 10 ; origin = k = r & m ; // move and rescan
oldSum = checkSum = 0 ; continue ; } checkSum += b ; } if ( ( k = ( k + 1 ) & m ) == origin ) { // continue until stable
if ( ( ss >= 0 || ( ss == ( ss = w . scanState ) ) ) && oldSum == ( oldSum = checkSum ) ) { if ( ss < 0 || w . qlock < 0 ) // already inactive
break ; int ns = ss | INACTIVE ; // try to inactivate
long nc = ( ( SP_MASK & ns ) | ( UC_MASK & ( ( c = ctl ) - AC_UNIT ) ) ) ; w . stackPred = ( int ) c ; // hold prev stack top
U . putInt ( w , QSCANSTATE , ns ) ; if ( U . compareAndSwapLong ( this , CTL , c , nc ) ) ss = ns ; else w . scanState = ss ; // back out
} checkSum = 0 ; } } } return null ;


signature:
public class ForkJoinPool { /** * Possibly blocks worker w waiting for a task to steal , or
 * returns false if the worker should terminate . If inactivating
 * w has caused the pool to become quiescent , checks for pool
 * termination , and , so long as this is not the only worker , waits
 * for up to a given duration . On timeout , if ctl has not
 * changed , terminates the worker , which will in turn wake up
 * another worker to possibly repeat this process .
 * @ param w the calling worker
 * @ param r a random seed ( for spins )
 * @ return false if the worker should terminate */
private boolean awaitWork ( WorkQueue w , int r ) { } }

implementation:
if ( w == null || w . qlock < 0 ) // w is terminating
return false ; for ( int pred = w . stackPred , spins = SPINS , ss ; ; ) { if ( ( ss = w . scanState ) >= 0 ) break ; else if ( spins > 0 ) { r ^= r << 6 ; r ^= r >>> 21 ; r ^= r << 7 ; if ( r >= 0 && -- spins == 0 ) { // randomize spins
WorkQueue v ; WorkQueue [ ] ws ; int s , j ; AtomicLong sc ; if ( pred != 0 && ( ws = workQueues ) != null && ( j = pred & SMASK ) < ws . length && ( v = ws [ j ] ) != null && // see if pred parking
( v . parker == null || v . scanState >= 0 ) ) spins = SPINS ; // continue spinning
} } else if ( w . qlock < 0 ) // recheck after spins
return false ; else if ( ! Thread . interrupted ( ) ) { long c , prevctl , parkTime , deadline ; int ac = ( int ) ( ( c = ctl ) >> AC_SHIFT ) + ( config & SMASK ) ; if ( ( ac <= 0 && tryTerminate ( false , false ) ) || ( runState & STOP ) != 0 ) // pool terminating
return false ; if ( ac <= 0 && ss == ( int ) c ) { // is last waiter
prevctl = ( UC_MASK & ( c + AC_UNIT ) ) | ( SP_MASK & pred ) ; int t = ( short ) ( c >>> TC_SHIFT ) ; // shrink excess spares
if ( t > 2 && U . compareAndSwapLong ( this , CTL , c , prevctl ) ) return false ; // else use timed wait
parkTime = IDLE_TIMEOUT * ( ( t >= 0 ) ? 1 : 1 - t ) ; deadline = System . nanoTime ( ) + parkTime - TIMEOUT_SLOP ; } else prevctl = parkTime = deadline = 0L ; Thread wt = Thread . currentThread ( ) ; U . putObject ( wt , PARKBLOCKER , this ) ; // emulate LockSupport
w . parker = wt ; if ( w . scanState < 0 && ctl == c ) // recheck before park
U . park ( false , parkTime ) ; U . putOrderedObject ( w , QPARKER , null ) ; U . putObject ( wt , PARKBLOCKER , null ) ; if ( w . scanState >= 0 ) break ; if ( parkTime != 0L && ctl == c && deadline - System . nanoTime ( ) <= 0L && U . compareAndSwapLong ( this , CTL , c , prevctl ) ) return false ; // shrink pool
} } return true ;


signature:
public class ForkJoinPool { /** * Tries to steal and run tasks within the target ' s computation .
 * Uses a variant of the top - level algorithm , restricted to tasks
 * with the given task as ancestor : It prefers taking and running
 * eligible tasks popped from the worker ' s own queue ( via
 * popCC ) . Otherwise it scans others , randomly moving on
 * contention or execution , deciding to give up based on a
 * checksum ( via return codes frob pollAndExecCC ) . The maxTasks
 * argument supports external usages ; internal calls use zero ,
 * allowing unbounded steps ( external calls trap non - positive
 * values ) .
 * @ param w caller
 * @ param maxTasks if non - zero , the maximum number of other tasks to run
 * @ return task status on exit */
final int helpComplete ( WorkQueue w , CountedCompleter < ? > task , int maxTasks ) { } }

implementation:
WorkQueue [ ] ws ; int s = 0 , m ; if ( ( ws = workQueues ) != null && ( m = ws . length - 1 ) >= 0 && task != null && w != null ) { int mode = w . config ; // for popCC
int r = w . hint ^ w . top ; // arbitrary seed for origin
int origin = r & m ; // first queue to scan
int h = 1 ; // 1 : ran , > 1 : contended , < 0 : hash
for ( int k = origin , oldSum = 0 , checkSum = 0 ; ; ) { CountedCompleter < ? > p ; WorkQueue q ; if ( ( s = task . status ) < 0 ) break ; if ( h == 1 && ( p = w . popCC ( task , mode ) ) != null ) { p . doExec ( ) ; // run local task
if ( maxTasks != 0 && -- maxTasks == 0 ) break ; origin = k ; // reset
oldSum = checkSum = 0 ; } else { // poll other queues
if ( ( q = ws [ k ] ) == null ) h = 0 ; else if ( ( h = q . pollAndExecCC ( task ) ) < 0 ) checkSum += h ; if ( h > 0 ) { if ( h == 1 && maxTasks != 0 && -- maxTasks == 0 ) break ; r ^= r << 13 ; r ^= r >>> 17 ; r ^= r << 5 ; // xorshift
origin = k = r & m ; // move and restart
oldSum = checkSum = 0 ; } else if ( ( k = ( k + 1 ) & m ) == origin ) { if ( oldSum == ( oldSum = checkSum ) ) break ; checkSum = 0 ; } } } } return s ;


signature:
public class ForkJoinPool { /** * Tries to decrement active count ( sometimes implicitly ) and
 * possibly release or create a compensating worker in preparation
 * for blocking . Returns false ( retryable by caller ) , on
 * contention , detected staleness , instability , or termination .
 * @ param w caller */
private boolean tryCompensate ( WorkQueue w ) { } }

implementation:
boolean canBlock ; WorkQueue [ ] ws ; long c ; int m , pc , sp ; if ( w == null || w . qlock < 0 || // caller terminating
( ws = workQueues ) == null || ( m = ws . length - 1 ) <= 0 || ( pc = config & SMASK ) == 0 ) // parallelism disabled
canBlock = false ; else if ( ( sp = ( int ) ( c = ctl ) ) != 0 ) // release idle worker
canBlock = tryRelease ( c , ws [ sp & m ] , 0L ) ; else { int ac = ( int ) ( c >> AC_SHIFT ) + pc ; int tc = ( short ) ( c >> TC_SHIFT ) + pc ; int nbusy = 0 ; // validate saturation
for ( int i = 0 ; i <= m ; ++ i ) { // two passes of odd indices
WorkQueue v ; if ( ( v = ws [ ( ( i << 1 ) | 1 ) & m ] ) != null ) { if ( ( v . scanState & SCANNING ) != 0 ) break ; ++ nbusy ; } } if ( nbusy != ( tc << 1 ) || ctl != c ) canBlock = false ; // unstable or stale
else if ( tc >= pc && ac > 1 && w . isEmpty ( ) ) { long nc = ( ( AC_MASK & ( c - AC_UNIT ) ) | ( ~ AC_MASK & c ) ) ; // uncompensated
canBlock = U . compareAndSwapLong ( this , CTL , c , nc ) ; } else if ( tc >= MAX_CAP || ( this == common && tc >= pc + commonMaxSpares ) ) throw new RejectedExecutionException ( "Thread limit exceeded replacing blocked worker" ) ; else { // similar to tryAddWorker
boolean add = false ; int rs ; // CAS within lock
long nc = ( ( AC_MASK & c ) | ( TC_MASK & ( c + TC_UNIT ) ) ) ; if ( ( ( rs = lockRunState ( ) ) & STOP ) == 0 ) add = U . compareAndSwapLong ( this , CTL , c , nc ) ; unlockRunState ( rs , rs & ~ RSLOCK ) ; canBlock = add && createWorker ( ) ; // throws on exception
} } return canBlock ;


signature:
public class ForkJoinPool { /** * Returns a cheap heuristic guide for task partitioning when
 * programmers , frameworks , tools , or languages have little or no
 * idea about task granularity . In essence , by offering this
 * method , we ask users only about tradeoffs in overhead vs
 * expected throughput and its variance , rather than how finely to
 * partition tasks .
 * In a steady state strict ( tree - structured ) computation , each
 * thread makes available for stealing enough tasks for other
 * threads to remain active . Inductively , if all threads play by
 * the same rules , each thread should make available only a
 * constant number of tasks .
 * The minimum useful constant is just 1 . But using a value of 1
 * would require immediate replenishment upon each steal to
 * maintain enough tasks , which is infeasible . Further ,
 * partitionings / granularities of offered tasks should minimize
 * steal rates , which in general means that threads nearer the top
 * of computation tree should generate more than those nearer the
 * bottom . In perfect steady state , each thread is at
 * approximately the same level of computation tree . However ,
 * producing extra tasks amortizes the uncertainty of progress and
 * diffusion assumptions .
 * So , users will want to use values larger ( but not much larger )
 * than 1 to both smooth over transient shortages and hedge
 * against uneven progress ; as traded off against the cost of
 * extra task overhead . We leave the user to pick a threshold
 * value to compare with the results of this call to guide
 * decisions , but recommend values such as 3.
 * When all threads are active , it is on average OK to estimate
 * surplus strictly locally . In steady - state , if one thread is
 * maintaining say 2 surplus tasks , then so are others . So we can
 * just use estimated queue length . However , this strategy alone
 * leads to serious mis - estimates in some non - steady - state
 * conditions ( ramp - up , ramp - down , other stalls ) . We can detect
 * many of these by further considering the number of " idle "
 * threads , that are known to have zero queued tasks , so
 * compensate by a factor of ( # idle / # active ) threads . */
static int getSurplusQueuedTaskCount ( ) { } }

implementation: Thread t ; ForkJoinWorkerThread wt ; ForkJoinPool pool ; WorkQueue q ; if ( ( ( t = Thread . currentThread ( ) ) instanceof ForkJoinWorkerThread ) ) { int p = ( pool = ( wt = ( ForkJoinWorkerThread ) t ) . pool ) . config & SMASK ; int n = ( q = wt . workQueue ) . top - q . base ; int a = ( int ) ( pool . ctl >> AC_SHIFT ) + p ; return n - ( a > ( p >>>= 1 ) ? 0 : a > ( p >>>= 1 ) ? 1 : a > ( p >>>= 1 ) ? 2 : a > ( p >>>= 1 ) ? 4 : 8 ) ; } return 0 ;


signature:
public class ForkJoinPool { /** * Possibly initiates and / or completes termination .
 * @ param now if true , unconditionally terminate , else only
 * if no work and no active workers
 * @ param enable if true , enable shutdown when next possible
 * @ return true if now terminating or terminated */
private boolean tryTerminate ( boolean now , boolean enable ) { } }

implementation:
int rs ; if ( this == common ) // cannot shut down
return false ; if ( ( rs = runState ) >= 0 ) { if ( ! enable ) return false ; rs = lockRunState ( ) ; // enter SHUTDOWN phase
unlockRunState ( rs , ( rs & ~ RSLOCK ) | SHUTDOWN ) ; } if ( ( rs & STOP ) == 0 ) { if ( ! now ) { // check quiescence
for ( long oldSum = 0L ; ; ) { // repeat until stable
WorkQueue [ ] ws ; WorkQueue w ; int m , b ; long c ; long checkSum = ctl ; if ( ( int ) ( checkSum >> AC_SHIFT ) + ( config & SMASK ) > 0 ) return false ; // still active workers
if ( ( ws = workQueues ) == null || ( m = ws . length - 1 ) <= 0 ) break ; // check queues
for ( int i = 0 ; i <= m ; ++ i ) { if ( ( w = ws [ i ] ) != null ) { if ( ( b = w . base ) != w . top || w . scanState >= 0 || w . currentSteal != null ) { tryRelease ( c = ctl , ws [ m & ( int ) c ] , AC_UNIT ) ; return false ; // arrange for recheck
} checkSum += b ; if ( ( i & 1 ) == 0 ) w . qlock = - 1 ; // try to disable external
} } if ( oldSum == ( oldSum = checkSum ) ) break ; } } if ( ( runState & STOP ) == 0 ) { rs = lockRunState ( ) ; // enter STOP phase
unlockRunState ( rs , ( rs & ~ RSLOCK ) | STOP ) ; } } int pass = 0 ; // 3 passes to help terminate
for ( long oldSum = 0L ; ; ) { // or until done or stable
WorkQueue [ ] ws ; WorkQueue w ; ForkJoinWorkerThread wt ; int m ; long checkSum = ctl ; if ( ( short ) ( checkSum >>> TC_SHIFT ) + ( config & SMASK ) <= 0 || ( ws = workQueues ) == null || ( m = ws . length - 1 ) <= 0 ) { if ( ( runState & TERMINATED ) == 0 ) { rs = lockRunState ( ) ; // done
unlockRunState ( rs , ( rs & ~ RSLOCK ) | TERMINATED ) ; synchronized ( this ) { notifyAll ( ) ; } // for awaitTermination
} break ; } for ( int i = 0 ; i <= m ; ++ i ) { if ( ( w = ws [ i ] ) != null ) { checkSum += w . base ; w . qlock = - 1 ; // try to disable
if ( pass > 0 ) { w . cancelAll ( ) ; // clear queue
if ( pass > 1 && ( wt = w . owner ) != null ) { if ( ! wt . isInterrupted ( ) ) { try { // unblock join
wt . interrupt ( ) ; } catch ( Throwable ignore ) { } } if ( w . scanState < 0 ) U . unpark ( wt ) ; // wake up
} } } } if ( checkSum != oldSum ) { // unstable
oldSum = checkSum ; pass = 0 ; } else if ( pass > 3 && pass > m ) // can ' t further help
break ; else if ( ++ pass > 1 ) { // try to dequeue
long c ; int j = 0 , sp ; // bound attempts
while ( j ++ <= m && ( sp = ( int ) ( c = ctl ) ) != 0 ) tryRelease ( c , ws [ sp & m ] , AC_UNIT ) ; } } return true ;


signature:
public class ForkJoinPool { /** * Full version of externalPush , handling uncommon cases , as well
 * as performing secondary initialization upon the first
 * submission of the first task to the pool . It also detects
 * first submission by an external thread and creates a new shared
 * queue if the one at index if empty or contended .
 * @ param task the task . Caller must ensure non - null . */
private void externalSubmit ( ForkJoinTask < ? > task ) { } }

implementation:
int r ; // initialize caller ' s probe
if ( ( r = ThreadLocalRandomHelper . getProbe ( ) ) == 0 ) { ThreadLocalRandomHelper . localInit ( ) ; r = ThreadLocalRandomHelper . getProbe ( ) ; } for ( ; ; ) { WorkQueue [ ] ws ; WorkQueue q ; int rs , m , k ; boolean move = false ; if ( ( rs = runState ) < 0 ) { tryTerminate ( false , false ) ; // help terminate
throw new RejectedExecutionException ( ) ; } else if ( ( rs & STARTED ) == 0 || // initialize
( ( ws = workQueues ) == null || ( m = ws . length - 1 ) < 0 ) ) { int ns = 0 ; rs = lockRunState ( ) ; try { if ( ( rs & STARTED ) == 0 ) { U . compareAndSwapObject ( this , STEALCOUNTER , null , new AtomicLong ( ) ) ; // create workQueues array with size a power of two
int p = config & SMASK ; // ensure at least 2 slots
int n = ( p > 1 ) ? p - 1 : 1 ; n |= n >>> 1 ; n |= n >>> 2 ; n |= n >>> 4 ; n |= n >>> 8 ; n |= n >>> 16 ; n = ( n + 1 ) << 1 ; workQueues = new WorkQueue [ n ] ; ns = STARTED ; } } finally { unlockRunState ( rs , ( rs & ~ RSLOCK ) | ns ) ; } } else if ( ( q = ws [ k = r & m & SQMASK ] ) != null ) { if ( q . qlock == 0 && U . compareAndSwapInt ( q , QLOCK , 0 , 1 ) ) { ForkJoinTask < ? > [ ] a = q . array ; int s = q . top ; boolean submitted = false ; // initial submission or resizing
try { // locked version of push
if ( ( a != null && a . length > s + 1 - q . base ) || ( a = q . growArray ( ) ) != null ) { int j = ( ( ( a . length - 1 ) & s ) << ASHIFT ) + ABASE ; U . putOrderedObject ( a , j , task ) ; U . putOrderedInt ( q , QTOP , s + 1 ) ; submitted = true ; } } finally { U . compareAndSwapInt ( q , QLOCK , 1 , 0 ) ; } if ( submitted ) { signalWork ( ws , q ) ; return ; } } move = true ; // move on failure
} else if ( ( ( rs = runState ) & RSLOCK ) == 0 ) { // create new queue
q = new WorkQueue ( this , null ) ; q . hint = r ; q . config = k | SHARED_QUEUE ; q . scanState = INACTIVE ; rs = lockRunState ( ) ; // publish index
if ( rs > 0 && ( ws = workQueues ) != null && k < ws . length && ws [ k ] == null ) ws [ k ] = q ; // else terminated
unlockRunState ( rs , rs & ~ RSLOCK ) ; } else move = true ; // move if busy
if ( move ) r = ThreadLocalRandomHelper . advanceProbe ( r ) ; }


signature:
public class ForkJoinPool { /** * Tries to add the given task to a submission queue at
 * submitter ' s current queue . Only the ( vastly ) most common path
 * is directly handled in this method , while screening for need
 * for externalSubmit .
 * @ param task the task . Caller must ensure non - null . */
final void externalPush ( ForkJoinTask < ? > task ) { } }

implementation: WorkQueue [ ] ws ; WorkQueue q ; int m ; int r = ThreadLocalRandomHelper . getProbe ( ) ; int rs = runState ; if ( ( ws = workQueues ) != null && ( m = ( ws . length - 1 ) ) >= 0 && ( q = ws [ m & r & SQMASK ] ) != null && r != 0 && rs > 0 && U . compareAndSwapInt ( q , QLOCK , 0 , 1 ) ) { ForkJoinTask < ? > [ ] a ; int am , n , s ; if ( ( a = q . array ) != null && ( am = a . length - 1 ) > ( n = ( s = q . top ) - q . base ) ) { int j = ( ( am & s ) << ASHIFT ) + ABASE ; U . putOrderedObject ( a , j , task ) ; U . putOrderedInt ( q , QTOP , s + 1 ) ; U . putIntVolatile ( q , QLOCK , 0 ) ; if ( n <= 1 ) signalWork ( ws , q ) ; return ; } U . compareAndSwapInt ( q , QLOCK , 1 , 0 ) ; } externalSubmit ( task ) ;


signature:
public class ForkJoinPool { /** * Returns common pool queue for an external thread . */
static WorkQueue commonSubmitterQueue ( ) { } }

implementation: ForkJoinPool p = common ; int r = ThreadLocalRandomHelper . getProbe ( ) ; WorkQueue [ ] ws ; int m ; return ( p != null && ( ws = p . workQueues ) != null && ( m = ws . length - 1 ) >= 0 ) ? ws [ m & r & SQMASK ] : null ;


signature:
public class ForkJoinPool { /** * Performs tryUnpush for an external submitter : Finds queue ,
 * locks if apparently non - empty , validates upon locking , and
 * adjusts top . Each check can fail but rarely does . */
final boolean tryExternalUnpush ( ForkJoinTask < ? > task ) { } }

implementation: WorkQueue [ ] ws ; WorkQueue w ; ForkJoinTask < ? > [ ] a ; int m , s ; int r = ThreadLocalRandomHelper . getProbe ( ) ; if ( ( ws = workQueues ) != null && ( m = ws . length - 1 ) >= 0 && ( w = ws [ m & r & SQMASK ] ) != null && ( a = w . array ) != null && ( s = w . top ) != w . base ) { long j = ( ( ( a . length - 1 ) & ( s - 1 ) ) << ASHIFT ) + ABASE ; if ( U . compareAndSwapInt ( w , QLOCK , 0 , 1 ) ) { if ( w . top == s && w . array == a && U . getObject ( a , j ) == task && U . compareAndSwapObject ( a , j , task , null ) ) { U . putOrderedInt ( w , QTOP , s - 1 ) ; U . putOrderedInt ( w , QLOCK , 0 ) ; return true ; } U . compareAndSwapInt ( w , QLOCK , 1 , 0 ) ; } } return false ;


signature:
public class ForkJoinPool { /** * Performs helpComplete for an external submitter . */
final int externalHelpComplete ( CountedCompleter < ? > task , int maxTasks ) { } }

implementation: WorkQueue [ ] ws ; int n ; int r = ThreadLocalRandomHelper . getProbe ( ) ; return ( ( ws = workQueues ) == null || ( n = ws . length ) == 0 ) ? 0 : helpComplete ( ws [ ( n - 1 ) & r & SQMASK ] , task , maxTasks ) ;


signature:
public class ForkJoinPool { /** * Performs the given task , returning its result upon completion .
 * If the computation encounters an unchecked Exception or Error ,
 * it is rethrown as the outcome of this invocation . Rethrown
 * exceptions behave in the same way as regular exceptions , but ,
 * when possible , contain stack traces ( as displayed for example
 * using { @ code ex . printStackTrace ( ) } ) of both the current thread
 * as well as the thread actually encountering the exception ;
 * minimally only the latter .
 * @ param task the task
 * @ param < T > the type of the task ' s result
 * @ return the task ' s result
 * @ throws NullPointerException if the task is null
 * @ throws RejectedExecutionException if the task cannot be
 * scheduled for execution */
public < T > T invoke ( ForkJoinTask < T > task ) { } }

implementation: if ( task == null ) throw new NullPointerException ( ) ; externalPush ( task ) ; return task . join ( ) ;


signature:
public class ForkJoinPool { /** * Submits a ForkJoinTask for execution .
 * @ param task the task to submit
 * @ param < T > the type of the task ' s result
 * @ return the task
 * @ throws NullPointerException if the task is null
 * @ throws RejectedExecutionException if the task cannot be
 * scheduled for execution */
public < T > ForkJoinTask < T > submit ( ForkJoinTask < T > task ) { } }

implementation: if ( task == null ) throw new NullPointerException ( ) ; externalPush ( task ) ; return task ;


signature:
public class ForkJoinPool { /** * Returns an estimate of the total number of tasks stolen from
 * one thread ' s work queue by another . The reported value
 * underestimates the actual total number of steals when the pool
 * is not quiescent . This value may be useful for monitoring and
 * tuning fork / join programs : in general , steal counts should be
 * high enough to keep threads busy , but low enough to avoid
 * overhead and contention across threads .
 * @ return the number of steals */
public long getStealCount ( ) { } }

implementation: AtomicLong sc = stealCounter ; long count = ( sc == null ) ? 0L : sc . get ( ) ; WorkQueue [ ] ws ; WorkQueue w ; if ( ( ws = workQueues ) != null ) { for ( int i = 1 ; i < ws . length ; i += 2 ) { if ( ( w = ws [ i ] ) != null ) count += w . nsteals ; } } return count ;


signature:
public class ForkJoinPool { /** * Creates and returns the common pool , respecting user settings
 * specified via system properties . */
private static ForkJoinPool makeCommonPool ( ) { } }

implementation:
int parallelism = - 1 ; ForkJoinWorkerThreadFactory factory = null ; UncaughtExceptionHandler handler = null ; try { // ignore exceptions in accessing / parsing properties
String pp = System . getProperty ( "java.util.concurrent.ForkJoinPool.common.parallelism" ) ; String fp = System . getProperty ( "java.util.concurrent.ForkJoinPool.common.threadFactory" ) ; String hp = System . getProperty ( "java.util.concurrent.ForkJoinPool.common.exceptionHandler" ) ; String mp = System . getProperty ( "java.util.concurrent.ForkJoinPool.common.maximumSpares" ) ; if ( pp != null ) parallelism = Integer . parseInt ( pp ) ; if ( fp != null ) factory = ( ( ForkJoinWorkerThreadFactory ) ClassLoader . getSystemClassLoader ( ) . loadClass ( fp ) . newInstance ( ) ) ; if ( hp != null ) handler = ( ( UncaughtExceptionHandler ) ClassLoader . getSystemClassLoader ( ) . loadClass ( hp ) . newInstance ( ) ) ; if ( mp != null ) commonMaxSpares = Integer . parseInt ( mp ) ; } catch ( Exception ignore ) { } if ( factory == null ) { if ( System . getSecurityManager ( ) == null ) factory = defaultForkJoinWorkerThreadFactory ; else // use security - managed default
factory = new InnocuousForkJoinWorkerThreadFactory ( ) ; } if ( parallelism < 0 && // default 1 less than # cores
( parallelism = Runtime . getRuntime ( ) . availableProcessors ( ) - 1 ) <= 0 ) parallelism = 1 ; if ( parallelism > MAX_CAP ) parallelism = MAX_CAP ; return new ForkJoinPool ( parallelism , factory , handler , LIFO_QUEUE , "ForkJoinPool.commonPool-worker-" ) ;


signature: public class StaticFutureMethods { public static < R , T , E extends Throwable > AFuture < AList < R > > traverse ( AThreadPool tp , Iterable < T > values , AFunction1 < T , AFuture < R > , E > f ) throws E { } }

implementation: final List < AFuture < R > > result = new ArrayList < > ( ) ; for ( T o : values ) { result . add ( f . apply ( o ) ) ; } return lift ( tp , result ) ;


signature:
public class SharedQueueNonBlockingImpl { /** * Add a new task to the top of the shared queue , incrementing ' top ' . */
@ Override public void push ( Runnable task ) { } }

implementation:
while ( true ) { final long _base = UNSAFE . getLongVolatile ( this , OFFS_BASE ) ; final long _top = top ; if ( _top == _base + mask ) { throw new RejectedExecutionExceptionWithoutStacktrace ( "Queue overflow" ) ; } final long taskOffset = taskOffset ( _top ) ; if ( UNSAFE . compareAndSwapObject ( tasks , taskOffset , null , task ) ) { // if the publishing thread is interrupted here , other publishers will effectively do a spin wait
if ( ! UNSAFE . compareAndSwapLong ( this , OFFS_TOP , _top , _top + 1 ) ) { // there was a buffer wrap - around in the meantime - - > undo the CAS ' put ' operation and try again
UNSAFE . putObjectVolatile ( tasks , taskOffset , null ) ; continue ; } if ( _top - _base <= 1 ) { pool . onAvailableTask ( ) ; } break ; } }


signature:
public class ForkJoinTask { /** * Waits if necessary for at most the given time for the computation
 * to complete , and then retrieves its result , if available .
 * @ param timeout the maximum time to wait
 * @ param unit the time unit of the timeout argument
 * @ return the computed result
 * @ throws CancellationException if the computation was cancelled
 * @ throws ExecutionException if the computation threw an
 * exception
 * @ throws InterruptedException if the current thread is not a
 * member of a ForkJoinPool and was interrupted while waiting
 * @ throws TimeoutException if the wait timed out */
public final V get ( long timeout , TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException { } }

implementation:
int s ; long nanos = unit . toNanos ( timeout ) ; if ( Thread . interrupted ( ) ) throw new InterruptedException ( ) ; if ( ( s = status ) >= 0 && nanos > 0L ) { long d = System . nanoTime ( ) + nanos ; long deadline = ( d == 0L ) ? 1L : d ; // avoid 0
Thread t = Thread . currentThread ( ) ; if ( t instanceof ForkJoinWorkerThread ) { ForkJoinWorkerThread wt = ( ForkJoinWorkerThread ) t ; s = wt . pool . awaitJoin ( wt . workQueue , this , deadline ) ; } else if ( ( s = ( ( this instanceof CountedCompleter ) ? ForkJoinPool . common . externalHelpComplete ( ( CountedCompleter < ? > ) this , 0 ) : ForkJoinPool . common . tryExternalUnpush ( this ) ? doExec ( ) : 0 ) ) >= 0 ) { long ns , ms ; // measure in nanosecs , but wait in millisecs
while ( ( s = status ) >= 0 && ( ns = deadline - System . nanoTime ( ) ) > 0L ) { if ( ( ms = TimeUnit . NANOSECONDS . toMillis ( ns ) ) > 0L && U . compareAndSwapInt ( this , STATUS , s , s | SIGNAL ) ) { synchronized ( this ) { if ( status >= 0 ) wait ( ms ) ; // OK to throw InterruptedException
else notifyAll ( ) ; } } } } } if ( s >= 0 ) s = status ; if ( ( s &= DONE_MASK ) != NORMAL ) { Throwable ex ; if ( s == CANCELLED ) throw new CancellationException ( ) ; if ( s != EXCEPTIONAL ) throw new TimeoutException ( ) ; if ( ( ex = getThrowableException ( ) ) != null ) throw new ExecutionException ( ex ) ; } return getRawResult ( ) ;


signature:
public class ABTreeMap { /** * intentionally not volatile : This class is immutable , so recalculating per thread works */
@ SuppressWarnings ( "unchecked" ) public static < K , V > ABTreeMap < K , V > empty ( ABTreeSpec spec ) { } }

implementation: return new LeafNode ( spec , new Object [ 0 ] , new Object [ 0 ] ) ;


signature:
public class ABTreeMap { /** * public Iterable < V > values ( K keyMin , K keyMax ) ; */
@ SuppressWarnings ( "unchecked" ) public ABTreeMap < K , V > updated ( K key , V value ) { } }

implementation:
final UpdateResult result = _updated ( key , value ) ; if ( result . optRight == null ) { return result . left ; } // This is the only place where the tree depth can grow .
// The ' minimum number of children ' constraint does not apply to root nodes .
return new IndexNode ( spec , new Object [ ] { result . separator } , new ABTreeMap [ ] { result . left , result . optRight } ) ;


signature: public class AFutureImpl { @ Override public < S > AFuture < S > map ( AThreadPool tp , AFunction1 < T , S , ? > f ) { } }

implementation: final AFutureImpl < S > result = new AFutureImpl < > ( tp ) ; onComplete ( tp , v -> { try { result . complete ( v . map ( f ) ) ; } catch ( Throwable th ) { result . completeAsFailure ( th ) ; } } ) ; return result ;


signature:
public class AJsonSerHelper { /** * This is a convenience method for building simple JSON strings . It passes an AJsonSerHelper to a callback and
 * builds a string based on what the callback does with it . */
public static < E extends Throwable > String buildString ( AStatement1 < AJsonSerHelper , E > code ) throws E { } }

implementation: final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; code . apply ( new AJsonSerHelper ( baos ) ) ; return new String ( baos . toByteArray ( ) , UTF_8 ) ;


signature:
public class AThreadPoolImpl { /** * This method returns an approximation of statistical data for all worker threads since the pool was started . Updates of the statistical data is done without synchronization ,
 * so some or all of the data may be stale , and some numbers may be pretty outdated while others are very current , even for the same thread . For long - running pools however
 * the data may be useful in analyzing behavior in general and performance anomalies in particular . Your mileage may vary , you have been warned ! ; - ) */
@ Override public AThreadPoolStatistics getStatistics ( ) { } }

implementation:
final AWorkerThreadStatistics [ ] workerStats = new AWorkerThreadStatistics [ localQueues . length ] ; for ( int i = 0 ; i < localQueues . length ; i ++ ) { // noinspection ConstantConditions
workerStats [ i ] = localQueues [ i ] . thread . getStatistics ( ) ; } final ASharedQueueStatistics [ ] sharedQueueStats = new ASharedQueueStatistics [ sharedQueues . length ] ; for ( int i = 0 ; i < sharedQueues . length ; i ++ ) { sharedQueueStats [ i ] = new ASharedQueueStatistics ( sharedQueues [ i ] . approximateSize ( ) ) ; } return new AThreadPoolStatistics ( workerStats , sharedQueueStats ) ;


signature:
public class AThreadPoolImpl { /** * This method shuts down the thread pool . The method finishes immediately , returning a separate AFuture for every worker thread . In order to combine them into a single
 * AFuture for all worker threads , use { @ code AFuture . lift ( ) } on the result . */
@ Override public List < AFuture < Void > > shutdown ( ShutdownMode shutdownMode ) { } }

implementation:
if ( ! shutdown . compareAndSet ( false , true ) ) { throw new IllegalStateException ( "pool can be shut down only once" ) ; } if ( shutdownMode == ShutdownMode . SkipUnstarted || shutdownMode == ShutdownMode . InterruptRunning ) { for ( ASharedQueue sharedQueue : sharedQueues ) { sharedQueue . clear ( ) ; } for ( LocalQueue queue : localQueues ) { // noinspection StatementWithEmptyBody
while ( queue . popFifo ( ) != null ) { // do nothing , just drain the queue
} } if ( shutdownMode == ShutdownMode . InterruptRunning ) { for ( LocalQueue queue : localQueues ) { queue . thread . interrupt ( ) ; } } } final List < AFuture < Void > > result = new ArrayList < > ( ) ; for ( LocalQueue localQueue : localQueues ) { final ASettableFuture < Void > f = ASettableFuture . create ( ) ; sharedQueues [ 0 ] . push ( ( ) -> { workerThreadLifecycleCallback . onPreDie ( localQueue . thread ) ; throw new PoolShutdown ( f ) ; } ) ; UNSAFE . unpark ( localQueue . thread ) ; result . add ( f ) ; f . onComplete ( AThreadPool . SYNC_THREADPOOL , x -> workerThreadLifecycleCallback . onPostDie ( localQueue . thread ) ) ; } return result ;


signature:
public class AList { /** * Creates an AList based on the contents of an existing < code > java . util . Iterable < / code > , copying its contents . */
public static < T > AList < T > create ( Iterable < T > elements ) { } }

implementation: if ( elements instanceof AList ) { return ( AList < T > ) elements ; } if ( elements instanceof List ) { return create ( ( List < T > ) elements ) ; } AList < T > result = nil ( ) ; for ( T el : elements ) { result = result . cons ( el ) ; } return result . reverse ( ) ;


signature:
public class AList { /** * Creates an AList based on the contents of an existing < code > java . util . List < / code > , copying its content . */
public static < T > AList < T > create ( List < T > elements ) { } }

implementation: AList < T > result = nil ( ) ; for ( int i = elements . size ( ) - 1 ; i >= 0 ; i -- ) { result = result . cons ( elements . get ( i ) ) ; } return result ;


signature:
public class AList { /** * Creates an AList from a given list of elements . */
@ SafeVarargs public static < T > AList < T > create ( T ... elements ) { } }

implementation: return create ( Arrays . asList ( elements ) ) ;


signature:
public class AList { /** * Returns a copy of this AList with elements in reversed order . */
public AList < T > reverse ( ) { } }

implementation: AList < T > remaining = this ; AList < T > result = nil ( ) ; while ( ! remaining . isEmpty ( ) ) { result = result . cons ( remaining . head ( ) ) ; remaining = remaining . tail ( ) ; } return result ;


signature:
public class AList { /** * Returns a < code > java . util . Iterator < / code > over this AList ' s elements , allowing ALists to be used with Java ' s
 * < code > for ( . . . : list ) < / code > syntax introduced in version 1.5. */
@ Override public Iterator < T > iterator ( ) { } }

implementation: return new Iterator < T > ( ) { AList < T > pos = AList . this ; @ Override public boolean hasNext ( ) { return pos . nonEmpty ( ) ; } @ Override public T next ( ) { final T result = pos . head ( ) ; pos = pos . tail ( ) ; return result ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ;


signature:
public class ACollectionHelper { /** * Create a { @ link java . util . Set } from an { @ link Iterator } . */
public static < T > Set < T > createSet ( Iterator < T > elements ) { } }

implementation: final Set < T > result = new HashSet < > ( ) ; while ( elements . hasNext ( ) ) result . add ( elements . next ( ) ) ; return result ;


signature:
public class ACollectionHelper { /** * Create a { @ link java . util . Set } from an { @ link java . lang . Iterable } . */
public static < T > Set < T > createSet ( Iterable < T > elements ) { } }

implementation: return createSet ( elements . iterator ( ) ) ;


signature:
public class ACollectionHelper { /** * Create a { @ link java . util . Set } from an { @ link Iterator } , transforming each element . */
public static < T , U , E extends Throwable > Set < U > createSet ( Iterator < T > elements , AFunction1 < T , U , E > f ) throws E { } }

implementation: final Set < U > result = new HashSet < > ( ) ; while ( elements . hasNext ( ) ) result . add ( f . apply ( elements . next ( ) ) ) ; return result ;


signature:
public class ACollectionHelper { /** * Create a { @ link java . util . Set } from an { @ link Iterable } , transforming each element . */
public static < T , U , E extends Throwable > Set < U > createSet ( Iterable < T > elements , AFunction1 < T , U , E > f ) throws E { } }

implementation: return createSet ( elements . iterator ( ) , f ) ;


signature:
public class ACollectionHelper { /** * Returns a string representation of a collection , separating elements with a < code > separator < / code > and putting
 * < code > prefix < / code > before the first and a < code > suffix < / code > after the last element . */
public static String mkString ( Iterable < ? > iterable , String prefix , String separator , String suffix ) { } }

implementation: final StringBuilder result = new StringBuilder ( prefix ) ; boolean first = true ; for ( Object o : iterable ) { if ( first ) { first = false ; } else { result . append ( separator ) ; } result . append ( o ) ; } result . append ( suffix ) ; return result . toString ( ) ;


signature:
public class ACollectionHelper { /** * Returns an element of a collection that matches a predicate , if any , or AOption . none ( ) if there is no match . */
public static < T , E extends Throwable > AOption < T > find ( Iterable < T > coll , APredicate < ? super T , E > pred ) throws E { } }

implementation: for ( T o : coll ) { if ( pred . apply ( o ) ) { return AOption . some ( o ) ; } } return AOption . none ( ) ;


signature:
public class ACollectionHelper { /** * Matches a predicate against collection elements , and returns true iff it matches them all . */
public static < T , E extends Throwable > boolean forAll ( Iterable < T > coll , APredicate < ? super T , E > pred ) throws E { } }

implementation: for ( T o : coll ) { if ( ! pred . apply ( o ) ) { return false ; } } return true ;


signature:
public class ACollectionHelper { /** * Applies a transformation function to all elements of a collection , creating a new collection from the results . */
public static < T , X , E extends Throwable > List < X > map ( List < T > coll , AFunction1 < ? super T , ? extends X , E > f ) throws E { } }

implementation: final List < X > result = createEmptyListOfType ( coll , true ) ; for ( T o : coll ) { result . add ( f . apply ( o ) ) ; } return result ;


signature:
public class ACollectionHelper { /** * Applies a transformation function to all elements of a collection , creating a new collection from the results . */
public static < T , X , E extends Throwable > Set < X > map ( Set < T > coll , AFunction1 < ? super T , ? extends X , E > f ) throws E { } }

implementation: final Set < X > result = createEmptySetOfType ( coll , true ) ; for ( T o : coll ) { result . add ( f . apply ( o ) ) ; } return result ;


signature:
public class ACollectionHelper { /** * Same as < code > map ( ) < / code > , except that the transformation function returns collections and all the results are
 * flattened into a single collection . */
public static < T , X , E extends Throwable > Collection < X > flatMap ( Iterable < T > coll , AFunction1 < ? super T , ? extends Iterable < X > , E > f ) throws E { } }

implementation: final List < X > result = new ArrayList < > ( ) ; for ( T o : coll ) { for ( X el : f . apply ( o ) ) { result . add ( el ) ; } } return result ;


signature:
public class ACollectionHelper { /** * Same as < code > map ( ) < / code > , except that the transformation function returns collections and all the results are
 * flattened into a single collection . */
public static < T , X , E extends Throwable > Set < X > flatMapSet ( Iterable < T > coll , AFunction1 < ? super T , ? extends Iterable < X > , E > f ) throws E { } }

implementation: final Set < X > result = new HashSet < > ( ) ; for ( T o : coll ) { for ( X el : f . apply ( o ) ) { result . add ( el ) ; } } return result ;


signature:
public class ACollectionHelper { /** * Takes a collection of collections and creates a new collection from the elements , leaving out the innermost
 * level of collection . */
public static < T > Collection < T > flatten ( Iterable < ? extends Iterable < T > > coll ) { } }

implementation: final List < T > result = new ArrayList < > ( ) ; for ( Iterable < T > o : coll ) { for ( T el : o ) { result . add ( el ) ; } } return result ;


signature:
public class ACollectionHelper { /** * Takes a collection of collections and creates a new collection from the elements , leaving out the innermost
 * level of collection . */
public static < T > List < T > flattenList ( Iterable < ? extends Iterable < T > > coll ) { } }


signature:
public class ACollectionHelper { /** * Takes a collection of collections and creates a new collection from the elements , leaving out the innermost
 * level of collection . */
public static < T > Set < T > flattenSet ( Iterable < ? extends Iterable < T > > coll ) { } }

implementation: final Set < T > result = new HashSet < > ( ) ; for ( Iterable < T > o : coll ) { for ( T el : o ) { result . add ( el ) ; } } return result ;


signature:
public class ACollectionHelper { /** * Applies a transformation function to all elements of a collection , where the partial function is defined for . Creates a new collection
 * of the transformed elements only . So the number of result elements may be less than the number of elements in the source collection . */
public static < T , X , E extends Throwable > Collection < X > collect ( Iterable < T > coll , APartialFunction < ? super T , ? extends X , E > pf ) throws E { } }

implementation: final List < X > result = new ArrayList < > ( ) ; for ( T o : coll ) { if ( pf . isDefinedAt ( o ) ) { result . add ( pf . apply ( o ) ) ; } } return result ;


signature:
public class ACollectionHelper { /** * Applies a transformation function to all elements of a collection , where the partial function is defined for . Creates a new collection
 * of the transformed elements only . So the number of result elements may be less than the number of elements in the source collection . */
public static < T , X , E extends Throwable > List < X > collect ( List < T > coll , APartialFunction < ? super T , ? extends X , E > pf ) throws E { } }

implementation: final List < X > result = createEmptyListOfType ( coll , true ) ; for ( T o : coll ) { if ( pf . isDefinedAt ( o ) ) { result . add ( pf . apply ( o ) ) ; } } return result ;


signature:
public class ACollectionHelper { /** * Applies a transformation function to all elements of a collection , where the partial function is defined for . Creates a new collection
 * of the transformed elements only . So the number of result elements may be less than the number of elements in the source collection . */
public static < T , X , E extends Throwable > Set < X > collect ( Set < T > coll , APartialFunction < ? super T , ? extends X , E > pf ) throws E { } }

implementation: final Set < X > result = createEmptySetOfType ( coll , true ) ; for ( T o : coll ) { if ( pf . isDefinedAt ( o ) ) { result . add ( pf . apply ( o ) ) ; } } return result ;


signature:
public class ACollectionHelper { /** * Matches all elements of a collection against a predicate , creating a new collection from those that match . */
public static < T , E extends Throwable > Collection < T > filter ( Iterable < T > coll , APredicate < ? super T , E > pred ) throws E { } }

implementation: final List < T > result = new ArrayList < > ( ) ; for ( T o : coll ) { if ( pred . apply ( o ) ) { result . add ( o ) ; } } return result ;


signature:
public class ACollectionHelper { /** * Matches all elements of a collection against a predicate , creating a new collection from those that match . */
public static < T , E extends Throwable > List < T > filter ( List < T > coll , APredicate < ? super T , E > pred ) throws E { } }

implementation: final List < T > result = createEmptyListOfType ( coll , false ) ; for ( T o : coll ) { if ( pred . apply ( o ) ) { result . add ( o ) ; } } return result ;


signature:
public class ACollectionHelper { /** * Matches all elements of a collection against a predicate , creating a new collection from those that match . */
public static < T , E extends Throwable > Set < T > filter ( Set < T > coll , APredicate < ? super T , E > pred ) throws E { } }

implementation: final Set < T > result = createEmptySetOfType ( coll , false ) ; for ( T o : coll ) { if ( pred . apply ( o ) ) { result . add ( o ) ; } } return result ;


signature:
public class ACollectionHelper { /** * Creates a Map from a collection . Each element ' s key is determined by applying a function to the element . All
 * elements with the same key are stored as that key ' s value in the returned Map . */
public static < T , X , E extends Throwable > Map < X , Collection < T > > groupBy ( Iterable < T > coll , AFunction1 < ? super T , ? extends X , E > f ) throws E { } }

implementation: final Map < X , Collection < T > > result = new HashMap < > ( ) ; for ( T o : coll ) { final X key = f . apply ( o ) ; Collection < T > perKey = result . get ( key ) ; if ( perKey == null ) { perKey = new ArrayList < > ( ) ; result . put ( key , perKey ) ; } perKey . add ( o ) ; } return result ;


signature:
public class ACollectionHelper { /** * Creates a Map from a collection . Each element ' s key is determined by applying a function to the element . All
 * elements with the same key are stored as that key ' s value in the returned Map . */
public static < T , X , E extends Throwable > Map < X , List < T > > groupBy ( List < T > coll , AFunction1 < ? super T , ? extends X , E > f ) throws E { } }

implementation: final Map < X , List < T > > result = new HashMap < > ( ) ; for ( T o : coll ) { final X key = f . apply ( o ) ; List < T > perKey = result . get ( key ) ; if ( perKey == null ) { perKey = createEmptyListOfType ( coll , false ) ; result . put ( key , perKey ) ; } perKey . add ( o ) ; } return result ;


signature:
public class ACollectionHelper { /** * Applies a binary operator to a start value and all elements of this sequence , going left to right .
 * @ param < T > element type of the collection
 * @ param < R > result type */
public static < T , R , E extends Throwable > R foldLeft ( Iterable < T > coll , R startValue , AFunction2 < R , ? super T , R , E > f ) throws E { } }

implementation: R result = startValue ; for ( T e : coll ) { result = f . apply ( result , e ) ; } return result ;


signature:
public class ACollectionHelper { /** * Applies a binary operator to a start value and all elements of this list , going left to right .
 * @ param < T > element type of the collection
 * @ param < R > result type */
public static < T , R , E extends Throwable > R foldRight ( List < T > coll , R startValue , AFunction2 < R , ? super T , R , E > f ) throws E { } }

implementation: R result = startValue ; ListIterator < T > i = coll . listIterator ( coll . size ( ) ) ; while ( i . hasPrevious ( ) ) { result = f . apply ( result , i . previous ( ) ) ; } return result ;


signature:
public class ACollectionHelper { /** * Copies the content of an < code > Iterable < / code > into an ( immutable ) < code > ACollection < / code > instance . Subsequent
 * changes to the underlying collection have no effect on the returned < code > ACollection < / code > instance . < p >
 * The returned collection has list semantics with regard to < code > map ( ) < / code > and other modifying methods ;
 * duplicate values are allowed . */
public static < T > ACollectionWrapper < T > asACollectionCopy ( Collection < T > c ) { } }

implementation: return asACollectionView ( new ArrayList < > ( c ) ) ;


signature:
public class ACollectionHelper { /** * Wraps the content of a < code > java . util . Collection < / code > in an < code > ACollection < / code > instance . While the returned
 * instance itself has no mutator methods , changes to the underlying collection are reflected in the wrapping
 * < code > ACollection < / code > instance . < p >
 * The returned collection has list semantics with regard to < code > map ( ) < / code > and other modifying methods ; duplicate
 * values are allowed . */
@ SuppressWarnings ( "unchecked" ) public static < T > ACollectionWrapper < T > asACollectionView ( Collection < T > c ) { } }

implementation: return new ACollectionWrapper ( c ) ;


signature:
public class ACollectionHelper { /** * Wraps the content of a < code > java . util . Set < / code > in an < code > ASet < / code > instance . While the returned
 * instance itself has no mutator methods , changes to the underlying collection are reflected in the wrapping
 * < code > ASet < / code > instance . < p >
 * The returned collection has set semantics with regard to < code > map ( ) < / code > and other modifying methods ; duplicate
 * values are removed . */
public static < T > ASetWrapper < T > asASetView ( Collection < T > c ) { } }

implementation: if ( c instanceof Set ) { return new ASetWrapper < > ( ( Set < T > ) c ) ; } return new ASetWrapper < > ( new HashSet < > ( c ) ) ;


signature:
public class ACollectionHelper { /** * Copies the content of an array into an ( immutable ) < code > ACollection < / code > instance . Subsequent
 * changes to the underlying array have no effect on the returned < code > ACollection < / code > instance . < p >
 * The returned collection has list semantics with regard to < code > map ( ) < / code > and other modifying methods ;
 * duplicate values are allowed . */
@ SuppressWarnings ( "unchecked" ) public static < T > AArrayWrapper < T > asArrayCopy ( T [ ] c ) { } }

implementation: final T [ ] newArray = ( T [ ] ) Array . newInstance ( c . getClass ( ) . getComponentType ( ) , c . length ) ; System . arraycopy ( c , 0 , newArray , 0 , c . length ) ; return new AArrayWrapper < > ( newArray ) ;


signature:
public class ACollectionHelper { /** * Returns a < code > Collection < / code > with the exact same elements as an < code > Iterable < / code > , copying only if the parameter is not a collection . */
public static < T > List < T > asJavaUtilList ( Iterable < T > c ) { } }

implementation: if ( c instanceof List ) { return ( List < T > ) c ; } return asJavaUtilCollection ( c . iterator ( ) ) ;


signature:
public class ACollectionHelper { /** * Returns a < code > Collection < / code > with the exact same elements as an < code > Iterable < / code > , copying only if the parameter is not a collection . */
public static < T > Collection < T > asJavaUtilCollection ( Iterable < T > c ) { } }

implementation: if ( c instanceof Collection ) { return ( Collection < T > ) c ; } return asJavaUtilCollection ( c . iterator ( ) ) ;


signature:
public class ACollectionHelper { /** * Copies the elements from an < code > Iterator < / code > into a < code > Collection < / code > . */
public static < T > List < T > asJavaUtilCollection ( Iterator < T > c ) { } }

implementation: final List < T > result = new ArrayList < > ( ) ; while ( c . hasNext ( ) ) { result . add ( c . next ( ) ) ; } return result ;


signature:
public class AHashMap { /** * Returns an AHashMap instance with default ( i . e . equals - based ) equalityForEquals , initializing it from the contents of
 * a given < code > java . util . Map < / code > . */
@ SuppressWarnings ( "unused" ) public static < K , V > AHashMap < K , V > fromJavaUtilMap ( Map < K , V > map ) { } }

implementation: return fromJavaUtilMap ( DEFAULT_EQUALITY , map ) ;


signature:
public class AHashMap { /** * Returns an AHashMap instance for a given equalityForEquals , initializing it from the contents of a given
 * < code > java . util . Map < / code > . */
public static < K , V > AHashMap < K , V > fromJavaUtilMap ( AEquality equality , Map < K , V > map ) { } }

implementation: AHashMap < K , V > result = empty ( equality ) ; for ( Map . Entry < K , V > entry : map . entrySet ( ) ) { result = result . updated ( entry . getKey ( ) , entry . getValue ( ) ) ; } return result ;


signature:
public class AHashMap { /** * Returns an AHashMap instance with default ( i . e . equals - based ) equalityForEquals , initializing it from separate ' keys '
 * and ' values ' collections . Both collections are iterated exactly once , and are expected to have the same size . */
public static < K , V > AHashMap < K , V > fromKeysAndValues ( Iterable < K > keys , Iterable < V > values ) { } }

implementation: return fromKeysAndValues ( DEFAULT_EQUALITY , keys , values ) ;


signature:
public class AHashMap { /** * Returns an AHashMap instance with default ( i . e . equals - based ) equalityForEquals , initializing it from a collection of
 * keys and a function . For each element of the < code > keys < / code > collection , the function is called once to
 * determine the corresponding value , and the pair is then stored in the map . */
@ SuppressWarnings ( "unused" ) public static < K , V , E extends Throwable > AHashMap < K , V > fromKeysAndFunction ( Iterable < K > keys , AFunction1 < ? super K , ? extends V , E > f ) throws E { } }

implementation: return fromKeysAndFunction ( DEFAULT_EQUALITY , keys , f ) ;


signature:
public class AHashMap { /** * Returns an AHashMap instance with a given equalityForEquals , initializing it from a collection of
 * keys and a function . For each element of the < code > keys < / code > collection , the function is called once to
 * determine the corresponding value , and the pair is then stored in the map . */
public static < K , V , E extends Throwable > AHashMap < K , V > fromKeysAndFunction ( AEquality equality , Iterable < K > keys , AFunction1 < ? super K , ? extends V , E > f ) throws E { } }

implementation: final Iterator < K > ki = keys . iterator ( ) ; AHashMap < K , V > result = AHashMap . empty ( equality ) ; while ( ki . hasNext ( ) ) { final K key = ki . next ( ) ; final V value = f . apply ( key ) ; result = result . updated ( key , value ) ; } return result ;


signature:
public class AHashMap { /** * very internal method . It assumes hash0 ! = hash1. */
private static < K , V > HashTrieMap < K , V > mergeLeafMaps ( int hash0 , AHashMap < K , V > elem0 , int hash1 , AHashMap < K , V > elem1 , int level , int size , AEquality equality ) { } }

implementation:
final int index0 = ( hash0 >>> level ) & 0x1f ; final int index1 = ( hash1 >>> level ) & 0x1f ; if ( index0 != index1 ) { final int bitmap = ( 1 << index0 ) | ( 1 << index1 ) ; final AHashMap < K , V > [ ] elems = createArray ( 2 ) ; if ( index0 < index1 ) { elems [ 0 ] = elem0 ; elems [ 1 ] = elem1 ; } else { elems [ 0 ] = elem1 ; elems [ 1 ] = elem0 ; } return new HashTrieMap < > ( bitmap , elems , size , equality ) ; } else { final AHashMap < K , V > [ ] elems = createArray ( 1 ) ; final int bitmap = ( 1 << index0 ) ; // try again , based on the
elems [ 0 ] = mergeLeafMaps ( hash0 , elem0 , hash1 , elem1 , level + LEVEL_INCREMENT , size , equality ) ; return new HashTrieMap < > ( bitmap , elems , size , equality ) ; }


signature:
public class SharedQueueBlockPushBlockPopImpl { /** * Add a new task to the top of the shared queue , incrementing ' top ' . */
@ Override public void push ( Runnable task ) { } }

implementation:
final long _base ; final long _top ; synchronized ( PUSH_LOCK ) { _base = base ; _top = top ; if ( _top == _base + mask ) { throw new RejectedExecutionExceptionWithoutStacktrace ( "Shared queue overflow" ) ; } tasks [ asArrayIndex ( _top ) ] = task ; // volatile put for atomicity and to ensure ordering wrt . storing the task
UNSAFE . putLongVolatile ( this , OFFS_TOP , _top + 1 ) ; } pool . onAvailableTask ( ) ;


signature:
public class LocalQueue { /** * Add a new task to the top of the localQueue , incrementing ' top ' . This is only ever called from the owning thread . */
void push ( Runnable task ) { } }

implementation:
final long _base = UNSAFE . getLongVolatile ( this , OFFS_BASE ) ; // read base first ( and only once )
final long _top = top ; if ( _top == _base + mask ) { throw new RejectedExecutionExceptionWithoutStacktrace ( "local queue overflow" ) ; } tasks [ asArrayindex ( _top ) ] = task ; // ' top ' is only ever modified by the owning thread , so we need no CAS here . Storing ' top ' with volatile semantics publishes the task and ensures that changes to the task
// can never overtake changes to ' top ' wrt visibility .
UNSAFE . putLongVolatile ( this , OFFS_TOP , _top + 1 ) ; // Notify pool only for the first added item per queue .
if ( _top - _base <= 1 ) { pool . onAvailableTask ( ) ; }


signature:
public class LocalQueue { /** * Fetch ( and remove ) a task from the top of the queue , i . e . LIFO semantics . This is only ever called from the owning thread , removing ( or
 * at least reducing ) contention at the top of the queue : No other thread operates there . */
Runnable popLifo ( ) { } }

implementation:
final long _top = top ; final Runnable result = tasks [ asArrayindex ( _top - 1 ) ] ; if ( result == null ) { // The queue is empty . It is possible for the queue to be empty even if the previous unprotected read does not return null , but
// it will only ever return null if the queue really is empty : New entries are only added by the owning thread , and this method
// ' popLifo ( ) ' is also only ever called by the owning thread .
return null ; } if ( ! UNSAFE . compareAndSwapObject ( tasks , taskOffset ( _top - 1 ) , result , null ) ) { // The CAS operation failing means that another thread pulled the top - most item from the queue , so the queue is now definitely
// empty . It also null ' ed out the task in the array if it was previously available , allowing to to be GC ' ed when processing is
// finished .
return null ; } // Since ' result ' is not null , and was not previously consumed by another thread , we can safely consume it - - > decrement ' top '
UNSAFE . putOrderedLong ( this , OFFS_TOP , _top - 1 ) ; return result ;


signature:
public class LocalQueue { /** * Fetch ( and remove ) a task from the bottom of the queue , i . e . FIFO semantics . This method can be called by any thread . */
Runnable popFifo ( ) { } }

implementation:
long _base , _top ; while ( true ) { // reading ' base ' with volatile semantics emits the necessary barriers to ensure visibility of ' top '
_base = UNSAFE . getLongVolatile ( this , OFFS_BASE ) ; _top = top ; if ( _base == _top ) { // Terminate the loop : the queue is empty .
// TODO verify that Hotspot optimizes this kind of return - from - the - middle well
return null ; } // a regular read is OK here : ' push ( ) ' emits a store barrier after storing the task , ' popLifo ( ) ' modifies it with CAS , and ' popFifo ( ) ' does
// a volatile read of ' base ' before reading the task
final Runnable result = tasks [ asArrayindex ( _base ) ] ; // result = = null means that another thread concurrently fetched the task from under our nose .
// checking _ base against a re - read ' base ' with volatile semantics avoids wrap - around race - ' base ' could have incremented by a multiple of the queue ' s size between
// our first reading it and fetching the task at that offset , which would cause the increment inside the following if block to significantly decrement it and
// wreak havoc .
// CAS ensures that only one thread gets the task , and allows GC when processing is finished
if ( result != null && _base == UNSAFE . getLongVolatile ( this , OFFS_BASE ) && UNSAFE . compareAndSwapObject ( tasks , taskOffset ( _base ) , result , null ) ) { UNSAFE . putLongVolatile ( this , OFFS_BASE , _base + 1 ) ; // TODO is ' putOrdered ' sufficient ?
return result ; } }


signature:
public class AOption { /** * This is a convenience method that creates an AOption based on Java conventions .
 * @ return ' none ( ) ' if the parameter is null , ' some ( nullable ) ' otherwise */
public static < T > AOption < T > fromNullable ( T nullable ) { } }

implementation: return nullable != null ? some ( nullable ) : AOption . < T > none ( ) ;


signature:
public class ALongHashMap { /** * Returns an ALongHashMap initialized from separate ' keys ' and ' values ' collections . Both collections
 * are iterated exactly once and are expected to have the same size . */
public static < V > ALongHashMap < V > fromKeysAndValues ( Iterable < ? extends Number > keys , Iterable < V > values ) { } }

implementation: final Iterator < ? extends Number > ki = keys . iterator ( ) ; final Iterator < V > vi = values . iterator ( ) ; ALongHashMap < V > result = ALongHashMap . empty ( ) ; while ( ki . hasNext ( ) ) { final Number key = ki . next ( ) ; final V value = vi . next ( ) ; result = result . updated ( key . longValue ( ) , value ) ; } return result ;


signature:
public class ALongHashMap { /** * Returns an ALongHashMap instance initialized from a collection of
 * keys and a function . For each element of the < code > keys < / code > collection , the function is called once to
 * determine the corresponding value , and the pair is then stored in the map . */
@ SuppressWarnings ( "unused" ) public static < K extends Number , V , E extends Throwable > ALongHashMap < V > fromKeysAndFunction ( Iterable < K > keys , AFunction1 < ? super K , ? extends V , E > f ) throws E { } }

implementation: final Iterator < K > ki = keys . iterator ( ) ; ALongHashMap < V > result = empty ( ) ; while ( ki . hasNext ( ) ) { final K key = ki . next ( ) ; final V value = f . apply ( key ) ; result = result . updated ( key . longValue ( ) , value ) ; } return result ;


signature:
public class ALongHashMap { /** * very internal method . It assumes hash0 ! = hash1. */
private static < V > LongHashTrieMap < V > mergeLeafMaps ( long hash0 , ALongHashMap < V > elem0 , long hash1 , ALongHashMap < V > elem1 , int level , int size ) { } }

implementation:
final int index0 = ( int ) ( ( hash0 >>> level ) & 0x3f ) ; final int index1 = ( int ) ( ( hash1 >>> level ) & 0x3f ) ; if ( index0 != index1 ) { final long bitmap = ( 1L << index0 ) | ( 1L << index1 ) ; final ALongHashMap < V > [ ] elems = createArray ( 2 ) ; if ( index0 < index1 ) { elems [ 0 ] = elem0 ; elems [ 1 ] = elem1 ; } else { elems [ 0 ] = elem1 ; elems [ 1 ] = elem0 ; } return new LongHashTrieMap < > ( bitmap , elems , size ) ; } else { final ALongHashMap < V > [ ] elems = createArray ( 1 ) ; final long bitmap = ( 1L << index0 ) ; // try again , based on the
elems [ 0 ] = mergeLeafMaps ( hash0 , elem0 , hash1 , elem1 , level + LEVEL_INCREMENT , size ) ; return new LongHashTrieMap < > ( bitmap , elems , size ) ; }


signature:
public class AListMap { /** * Returns an empty AListMap instance with a given equalityForEquals . Calling this factory method instead
 * of the constructor allows internal reuse of empty map instances since they are immutable . */
@ SuppressWarnings ( "unchecked" ) public static < K , V > AListMap < K , V > empty ( AEquality equality ) { } }

implementation: if ( equality == AEquality . EQUALS ) return ( AListMap < K , V > ) emptyEquals ; if ( equality == AEquality . IDENTITY ) return ( AListMap < K , V > ) emptyIdentity ; return new AListMap < > ( equality ) ;


signature:
public class AListMap { /** * Returns an AListMap instance with default ( i . e . equals - based ) equalityForEquals , initializing it from separate ' keys '
 * and ' values ' collections . Both collections are iterated exactly once , and are expected to have the same size . */
public static < K , V > AListMap < K , V > fromKeysAndValues ( Iterable < ATuple2 < K , V > > elements ) { } }

implementation: return fromKeysAndValues ( DEFAULT_EQUALITY , elements ) ;


signature:
public class AListMap { /** * Returns an AHashMap instance with a given equalityForEquals , initializing it from separate ' keys '
 * and ' values ' collections . Both collections are iterated exactly once , and are expected to have the same size . */
public static < K , V > AListMap < K , V > fromKeysAndValues ( AEquality equality , Iterable < ATuple2 < K , V > > elements ) { } }

implementation: AListMap < K , V > result = empty ( equality ) ; for ( ATuple2 < K , V > el : elements ) { result = result . updated ( el . _1 , el . _2 ) ; } return result ;


signature:
public class AListMap { /** * Returns an AListMap instance with a given equalityForEquals , initializing it from separate ' keys '
 * and ' values ' collections . Both collections are iterated exactly once , and are expected to have the same size . */
public static < K , V > AListMap < K , V > fromKeysAndValues ( AEquality equality , Iterable < K > keys , Iterable < V > values ) { } }

implementation: final Iterator < K > ki = keys . iterator ( ) ; final Iterator < V > vi = values . iterator ( ) ; AListMap < K , V > result = empty ( equality ) ; while ( ki . hasNext ( ) ) { final K key = ki . next ( ) ; final V value = vi . next ( ) ; result = result . updated ( key , value ) ; } return result ;


signature:
public class ARedBlackTreeMap { /** * This method combines two separate sub - trees into a single ( balanced ) tree . It assumes that both subtrees are
 * balanced and that all elements in ' tl ' are smaller than all elements in ' tr ' . This situation occurs when a
 * node is deleted and its child nodes must be combined into a resulting tree . */
private static < K , V > Tree < K , V > append ( Tree < K , V > tl , Tree < K , V > tr ) { } }

implementation: if ( tl == null ) return tr ; if ( tr == null ) return tl ; if ( isRedTree ( tl ) && isRedTree ( tr ) ) { final Tree < K , V > bc = append ( tl . right , tr . left ) ; return isRedTree ( bc ) ? new RedTree < > ( bc . key , bc . value , new RedTree < > ( tl . key , tl . value , tl . left , bc . left ) , new RedTree < > ( tr . key , tr . value , bc . right , tr . right ) ) : new RedTree < > ( tl . key , tl . value , tl . left , new RedTree < > ( tr . key , tr . value , bc , tr . right ) ) ; } if ( isBlackTree ( tl ) && isBlackTree ( tr ) ) { final Tree < K , V > bc = append ( tl . right , tr . left ) ; return isRedTree ( bc ) ? new RedTree < > ( bc . key , bc . value , new BlackTree < > ( tl . key , tl . value , tl . left , bc . left ) , new BlackTree < > ( tr . key , tr . value , bc . right , tr . right ) ) : balanceLeft ( tl . key , tl . value , tl . left , new BlackTree < > ( tr . key , tr . value , bc , tr . right ) ) ; } if ( isRedTree ( tr ) ) { return new RedTree < > ( tr . key , tr . value , append ( tl , tr . left ) , tr . right ) ; } if ( isRedTree ( tl ) ) { return new RedTree < > ( tl . key , tl . value , tl . left , append ( tl . right , tr ) ) ; } throw new IllegalStateException ( "invariant violation: unmatched tree on append: " + tl + ", " + tr ) ;


signature:
public class ExecutorServiceWrapper { /** * - - - - - shutdown handling below this point - - - - - */
@ Override public void shutdown ( ) { } }

implementation: if ( poolWithAdmin == null ) throw new UnsupportedOperationException ( "shutdown only supported for AThreadPoolWithAdmin" ) ; shutdown . set ( AFuture . lift ( AThreadPool . SYNC_THREADPOOL , poolWithAdmin . shutdown ( AThreadPoolWithAdmin . ShutdownMode . ExecuteSubmitted ) ) ) ;


signature:
public class MapAsSetWrapper { /** * - - - - - collection transformations */
@ SuppressWarnings ( "unchecked" ) protected < X > ASet < X > createInternal ( Iterable < X > elements ) { } }

implementation: AMap result = inner . clear ( ) ; for ( X el : elements ) { result = result . updated ( el , Boolean . TRUE ) ; } return ( ASet ) wrapAsSet ( result ) ;


signature:
public class JavaUtilMapWrapper { /** * There is usually a performance gain to be had by overriding this default implementation */
@ Override public Set < K > keySet ( ) { } }

implementation: return new AbstractSet < K > ( ) { @ Override public Iterator < K > iterator ( ) { return new Iterator < K > ( ) { final Iterator < AMapEntry < K , V > > it = inner . iterator ( ) ; @ Override public boolean hasNext ( ) { return it . hasNext ( ) ; } @ Override public K next ( ) { return it . next ( ) . getKey ( ) ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; } @ Override public int size ( ) { return inner . size ( ) ; } } ;


signature:
public class RamlCache { /** * TODO save all included ramls of a raml . when any of them changes , reparse ! */
public RamlModelResult loadRaml ( String name ) { } }

implementation: final File file = new File ( CACHE_DIR , escaped ( loader . config ( ) ) + "-" + escaped ( simpleName ( name ) ) + ".braml" ) ; if ( ! file . exists ( ) ) { return parseAndSave ( loader , name , file ) ; } final InputStream in = loader . fetchResource ( name , file . lastModified ( ) ) ; if ( in != null ) { final byte [ ] data = loadedData ( name , in ) ; return parseAndSave ( new PreloadedLoader ( loader , name , data ) , name , file ) ; } try { return load ( file ) ; } catch ( IOException | ClassNotFoundException e ) { return parseAndSave ( loader , name , file ) ; }


signature:
public class UriLoader { /** * - > hack to undo this */
private String normalizeResourceName ( String name ) { } }

implementation: if ( name . startsWith ( "//" ) ) { return "classpath:" + name ; } final int firstProtocol = name . indexOf ( "://" ) ; final int secondProtocol = name . indexOf ( "://" , firstProtocol + 1 ) ; final int protocol = secondProtocol < 0 ? firstProtocol : secondProtocol ; final int endOfFirst = name . lastIndexOf ( "/" , protocol ) ; if ( endOfFirst >= 0 ) { return name . substring ( endOfFirst + 1 ) ; } return name ;


signature:
public class ValueTypeXmlAdapter { /** * Marshals the specified user - defined value type object to single XML value
 * string representation .
 * @ throws If the specified object is not a user - defined value type . */
@ Override public String marshal ( BoundType v ) throws Exception { } }

implementation: Class < ? extends Object > type = v . getClass ( ) ; if ( ! Types . isUserDefinedValueType ( type ) ) { throw new IllegalArgumentException ( "Type [" + type + "] must be an user-defined value type; " + "@XmlJavaTypeAdapter(ValueTypeXmlAdapter.class) " + "can be annotated to user-defined value type and field only" ) ; } Converter converter = ConvertUtils . lookup ( type ) ; if ( ( converter != null && converter instanceof AbstractConverter ) ) { String string = ( String ) ConvertUtils . convert ( v , String . class ) ; if ( string != null ) { return string ; } } return v . toString ( ) ;


signature:
public class XMLRequest { /** * Constructs a new { @ code XMLRequest } from the current { @ code WebContext } .
 * @ param context The current { @ code WebContext } . */
public void from ( WebContext context ) { } }

implementation: DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; try { DocumentBuilder builder = factory . newDocumentBuilder ( ) ; Document document = builder . parse ( new InputSource ( context . request ( ) . getReader ( ) ) ) ; node = document . getDocumentElement ( ) ; } catch ( Exception e ) { logger . warn ( "Cannot parse XML document into DOM object" , e ) ; throw new UncheckedException ( e ) ; } super . from ( context ) ;


signature:
public class XMLRequest { /** * Returns the Web endpoint method parameter value from the current HTTP
 * request body sent as XML format .
 * This method supports the following parameter declaration independently .
 * Other than them are the same as { @ link AbstractRequest } .
 * < ol >
 * < li > Named collection of user - defined object type < / li >
 * < li > Named user - defined object type < / li >
 * < / ol >
 * @ param type Web endpoint method parameter type .
 * @ param name Web endpoint method parameter name .
 * @ return Web endpoint method parameter value . */
@ Override protected Object body ( Type type , String name ) { } }

implementation: return body ( type , name , node ) ;


signature:
public class XMLRequest { /** * Converts the specified object to the specified type .
 * The object to be converted must be a { @ code Node } that has no child , or
 * this method return < code > null < / code > .
 * @ param object The object to be converted
 * @ param type The type to which the specified object be converted .
 * @ return The converted object . */
@ Override protected Object convert ( Object object , Class < ? > type ) { } }

implementation: if ( object instanceof Node ) { Node node = ( Node ) object ; NodeList nodes = node . getChildNodes ( ) ; Text text = null ; for ( int i = 0 ; i < nodes . getLength ( ) ; i ++ ) { Node child = nodes . item ( i ) ; if ( child . getNodeType ( ) == Node . TEXT_NODE ) { text = ( Text ) child ; } } if ( text == null ) { logger . warn ( "Parameter [" + object + "] cannot be converted to [" + type + "]; Converted 'object' must have one child [" + Text . class + "] node" ) ; return null ; } return super . convert ( text . getNodeValue ( ) , type ) ; } else { logger . warn ( "Parameter [" + object + "] cannot be converted to [" + type + "]; Converted 'object' must be a [" + Node . class + "]" ) ; return null ; }


signature:
public class FastCharBuffer { /** * Appends < code > char < / code > array to buffer . */
public FastCharBuffer append ( char [ ] array , int off , int len ) { } }

implementation:
int end = off + len ; if ( ( off < 0 ) || ( len < 0 ) || ( end > array . length ) ) { throw new IndexOutOfBoundsException ( ) ; } if ( len == 0 ) { return this ; } int newSize = size + len ; int remaining = len ; if ( currentBuffer != null ) { // first try to fill current buffer
int part = Math . min ( remaining , currentBuffer . length - offset ) ; System . arraycopy ( array , end - remaining , currentBuffer , offset , part ) ; remaining -= part ; offset += part ; size += part ; } if ( remaining > 0 ) { // still some data left
// ask for new buffer
needNewBuffer ( newSize ) ; // then copy remaining
// but this time we are sure that it will fit
int part = Math . min ( remaining , currentBuffer . length - offset ) ; System . arraycopy ( array , end - remaining , currentBuffer , offset , part ) ; offset += part ; size += part ; } return this ;


signature:
public class FastCharBuffer { /** * Creates < code > char < / code > subarray from buffered content . */
public char [ ] toArray ( int start , int len ) { } }

implementation: int remaining = len ; int pos = 0 ; char [ ] array = new char [ len ] ; if ( len == 0 ) { return array ; } int i = 0 ; while ( start >= buffers [ i ] . length ) { start -= buffers [ i ] . length ; i ++ ; } while ( i < buffersCount ) { char [ ] buf = buffers [ i ] ; int c = Math . min ( buf . length - start , remaining ) ; System . arraycopy ( buf , start , array , pos , c ) ; pos += c ; remaining -= c ; if ( remaining == 0 ) { break ; } start = 0 ; i ++ ; } return array ;


signature:
public class FastCharBuffer { /** * Returns < code > char < / code > element at given index . */
public char get ( int index ) { } }

implementation: if ( ( index >= size ) || ( index < 0 ) ) { throw new IndexOutOfBoundsException ( ) ; } int ndx = 0 ; while ( true ) { char [ ] b = buffers [ ndx ] ; if ( index < b . length ) { return b [ index ] ; } ndx ++ ; index -= b . length ; }


signature:
public class FastCharBuffer { /** * Returns sub sequence . */
public CharSequence subSequence ( int start , int end ) { } }

implementation: int len = end - start ; return new StringBuilder ( len ) . append ( toArray ( start , len ) ) ;


signature:
public class FastCharBuffer { /** * Appends string content to buffer . */
public FastCharBuffer append ( String string ) { } }

implementation:
int len = string . length ( ) ; if ( len == 0 ) { return this ; } int end = offset + len ; int newSize = size + len ; int remaining = len ; int start = 0 ; if ( currentBuffer != null ) { // first try to fill current buffer
int part = Math . min ( remaining , currentBuffer . length - offset ) ; string . getChars ( 0 , part , currentBuffer , offset ) ; remaining -= part ; offset += part ; size += part ; start += part ; } if ( remaining > 0 ) { // still some data left
// ask for new buffer
needNewBuffer ( newSize ) ; // then copy remaining
// but this time we are sure that it will fit
int part = Math . min ( remaining , currentBuffer . length - offset ) ; string . getChars ( start , start + part , currentBuffer , offset ) ; offset += part ; size += part ; } return this ;


signature:
public class BinarySearch { /** * Creates binary search wrapper over a list of comparable elements . */
public static < T extends Comparable > BinarySearch < T > forList ( final List < T > list ) { } }

implementation: return new BinarySearch < T > ( ) { @ Override @ SuppressWarnings ( { "unchecked" } ) protected int compare ( int index , T element ) { return list . get ( index ) . compareTo ( element ) ; } @ Override protected int getLastIndex ( ) { return list . size ( ) - 1 ; } } ;


signature:
public class BinarySearch { /** * Creates binary search wrapper over a list with given comparator . */
public static < T > BinarySearch < T > forList ( final List < T > list , final Comparator < T > comparator ) { } }

implementation: return new BinarySearch < T > ( ) { @ Override @ SuppressWarnings ( { "unchecked" } ) protected int compare ( int index , T element ) { return comparator . compare ( list . get ( index ) , element ) ; } @ Override protected int getLastIndex ( ) { return list . size ( ) - 1 ; } } ;


signature:
public class BinarySearch { /** * Finds very first index of given element in inclusive index range . Returns negative
 * value if element is not found . */
public int findFirst ( E o , int low , int high ) { } }

implementation: int ndx = - 1 ; while ( low <= high ) { int mid = ( low + high ) >>> 1 ; int delta = compare ( mid , o ) ; if ( delta < 0 ) { low = mid + 1 ; } else { if ( delta == 0 ) { ndx = mid ; } high = mid - 1 ; } } if ( ndx == - 1 ) { return - ( low + 1 ) ; } return ndx ;


signature:
public class ValueTypeJsonSerializer { /** * Serializes the specified user - defined value type object to
 * < code > JsonPrimitive < / code > representation . */
public JsonElement serialize ( T src , Type typeOfSrc , JsonSerializationContext context ) { } }

implementation: Class < ? > type = Types . getRawType ( typeOfSrc ) ; Converter converter = ConvertUtils . lookup ( type ) ; if ( ( converter != null && converter instanceof AbstractConverter ) ) { String string = ( String ) ConvertUtils . convert ( src , String . class ) ; if ( string != null ) { return new JsonPrimitive ( string ) ; } } return new JsonPrimitive ( src . toString ( ) ) ;


signature:
public class CtClassClassResolver { /** * Loads the class of the specified name from the specified
 * { @ code InputStream } and returns loaded class representation as
 * { @ code javassist . CtClass } .
 * @ param clazz The name of the class to be loaded .
 * @ param stream { @ code InputStream } to load a class file .
 * @ return The loaded class representation as { @ code javassist . CtClass } . */
@ Override protected CtClass load ( String clazz , InputStream stream ) { } }

implementation: try { return pool . makeClass ( stream ) ; } catch ( Exception e ) { return null ; }


signature:
public class CtClassClassResolver { /** * Resolves the classes that is annotated by the specified annotation as
 * { @ code javassist . CtClass } .
 * @ param annotation The annotation the class being annotated .
 * @ return Classes that is annotated by the specified annotation as
 * { @ code javassist . CtClass } .
 * @ throws IOException If any I / O access fails while traversing the search
 * path . */
@ Override public Set < CtClass > resolveByAnnotation ( final Class < ? extends Annotation > annotation ) throws IOException { } }

implementation: Matcher < CtClass > matcher = new Matcher < CtClass > ( ) { @ Override public boolean matches ( CtClass ctClass ) { try { for ( Object object : ctClass . getAnnotations ( ) ) { Annotation a = ( Annotation ) object ; if ( a . annotationType ( ) . equals ( annotation ) ) { return true ; } } } catch ( Exception e ) { } ctClass . detach ( ) ; return false ; } } ; return resolve ( matcher ) ;


signature:
public class CtClassClassResolver { /** * Resolves the classes that implements the specified interface as
 * { @ code javassist . CtClass } .
 * @ param interfaceClass The interface being implemented .
 * @ return Classes that implements the specified interface as
 * { @ code javassist . CtClass } .
 * @ throws IOException If any I / O access fails while traversing the search
 * path . */
@ Override public Set < CtClass > resolveByInterface ( final Class < ? > interfaceClass ) throws IOException { } }

implementation: Matcher < CtClass > matcher = new Matcher < CtClass > ( ) { @ Override public boolean matches ( CtClass ctClass ) { try { for ( CtClass c : ctClass . getInterfaces ( ) ) { if ( c . getName ( ) . equals ( interfaceClass . getName ( ) ) ) { return true ; } } CtClass superclass = ctClass . getSuperclass ( ) ; if ( superclass != null ) { return matches ( superclass ) ; } } catch ( Exception e ) { } ctClass . detach ( ) ; return false ; } } ; return resolve ( matcher ) ;


signature:
public class CtClassClassResolver { /** * Resolves the classes that contains the specified name as
 * { @ code javassist . CtClass } .
 * @ param name The part of the class name .
 * @ return Classes that contains the specified name as
 * { @ code javassist . CtClass } .
 * @ throws IOException If any I / O access fails while traversing the search
 * path . */
@ Override public Set < CtClass > resolveByName ( final String name ) throws IOException { } }

implementation: Matcher < CtClass > matcher = new Matcher < CtClass > ( ) { @ Override public boolean matches ( CtClass ctClass ) { if ( ctClass . getName ( ) . contains ( name ) ) { return true ; } ctClass . detach ( ) ; return false ; } } ; return resolve ( matcher ) ;


signature:
public class Routing { /** * Adds URL routing pattern .
 * The routing pattern can be specified as URI template format and the path
 * variables can be passed to Web endpoint method like this :
 * < pre >
 * { @ code @ Override }
 * public void routing ( Routing routing ) {
 * routing . add ( " / user / { id } / * " , User . class , " handle " ) ;
 * < / pre >
 * < pre >
 * { @ code }
 * public class User {
 * / / ' / user / { id } / * ' is routed to this method .
 * public void handle ( { @ code } String id ) {
 * < / pre >
 * < b > Note < / b > : If a certain URI matches to multiple routing patterns , the
 * routing pattern that has the most path segments ( split by ' / ' ) is used in
 * preference to the others . If there are multiple routing patterns that
 * have the same path segments , the first - specified one is used .
 * @ param pattern URL routing pattern as URI template format .
 * @ param endpoint Web endpoint class corresponding to the routing pattern .
 * @ param method Web endpoint method corresponding to the routing pattern .
 * @ see URITemplate */
public void add ( String pattern , Class < ? > endpoint , String method ) { } }

implementation: add ( null , pattern , endpoint , method ) ;


signature:
public class Routing { /** * Adds URL routing pattern .
 * The routing pattern can be specified as URI template format and the path
 * variables can be passed to Web endpoint method like this :
 * < pre >
 * { @ code @ Override }
 * public void routing ( Routing routing ) {
 * routing . add ( " / user / { id } / * " , User . class , " handle " ) ;
 * < / pre >
 * < pre >
 * { @ code }
 * public class User {
 * / / ' / user / { id } / * ' is routed to this method .
 * public void handle ( { @ code } String id ) {
 * < / pre >
 * < b > Note < / b > : If a certain URI matches to multiple routing patterns , the
 * routing pattern that has the most path segments ( split by ' / ' ) is used in
 * preference to the others . If there are multiple routing patterns that
 * have the same path segments , the first - specified one is used .
 * @ param pattern URL routing pattern as URI template format .
 * @ param endpoint Web endpoint class corresponding to the routing pattern .
 * @ param method Web endpoint method corresponding to the routing pattern .
 * @ see URITemplate */
public void add ( Verb verb , String pattern , Class < ? > endpoint , String method ) { } }

implementation: Preconditions . checkArgument ( pattern != null , "Parameter 'pattern' must not be [" + pattern + "]" ) ; Preconditions . checkArgument ( pattern . startsWith ( "/" ) , "Parameter 'pattern' must start with [/]" ) ; Preconditions . checkArgument ( endpoint != null , "Parameter 'endpoint' must not be [" + endpoint + "]" ) ; Preconditions . checkArgument ( method != null , "Parameter 'method' must not be [" + method + "]" ) ; for ( Method m : endpoint . getMethods ( ) ) { if ( m . getName ( ) . equals ( method ) ) { URITemplate template = null ; if ( templates . containsKey ( pattern ) ) { template = templates . get ( pattern ) ; } else { template = new URITemplate ( pattern ) ; templates . put ( pattern , template ) ; } Map < Verb , Method > methods = null ; if ( routes . containsKey ( template ) ) { methods = routes . get ( template ) ; } else { methods = new HashMap < Verb , Method > ( ) ; routes . put ( template , methods ) ; } methods . put ( verb , m ) ; return ; } } throw new IllegalArgumentException ( "Method [" + method + "] does not exist on Web endpoint [" + endpoint + "]" ) ;


signature:
public class Routing { /** * Adds ignore - routing patterns .
 * The requested URL that matches to the patterns is not handled by
 * Bootleg . < code > * < / code > ( meta character ) can be used in the pattern
 * ( e . g . , < code > * . png < / code > ) .
 * < br > < b > Note < / b > : Ignore - routing patterns are in preference to routing
 * patterns .
 * @ param patterns The ignore - routing patterns . */
public void ignore ( String ... patterns ) { } }

implementation: Preconditions . checkArgument ( patterns != null , "Parameter 'patterns' must not be [" + patterns + "]" ) ; for ( String pattern : patterns ) { Preconditions . checkArgument ( pattern != null && ! pattern . isEmpty ( ) , "Parameter 'patterns' must not include [null] or empty entry" ) ; ignores . add ( Pattern . compile ( pattern . replaceAll ( "\\." , Matcher . quoteReplacement ( "\\." ) ) . replaceAll ( "\\*" , ".*?" ) ) ) ; }