Input: Asynchronous point - multicast communication to services subscribed that matches the destination service <code > name< / code > . [CODESPLIT] public ArrayList < TransId > mcast_async ( final String name , final byte [ ] request ) throws InvalidInputException , MessageDecodingException , TerminateException { return mcast_async ( name , new byte [ 0 ] , request , this . timeout_async , this . priority_default ) ; }


Input: Forward a message to another service subscribed that matches the destination service <code > name< / code > . [CODESPLIT] public void forward_ ( final Integer request_type , final String name , final byte [ ] request_info , final byte [ ] request , final Integer timeout , final Byte priority , final byte [ ] trans_id , final OtpErlangPid pid ) throws ForwardAsyncException , ForwardSyncException , InvalidInputException { if ( request_type == API . ASYNC ) forward_async ( name , request_info , request , timeout , priority , trans_id , pid ) ; else if ( request_type == API . SYNC ) forward_sync ( name , request_info , request , timeout , priority , trans_id , pid ) ; else throw new InvalidInputException ( ) ; }


Input: Asynchronously forward a message to another service subscribed that matches the destination service <code > name< / code > . [CODESPLIT] public void forward_async ( final String name , final byte [ ] request_info , final byte [ ] request , Integer timeout , final Byte priority , final byte [ ] trans_id , final OtpErlangPid pid ) throws ForwardAsyncException { try { OtpOutputStream forward_async = new OtpOutputStream ( ) ; forward_async . write ( OtpExternal . versionTag ) ; final OtpErlangObject [ ] tuple = { new OtpErlangAtom ( "forward_async" ) , new OtpErlangString ( name ) , new OtpErlangBinary ( request_info ) , new OtpErlangBinary ( request ) , new OtpErlangUInt ( timeout ) , new OtpErlangInt ( priority ) , new OtpErlangBinary ( trans_id ) , pid } ; forward_async . write_any ( new OtpErlangTuple ( tuple ) ) ; send ( forward_async ) ; } catch ( OtpErlangRangeException e ) { e . printStackTrace ( API . err ) ; return ; } throw new ForwardAsyncException ( ) ; }


Input: Returns a response from a service request . [CODESPLIT] public void return_ ( final Integer request_type , final String name , final String pattern , final byte [ ] response_info , final byte [ ] response , final Integer timeout , final byte [ ] trans_id , final OtpErlangPid pid ) throws ReturnAsyncException , ReturnSyncException , InvalidInputException { if ( request_type == API . ASYNC ) return_async ( name , pattern , response_info , response , timeout , trans_id , pid ) ; else if ( request_type == API . SYNC ) return_sync ( name , pattern , response_info , response , timeout , trans_id , pid ) ; else throw new InvalidInputException ( ) ; }


Input: Synchronously returns a response from a service request . [CODESPLIT] public void return_sync ( final String name , final String pattern , byte [ ] response_info , byte [ ] response , Integer timeout , final byte [ ] trans_id , final OtpErlangPid pid ) throws ReturnSyncException { try { OtpOutputStream return_sync = new OtpOutputStream ( ) ; return_sync . write ( OtpExternal . versionTag ) ; final OtpErlangObject [ ] tuple = { new OtpErlangAtom ( "return_sync" ) , new OtpErlangString ( name ) , new OtpErlangString ( pattern ) , new OtpErlangBinary ( response_info ) , new OtpErlangBinary ( response ) , new OtpErlangUInt ( timeout ) , new OtpErlangBinary ( trans_id ) , pid } ; return_sync . write_any ( new OtpErlangTuple ( tuple ) ) ; send ( return_sync ) ; } catch ( OtpErlangRangeException e ) { e . printStackTrace ( API . err ) ; return ; } throw new ReturnSyncException ( ) ; }


Input: Asynchronously receive a response . [CODESPLIT] public Response recv_async ( final Integer timeout ) throws InvalidInputException , MessageDecodingException , TerminateException { return recv_async ( timeout , TransIdNull , true ) ; }


Input: Asynchronously receive a response . [CODESPLIT] public Response recv_async ( final byte [ ] trans_id ) throws InvalidInputException , MessageDecodingException , TerminateException { return recv_async ( this . timeout_sync , trans_id , true ) ; }


Input: Asynchronously receive a response . [CODESPLIT] public Response recv_async ( final boolean consume ) throws InvalidInputException , MessageDecodingException , TerminateException { return recv_async ( this . timeout_sync , TransIdNull , consume ) ; }


Input: Asynchronously receive a response . [CODESPLIT] public Response recv_async ( final byte [ ] trans_id , final boolean consume ) throws InvalidInputException , MessageDecodingException , TerminateException { return recv_async ( this . timeout_sync , trans_id , consume ) ; }


Input: Asynchronously receive a response . [CODESPLIT] public Response recv_async ( final Integer timeout , final byte [ ] trans_id , final boolean consume ) throws InvalidInputException , MessageDecodingException , TerminateException { 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 ; } }


Input: Blocks to process incoming CloudI service requests [CODESPLIT] public boolean poll ( final int timeout ) throws InvalidInputException , MessageDecodingException , TerminateException { if ( Boolean . TRUE == poll_request ( timeout , true ) ) return true ; return false ; }


Input: Shutdown the service successfully [CODESPLIT] public void shutdown ( final String reason ) { 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 ) ; }


Input: TODO make specific Throwables contributable? [CODESPLIT] public static boolean requiresNonLocalHandling ( Throwable th ) { return th instanceof VirtualMachineError || th instanceof ThreadDeath || th instanceof InterruptedException || th instanceof LinkageError ; }


Input: This method checks if a given Throwable is fit for local handling returning it if it is and throwing it otherwise . [CODESPLIT] public static < T extends Throwable > T forLocalHandling ( T th ) { if ( requiresNonLocalHandling ( th ) ) { AUnchecker . throwUnchecked ( th ) ; } return th ; }


Input: Acquires the runState lock ; returns current ( locked ) runState . [CODESPLIT] private int lockRunState ( ) { int rs ; return ( ( ( ( rs = runState ) & RSLOCK ) != 0 || ! U . compareAndSwapInt ( this , RUNSTATE , rs , rs |= RSLOCK ) ) ? awaitRunStateLock ( ) : rs ) ; }


Input: Spins and / or blocks until runstate lock is available . See above for explanation . [CODESPLIT] private int awaitRunStateLock ( ) { 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 ( ) ; } } } }


Input: Unlocks and sets runState to newRunState . [CODESPLIT] private void unlockRunState ( int oldRunState , int newRunState ) { if ( ! U . compareAndSwapInt ( this , RUNSTATE , oldRunState , newRunState ) ) { Object lock = stealCounter ; runState = newRunState ; // clears RSIGNAL bit if ( lock != null ) synchronized ( lock ) { lock . notifyAll ( ) ; } } }


Input: Tries to construct and start one worker . Assumes that total count has already been incremented as a reservation . Invokes deregisterWorker on any failure . [CODESPLIT] private boolean createWorker ( ) { 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 ; }


Input: Tries to add one worker incrementing ctl counts before doing so relying on createWorker to back out on failure . [CODESPLIT] private void tryAddWorker ( long c ) { 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 ) ; }


Input: Callback from ForkJoinWorkerThread constructor to establish and record its WorkQueue . [CODESPLIT] final WorkQueue registerWorker ( ForkJoinWorkerThread wt ) { 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 ; }


Input: 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 . [CODESPLIT] final void deregisterWorker ( ForkJoinWorkerThread wt , Throwable ex ) { 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 ) ; }


Input: Tries to create or activate a worker if too few are active . [CODESPLIT] final void signalWork ( WorkQueue [ ] ws , WorkQueue q ) { 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 ; } }


Input: 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 . [CODESPLIT] private boolean tryRelease ( long c , WorkQueue v , long inc ) { 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 ; }


Input: Top - level runloop for workers called by ForkJoinWorkerThread . run . [CODESPLIT] final void runWorker ( WorkQueue w ) { 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 } }


Input: 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 . [CODESPLIT] private ForkJoinTask < ? > scan ( WorkQueue w , int r ) { 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 ; }


Input: 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 . [CODESPLIT] private boolean awaitWork ( WorkQueue w , int r ) { 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 ; }


Input: 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 ) . [CODESPLIT] final int helpComplete ( WorkQueue w , CountedCompleter < ? > task , int maxTasks ) { 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 ; }


Input: 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 . [CODESPLIT] private boolean tryCompensate ( WorkQueue w ) { 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 ; }


Input: 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 . [CODESPLIT] static int getSurplusQueuedTaskCount ( ) { 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 ; }


Input: Possibly initiates and / or completes termination . [CODESPLIT] private boolean tryTerminate ( boolean now , boolean enable ) { 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 ; }


Input: 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 . [CODESPLIT] private void externalSubmit ( ForkJoinTask < ? > task ) { 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 ) ; } }


Input: 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 . [CODESPLIT] final void externalPush ( ForkJoinTask < ? > task ) { 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 ) ; }


Input: Returns common pool queue for an external thread . [CODESPLIT] static WorkQueue commonSubmitterQueue ( ) { 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 ; }


Input: 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 . [CODESPLIT] final boolean tryExternalUnpush ( ForkJoinTask < ? > task ) { 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 ; }


Input: Performs helpComplete for an external submitter . [CODESPLIT] final int externalHelpComplete ( CountedCompleter < ? > task , int maxTasks ) { 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 ) ; }


Input: 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 . [CODESPLIT] public < T > T invoke ( ForkJoinTask < T > task ) { if ( task == null ) throw new NullPointerException ( ) ; externalPush ( task ) ; return task . join ( ) ; }


Input: Submits a ForkJoinTask for execution . [CODESPLIT] public < T > ForkJoinTask < T > submit ( ForkJoinTask < T > task ) { if ( task == null ) throw new NullPointerException ( ) ; externalPush ( task ) ; return task ; }


Input: 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 . [CODESPLIT] public long getStealCount ( ) { 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 ; }


Input: Creates and returns the common pool respecting user settings specified via system properties . [CODESPLIT] private static ForkJoinPool makeCommonPool ( ) { 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-" ) ; }


Input: } [CODESPLIT] public static < R , T , E extends Throwable > AFuture < AList < R > > traverse ( AThreadPool tp , Iterable < T > values , AFunction1 < T , AFuture < R > , E > f ) throws E { final List < AFuture < R > > result = new ArrayList <> ( ) ; for ( T o : values ) { result . add ( f . apply ( o ) ) ; } return lift ( tp , result ) ; }


Input: Add a new task to the top of the shared queue incrementing top . [CODESPLIT] @ Override public void push ( Runnable task ) { 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 ; } } }


Input: Waits if necessary for at most the given time for the computation to complete and then retrieves its result if available . [CODESPLIT] public final V get ( long timeout , TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException { 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 ( ) ; }


Input: intentionally not volatile : This class is immutable so recalculating per thread works [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public static < K , V > ABTreeMap < K , V > empty ( ABTreeSpec spec ) { return new LeafNode ( spec , new Object [ 0 ] , new Object [ 0 ] ) ; }


Input: public Iterable<V > values ( K keyMin K keyMax ) ; [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public ABTreeMap < K , V > updated ( K key , V value ) { 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 } ) ; }


Input: } [CODESPLIT] @ Override public < S > AFuture < S > map ( AThreadPool tp , AFunction1 < T , S , ? > f ) { final AFutureImpl < S > result = new AFutureImpl <> ( tp ) ; onComplete ( tp , v -> { try { result . complete ( v . map ( f ) ) ; } catch ( Throwable th ) { result . completeAsFailure ( th ) ; } } ) ; return result ; }


Input: 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 . [CODESPLIT] public static < E extends Throwable > String buildString ( AStatement1 < AJsonSerHelper , E > code ) throws E { final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; code . apply ( new AJsonSerHelper ( baos ) ) ; return new String ( baos . toByteArray ( ) , UTF_8 ) ; }


Input: 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! ; - ) [CODESPLIT] @ Override public AThreadPoolStatistics getStatistics ( ) { 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 ) ; }


Input: 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 { [CODESPLIT] @ Override public List < AFuture < Void > > shutdown ( ShutdownMode shutdownMode ) { 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 ; }


Input: Creates an AList based on the contents of an existing <code > java . util . Iterable< / code > copying its contents . [CODESPLIT] public static < T > AList < T > create ( Iterable < T > elements ) { 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 ( ) ; }


Input: Creates an AList based on the contents of an existing <code > java . util . List< / code > copying its content . [CODESPLIT] public static < T > AList < T > create ( List < T > elements ) { AList < T > result = nil ( ) ; for ( int i = elements . size ( ) - 1 ; i >= 0 ; i -- ) { result = result . cons ( elements . get ( i ) ) ; } return result ; }


Input: Creates an AList from a given list of elements . [CODESPLIT] @ SafeVarargs public static < T > AList < T > create ( T ... elements ) { return create ( Arrays . asList ( elements ) ) ; }


Input: Returns a copy of this AList with elements in reversed order . [CODESPLIT] public AList < T > reverse ( ) { AList < T > remaining = this ; AList < T > result = nil ( ) ; while ( ! remaining . isEmpty ( ) ) { result = result . cons ( remaining . head ( ) ) ; remaining = remaining . tail ( ) ; } return result ; }


Input: 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 . [CODESPLIT] @ Override public Iterator < T > iterator ( ) { 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 ( ) ; } } ; }


Input: Create a { [CODESPLIT] public static < T > Set < T > createSet ( Iterator < T > elements ) { final Set < T > result = new HashSet <> ( ) ; while ( elements . hasNext ( ) ) result . add ( elements . next ( ) ) ; return result ; }


Input: Create a { [CODESPLIT] public static < T > Set < T > createSet ( Iterable < T > elements ) { return createSet ( elements . iterator ( ) ) ; }


Input: Create a { [CODESPLIT] public static < T , U , E extends Throwable > Set < U > createSet ( Iterator < T > elements , AFunction1 < T , U , E > f ) throws E { final Set < U > result = new HashSet <> ( ) ; while ( elements . hasNext ( ) ) result . add ( f . apply ( elements . next ( ) ) ) ; return result ; }


Input: Create a { [CODESPLIT] public static < T , U , E extends Throwable > Set < U > createSet ( Iterable < T > elements , AFunction1 < T , U , E > f ) throws E { return createSet ( elements . iterator ( ) , f ) ; }


Input: 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 . [CODESPLIT] public static String mkString ( Iterable < ? > iterable , String prefix , String separator , String suffix ) { 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 ( ) ; }


Input: Returns an element of a collection that matches a predicate if any or AOption . none () if there is no match . [CODESPLIT] public static < T , E extends Throwable > AOption < T > find ( Iterable < T > coll , APredicate < ? super T , E > pred ) throws E { for ( T o : coll ) { if ( pred . apply ( o ) ) { return AOption . some ( o ) ; } } return AOption . none ( ) ; }


Input: Matches a predicate against collection elements and returns true iff it matches them all . [CODESPLIT] public static < T , E extends Throwable > boolean forAll ( Iterable < T > coll , APredicate < ? super T , E > pred ) throws E { for ( T o : coll ) { if ( ! pred . apply ( o ) ) { return false ; } } return true ; }


Input: Applies a transformation function to all elements of a collection creating a new collection from the results . [CODESPLIT] public static < T , X , E extends Throwable > List < X > map ( List < T > coll , AFunction1 < ? super T , ? extends X , E > f ) throws E { final List < X > result = createEmptyListOfType ( coll , true ) ; for ( T o : coll ) { result . add ( f . apply ( o ) ) ; } return result ; }


Input: Applies a transformation function to all elements of a collection creating a new collection from the results . [CODESPLIT] public static < T , X , E extends Throwable > Set < X > map ( Set < T > coll , AFunction1 < ? super T , ? extends X , E > f ) throws E { final Set < X > result = createEmptySetOfType ( coll , true ) ; for ( T o : coll ) { result . add ( f . apply ( o ) ) ; } return result ; }


Input: Same as <code > map () < / code > except that the transformation function returns collections and all the results are flattened into a single collection . [CODESPLIT] public static < T , X , E extends Throwable > Collection < X > flatMap ( Iterable < T > coll , AFunction1 < ? super T , ? extends Iterable < X > , E > f ) throws E { final List < X > result = new ArrayList <> ( ) ; for ( T o : coll ) { for ( X el : f . apply ( o ) ) { result . add ( el ) ; } } return result ; }


Input: Same as <code > map () < / code > except that the transformation function returns collections and all the results are flattened into a single collection . [CODESPLIT] public static < T , X , E extends Throwable > Set < X > flatMapSet ( Iterable < T > coll , AFunction1 < ? super T , ? extends Iterable < X > , E > f ) throws E { final Set < X > result = new HashSet <> ( ) ; for ( T o : coll ) { for ( X el : f . apply ( o ) ) { result . add ( el ) ; } } return result ; }


Input: Takes a collection of collections and creates a new collection from the elements leaving out the innermost level of collection . [CODESPLIT] public static < T > Collection < T > flatten ( Iterable < ? extends Iterable < T > > coll ) { final List < T > result = new ArrayList <> ( ) ; for ( Iterable < T > o : coll ) { for ( T el : o ) { result . add ( el ) ; } } return result ; }


Input: Takes a collection of collections and creates a new collection from the elements leaving out the innermost level of collection . [CODESPLIT] public static < T > List < T > flattenList ( Iterable < ? extends Iterable < T > > coll ) { final List < T > result = new ArrayList <> ( ) ; for ( Iterable < T > o : coll ) { for ( T el : o ) { result . add ( el ) ; } } return result ; }


Input: Takes a collection of collections and creates a new collection from the elements leaving out the innermost level of collection . [CODESPLIT] public static < T > Set < T > flattenSet ( Iterable < ? extends Iterable < T > > coll ) { final Set < T > result = new HashSet <> ( ) ; for ( Iterable < T > o : coll ) { for ( T el : o ) { result . add ( el ) ; } } return result ; }


Input: 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 . [CODESPLIT] public static < T , X , E extends Throwable > Collection < X > collect ( Iterable < T > coll , APartialFunction < ? super T , ? extends X , E > pf ) throws E { final List < X > result = new ArrayList <> ( ) ; for ( T o : coll ) { if ( pf . isDefinedAt ( o ) ) { result . add ( pf . apply ( o ) ) ; } } return result ; }


Input: 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 . [CODESPLIT] public static < T , X , E extends Throwable > List < X > collect ( List < T > coll , APartialFunction < ? super T , ? extends X , E > pf ) throws E { final List < X > result = createEmptyListOfType ( coll , true ) ; for ( T o : coll ) { if ( pf . isDefinedAt ( o ) ) { result . add ( pf . apply ( o ) ) ; } } return result ; }


Input: 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 . [CODESPLIT] public static < T , X , E extends Throwable > Set < X > collect ( Set < T > coll , APartialFunction < ? super T , ? extends X , E > pf ) throws E { final Set < X > result = createEmptySetOfType ( coll , true ) ; for ( T o : coll ) { if ( pf . isDefinedAt ( o ) ) { result . add ( pf . apply ( o ) ) ; } } return result ; }


Input: Matches all elements of a collection against a predicate creating a new collection from those that match . [CODESPLIT] public static < T , E extends Throwable > Collection < T > filter ( Iterable < T > coll , APredicate < ? super T , E > pred ) throws E { final List < T > result = new ArrayList <> ( ) ; for ( T o : coll ) { if ( pred . apply ( o ) ) { result . add ( o ) ; } } return result ; }


Input: Matches all elements of a collection against a predicate creating a new collection from those that match . [CODESPLIT] public static < T , E extends Throwable > List < T > filter ( List < T > coll , APredicate < ? super T , E > pred ) throws E { final List < T > result = createEmptyListOfType ( coll , false ) ; for ( T o : coll ) { if ( pred . apply ( o ) ) { result . add ( o ) ; } } return result ; }


Input: Matches all elements of a collection against a predicate creating a new collection from those that match . [CODESPLIT] public static < T , E extends Throwable > Set < T > filter ( Set < T > coll , APredicate < ? super T , E > pred ) throws E { final Set < T > result = createEmptySetOfType ( coll , false ) ; for ( T o : coll ) { if ( pred . apply ( o ) ) { result . add ( o ) ; } } return result ; }


Input: 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 . [CODESPLIT] public static < T , X , E extends Throwable > Map < X , Collection < T > > groupBy ( Iterable < T > coll , AFunction1 < ? super T , ? extends X , E > f ) throws E { 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 ; }


Input: 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 . [CODESPLIT] public static < T , X , E extends Throwable > Map < X , List < T > > groupBy ( List < T > coll , AFunction1 < ? super T , ? extends X , E > f ) throws E { 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 ; }


Input: Applies a binary operator to a start value and all elements of this sequence going left to right . [CODESPLIT] public static < T , R , E extends Throwable > R foldLeft ( Iterable < T > coll , R startValue , AFunction2 < R , ? super T , R , E > f ) throws E { R result = startValue ; for ( T e : coll ) { result = f . apply ( result , e ) ; } return result ; }


Input: Applies a binary operator to a start value and all elements of this list going left to right . [CODESPLIT] public static < T , R , E extends Throwable > R foldRight ( List < T > coll , R startValue , AFunction2 < R , ? super T , R , E > f ) throws E { R result = startValue ; ListIterator < T > i = coll . listIterator ( coll . size ( ) ) ; while ( i . hasPrevious ( ) ) { result = f . apply ( result , i . previous ( ) ) ; } return result ; }


Input: 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 > [CODESPLIT] public static < T > ACollectionWrapper < T > asACollectionCopy ( Collection < T > c ) { return asACollectionView ( new ArrayList <> ( c ) ) ; }


Input: 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 > [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public static < T > ACollectionWrapper < T > asACollectionView ( Collection < T > c ) { return new ACollectionWrapper ( c ) ; }


Input: 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 > [CODESPLIT] public static < T > ASetWrapper < T > asASetView ( Collection < T > c ) { if ( c instanceof Set ) { return new ASetWrapper <> ( ( Set < T > ) c ) ; } return new ASetWrapper <> ( new HashSet <> ( c ) ) ; }


Input: 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 > [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public static < T > AArrayWrapper < T > asArrayCopy ( T [ ] c ) { final T [ ] newArray = ( T [ ] ) Array . newInstance ( c . getClass ( ) . getComponentType ( ) , c . length ) ; System . arraycopy ( c , 0 , newArray , 0 , c . length ) ; return new AArrayWrapper <> ( newArray ) ; }


Input: Returns a <code > Collection< / code > with the exact same elements as an <code > Iterable< / code > copying only if the parameter is not a collection . [CODESPLIT] public static < T > List < T > asJavaUtilList ( Iterable < T > c ) { if ( c instanceof List ) { return ( List < T > ) c ; } return asJavaUtilCollection ( c . iterator ( ) ) ; }


Input: Returns a <code > Collection< / code > with the exact same elements as an <code > Iterable< / code > copying only if the parameter is not a collection . [CODESPLIT] public static < T > Collection < T > asJavaUtilCollection ( Iterable < T > c ) { if ( c instanceof Collection ) { return ( Collection < T > ) c ; } return asJavaUtilCollection ( c . iterator ( ) ) ; }


Input: Copies the elements from an <code > Iterator< / code > into a <code > Collection< / code > . [CODESPLIT] public static < T > List < T > asJavaUtilCollection ( Iterator < T > c ) { final List < T > result = new ArrayList <> ( ) ; while ( c . hasNext ( ) ) { result . add ( c . next ( ) ) ; } return result ; }


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


Input: Returns an AHashMap instance for a given equalityForEquals initializing it from the contents of a given <code > java . util . Map< / code > . [CODESPLIT] public static < K , V > AHashMap < K , V > fromJavaUtilMap ( AEquality equality , Map < K , V > map ) { AHashMap < K , V > result = empty ( equality ) ; for ( Map . Entry < K , V > entry : map . entrySet ( ) ) { result = result . updated ( entry . getKey ( ) , entry . getValue ( ) ) ; } return result ; }


Input: 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 . [CODESPLIT] public static < K , V > AHashMap < K , V > fromKeysAndValues ( Iterable < K > keys , Iterable < V > values ) { return fromKeysAndValues ( DEFAULT_EQUALITY , keys , values ) ; }


Input: 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 . [CODESPLIT] @ 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 { return fromKeysAndFunction ( DEFAULT_EQUALITY , keys , f ) ; }


Input: 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 . [CODESPLIT] 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 { 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 ; }


Input: very internal method . It assumes hash0 ! = hash1 . [CODESPLIT] 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 ) { 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 ) ; } }


Input: Add a new task to the top of the shared queue incrementing top . [CODESPLIT] @ Override public void push ( Runnable task ) { 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 ( ) ; }


Input: Add a new task to the top of the localQueue incrementing top . This is only ever called from the owning thread . [CODESPLIT] void push ( Runnable task ) { 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 ( ) ; } }


Input: 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 . [CODESPLIT] Runnable popLifo ( ) { 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 ; }


Input: Fetch ( and remove ) a task from the bottom of the queue i . e . FIFO semantics . This method can be called by any thread . [CODESPLIT] Runnable popFifo ( ) { 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 ; } } }


Input: This is a convenience method that creates an AOption based on Java conventions . [CODESPLIT] public static < T > AOption < T > fromNullable ( T nullable ) { return nullable != null ? some ( nullable ) : AOption . < T > none ( ) ; }


Input: Returns an ALongHashMap initialized from separate keys and values collections . Both collections are iterated exactly once and are expected to have the same size . [CODESPLIT] public static < V > ALongHashMap < V > fromKeysAndValues ( Iterable < ? extends Number > keys , Iterable < V > values ) { 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 ; }


Input: 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 . [CODESPLIT] @ 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 { 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 ; }


Input: very internal method . It assumes hash0 ! = hash1 . [CODESPLIT] private static < V > LongHashTrieMap < V > mergeLeafMaps ( long hash0 , ALongHashMap < V > elem0 , long hash1 , ALongHashMap < V > elem1 , int level , int size ) { 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 ) ; } }


Input: 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 . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public static < K , V > AListMap < K , V > empty ( AEquality equality ) { if ( equality == AEquality . EQUALS ) return ( AListMap < K , V > ) emptyEquals ; if ( equality == AEquality . IDENTITY ) return ( AListMap < K , V > ) emptyIdentity ; return new AListMap <> ( equality ) ; }


Input: 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 . [CODESPLIT] public static < K , V > AListMap < K , V > fromKeysAndValues ( Iterable < ATuple2 < K , V > > elements ) { return fromKeysAndValues ( DEFAULT_EQUALITY , elements ) ; }


Input: 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 . [CODESPLIT] public static < K , V > AListMap < K , V > fromKeysAndValues ( AEquality equality , Iterable < ATuple2 < K , V > > elements ) { AListMap < K , V > result = empty ( equality ) ; for ( ATuple2 < K , V > el : elements ) { result = result . updated ( el . _1 , el . _2 ) ; } return result ; }


Input: 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 . [CODESPLIT] public static < K , V > AListMap < K , V > fromKeysAndValues ( AEquality equality , Iterable < K > keys , Iterable < V > values ) { 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 ; }


Input: 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 . [CODESPLIT] private static < K , V > Tree < K , V > append ( Tree < K , V > tl , Tree < K , V > tr ) { 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 ) ; }


Input: ------------------- shutdown handling below this point --------------------- [CODESPLIT] @ Override public void shutdown ( ) { if ( poolWithAdmin == null ) throw new UnsupportedOperationException ( "shutdown only supported for AThreadPoolWithAdmin" ) ; shutdown . set ( AFuture . lift ( AThreadPool . SYNC_THREADPOOL , poolWithAdmin . shutdown ( AThreadPoolWithAdmin . ShutdownMode . ExecuteSubmitted ) ) ) ; }


Input: -------------------------------------- collection transformations [CODESPLIT] @ SuppressWarnings ( "unchecked" ) protected < X > ASet < X > createInternal ( Iterable < X > elements ) { AMap result = inner . clear ( ) ; for ( X el : elements ) { result = result . updated ( el , Boolean . TRUE ) ; } return ( ASet ) wrapAsSet ( result ) ; }


Input: There is usually a performance gain to be had by overriding this default implementation [CODESPLIT] @ Override public Set < K > keySet ( ) { 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 ( ) ; } } ; }


Input: TODO save all included ramls of a raml . when any of them changes reparse! [CODESPLIT] public RamlModelResult loadRaml ( String name ) { 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 ) ; } }


Input: - > hack to undo this [CODESPLIT] private String normalizeResourceName ( String name ) { 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 ; }


Input: Marshals the specified user - defined value type object to single XML value string representation . [CODESPLIT] @ Override public String marshal ( BoundType v ) throws Exception { 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 ( ) ; }


Input: Constructs a new { @code XMLRequest } from the current { @code WebContext } . [CODESPLIT] public void from ( WebContext context ) { 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 ) ; }


Input: 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 > [CODESPLIT] @ Override protected Object body ( Type type , String name ) { return body ( type , name , node ) ; }


Input: 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 > . [CODESPLIT] @ Override protected Object convert ( Object object , Class < ? > type ) { 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 ; } }


Input: Appends <code > char< / code > array to buffer . [CODESPLIT] public FastCharBuffer append ( char [ ] array , int off , int len ) { 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 ; }


Input: Creates <code > char< / code > subarray from buffered content . [CODESPLIT] public char [ ] toArray ( int start , int len ) { 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 ; }


Input: Returns <code > char< / code > element at given index . [CODESPLIT] public char get ( int index ) { 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 ; } }


Input: Returns sub sequence . [CODESPLIT] public CharSequence subSequence ( int start , int end ) { int len = end - start ; return new StringBuilder ( len ) . append ( toArray ( start , len ) ) ; }


Input: Appends string content to buffer . [CODESPLIT] public FastCharBuffer append ( String string ) { 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 ; }


Input: Creates binary search wrapper over a list of comparable elements . [CODESPLIT] public static < T extends Comparable > BinarySearch < T > forList ( final List < T > list ) { 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 ; } } ; }


Input: Creates binary search wrapper over a list with given comparator . [CODESPLIT] public static < T > BinarySearch < T > forList ( final List < T > list , final Comparator < T > comparator ) { 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 ; } } ; }


Input: Finds very first index of given element in inclusive index range . Returns negative value if element is not found . [CODESPLIT] public int findFirst ( E o , int low , int high ) { 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 ; }


Input: Serializes the specified user - defined value type object to <code > JsonPrimitive< / code > representation . [CODESPLIT] public JsonElement serialize ( T src , Type typeOfSrc , JsonSerializationContext context ) { 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 ( ) ) ; }


Input: Loads the class of the specified name from the specified { @code InputStream } and returns loaded class representation as { @code javassist . CtClass } . [CODESPLIT] @ Override protected CtClass load ( String clazz , InputStream stream ) { try { return pool . makeClass ( stream ) ; } catch ( Exception e ) { return null ; } }


Input: Resolves the classes that is annotated by the specified annotation as { @code javassist . CtClass } . [CODESPLIT] @ Override public Set < CtClass > resolveByAnnotation ( final Class < ? extends Annotation > annotation ) throws IOException { 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 ) ; }


Input: Resolves the classes that implements the specified interface as { @code javassist . CtClass } . [CODESPLIT] @ Override public Set < CtClass > resolveByInterface ( final Class < ? > interfaceClass ) throws IOException { 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 ) ; }


Input: Resolves the classes that contains the specified name as { @code javassist . CtClass } . [CODESPLIT] @ Override public Set < CtClass > resolveByName ( final String name ) throws IOException { 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 ) ; }


Input: 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 { [CODESPLIT] public void add ( String pattern , Class < ? > endpoint , String method ) { add ( null , pattern , endpoint , method ) ; }


Input: 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 { [CODESPLIT] public void add ( Verb verb , String pattern , Class < ? > endpoint , String method ) { 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 + "]" ) ; }


Input: 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 . [CODESPLIT] public void ignore ( String ... patterns ) { 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 ( "\\*" , ".*?" ) ) ) ; } }


Input: Send an email [CODESPLIT] public static Future < Boolean > send ( Email email ) { try { email = buildMessage ( email ) ; if ( GojaConfig . getProperty ( "mail.smtp" , StringPool . EMPTY ) . equals ( "mock" ) && GojaConfig . getApplicationMode ( ) . isDev ( ) ) { Mock . send ( email ) ; return new Future < Boolean > ( ) { @ Override public boolean cancel ( boolean mayInterruptIfRunning ) { return false ; } @ Override public boolean isCancelled ( ) { return false ; } @ Override public boolean isDone ( ) { return true ; } @ Override public Boolean get ( ) throws InterruptedException , ExecutionException { return true ; } @ Override public Boolean get ( long timeout , final TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException { return true ; } } ; } email . setMailSession ( getSession ( ) ) ; return sendMessage ( email ) ; } catch ( EmailException ex ) { throw new MailException ( "Cannot send email" , ex ) ; } }


Input: Send a JavaMail message [CODESPLIT] public static Future < Boolean > sendMessage ( final Email msg ) { if ( asynchronousSend ) { return executor . submit ( new Callable < Boolean > ( ) { public Boolean call ( ) { try { msg . setSentDate ( new Date ( ) ) ; msg . send ( ) ; return true ; } catch ( Throwable e ) { MailException me = new MailException ( "Error while sending email" , e ) ; logger . error ( "The email has not been sent" , me ) ; return false ; } } } ) ; } else { final StringBuffer result = new StringBuffer ( ) ; try { msg . setSentDate ( new Date ( ) ) ; msg . send ( ) ; } catch ( Throwable e ) { MailException me = new MailException ( "Error while sending email" , e ) ; logger . error ( "The email has not been sent" , me ) ; result . append ( "oops" ) ; } return new Future < Boolean > ( ) { public boolean cancel ( boolean mayInterruptIfRunning ) { return false ; } public boolean isCancelled ( ) { return false ; } public boolean isDone ( ) { return true ; } public Boolean get ( ) throws InterruptedException , ExecutionException { return result . length ( ) == 0 ; } public Boolean get ( long timeout , TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException { return result . length ( ) == 0 ; } } ; } }


Input: Specify a handler that will be called for all HTTP methods [CODESPLIT] public void bind ( final RouteBinding handler ) { final Method method = handler . getMethod ( ) ; logger . info ( "Using appId: {} and default version: {}" , appAcceptId , defaultVersion ) ; List < String > versions = handler . getVersions ( ) ; if ( versions == null || versions . isEmpty ( ) ) { versions = Collections . singletonList ( defaultVersion ) ; } for ( final String version : versions ) { final Set < Method > methods = new HashSet <> ( ) ; if ( method == Method . ANY ) { for ( final Method m : Method . values ( ) ) { methods . add ( m ) ; } } else { methods . add ( method ) ; } for ( final Method m : methods ) { final BindingKey key = new BindingKey ( m , version ) ; List < PatternRouteBinding > b = routeBindings . get ( key ) ; if ( b == null ) { b = new ArrayList <> ( ) ; routeBindings . put ( key , b ) ; } logger . info ( "ADD: {}, Pattern: {}, Route: {}\n" , key , handler . getPath ( ) , handler ) ; addPattern ( handler , b ) ; } } }


Input: Specify a filter handler that will be used to wrap route executions [CODESPLIT] public void bind ( final FilterBinding handler ) { final Method method = handler . getMethod ( ) ; final String path = handler . getPath ( ) ; logger . info ( "Using appId: {} and default version: {}" , appAcceptId , defaultVersion ) ; List < String > versions = handler . getVersions ( ) ; if ( versions == null || versions . isEmpty ( ) ) { versions = Collections . singletonList ( defaultVersion ) ; } for ( final String version : versions ) { final Set < Method > methods = new HashSet <> ( ) ; if ( method == Method . ANY ) { for ( final Method m : Method . values ( ) ) { methods . add ( m ) ; } } else { methods . add ( method ) ; } for ( final Method m : methods ) { final BindingKey key = new BindingKey ( m , version ) ; logger . info ( "ADD: {}, Pattern: {}, Filter: {}\n" , key , path , handler ) ; List < PatternFilterBinding > allFilterBindings = this . filterBindings . get ( key ) ; if ( allFilterBindings == null ) { allFilterBindings = new ArrayList <> ( ) ; this . filterBindings . put ( key , allFilterBindings ) ; } boolean found = false ; for ( final PatternFilterBinding binding : allFilterBindings ) { if ( binding . getPattern ( ) . pattern ( ) . equals ( handler . getPath ( ) ) ) { binding . addFilter ( handler ) ; found = true ; break ; } } if ( ! found ) { final PatternFilterBinding binding = new PatternFilterBinding ( handler . getPath ( ) , handler ) ; allFilterBindings . add ( binding ) ; } } } }


Input: 根据浏览器If - Modified - Since Header 计算文件是否已被修改 . <p / > 如果无修改 checkIfModify返回false 设置304 not modify status . [CODESPLIT] public static boolean checkIfModifiedSince ( HttpServletRequest request , HttpServletResponse response , long lastModified ) { long ifModifiedSince = request . getDateHeader ( HttpHeaders . IF_MODIFIED_SINCE ) ; if ( ( ifModifiedSince != - 1 ) && ( lastModified < ( ifModifiedSince + 1000 ) ) ) { response . setStatus ( HttpServletResponse . SC_NOT_MODIFIED ) ; return false ; } return true ; }


Input: 根据浏览器 If - None - Match Header 计算Etag是否已无效 . <p / > 如果Etag有效 checkIfNoneMatch返回false 设置304 not modify status . [CODESPLIT] public static boolean checkIfNoneMatchEtag ( HttpServletRequest request , HttpServletResponse response , String etag ) { String headerValue = request . getHeader ( HttpHeaders . IF_NONE_MATCH ) ; if ( headerValue != null ) { boolean conditionSatisfied = false ; if ( ! StringPool . ASTERISK . equals ( headerValue ) ) { StringTokenizer commaTokenizer = new StringTokenizer ( headerValue , StringPool . COMMA ) ; while ( ! conditionSatisfied && commaTokenizer . hasMoreTokens ( ) ) { String currentToken = commaTokenizer . nextToken ( ) ; if ( currentToken . trim ( ) . equals ( etag ) ) { conditionSatisfied = true ; } } } else { conditionSatisfied = true ; } if ( conditionSatisfied ) { response . setStatus ( HttpServletResponse . SC_NOT_MODIFIED ) ; response . setHeader ( HttpHeaders . ETAG , etag ) ; return false ; } } return true ; }


Input: 设置让浏览器弹出下载对话框的Header . [CODESPLIT] public static void setFileDownloadHeader ( HttpServletResponse response , String fileName ) { try { // 中文文件名支持 String encodedfileName = new String ( fileName . getBytes ( ) , "ISO8859-1" ) ; response . setHeader ( HttpHeaders . CONTENT_DISPOSITION , "attachment; filename=\"" + encodedfileName + StringPool . QUOTE ) ; } catch ( UnsupportedEncodingException ignored ) { } }


Input: 取得带相同前缀的Request Parameters copy from spring WebUtils . <p / > 返回的结果的Parameter名已去除前缀 . [CODESPLIT] public static Map < String , Object > getParametersStartingWith ( ServletRequest request , String prefix ) { Validate . notNull ( request , "Request must not be null" ) ; Enumeration paramNames = request . getParameterNames ( ) ; Map < String , Object > params = new TreeMap < String , Object > ( ) ; if ( prefix == null ) { prefix = "" ; } while ( ( paramNames != null ) && paramNames . hasMoreElements ( ) ) { String paramName = ( String ) paramNames . nextElement ( ) ; if ( "" . equals ( prefix ) || paramName . startsWith ( prefix ) ) { String unprefixed = paramName . substring ( prefix . length ( ) ) ; String [ ] values = request . getParameterValues ( paramName ) ; if ( ( values == null ) || ( values . length == 0 ) ) { // Do nothing, no values found at all. } else if ( values . length > 1 ) { params . put ( unprefixed , values ) ; } else { params . put ( unprefixed , values [ 0 ] ) ; } } } return params ; }


Input: 组合Parameters生成Query String的Parameter部分 并在paramter name上加上prefix . [CODESPLIT] public static String encodeParameterStringWithPrefix ( Map < String , Object > params , String prefix ) { if ( ( params == null ) || ( params . size ( ) == 0 ) ) { return "" ; } if ( prefix == null ) { prefix = "" ; } StringBuilder queryStringBuilder = new StringBuilder ( ) ; Iterator < Map . Entry < String , Object > > it = params . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { Map . Entry < String , Object > entry = it . next ( ) ; queryStringBuilder . append ( prefix ) . append ( entry . getKey ( ) ) . append ( ' ' ) . append ( entry . getValue ( ) ) ; if ( it . hasNext ( ) ) { queryStringBuilder . append ( ' ' ) ; } } return queryStringBuilder . toString ( ) ; }


Input: 客户端对Http Basic验证的 Header进行编码 . [CODESPLIT] public static String encodeHttpBasic ( String userName , String password ) { String encode = userName + StringPool . COLON + password ; return "Basic " + EncodeKit . encodeBase64 ( encode . getBytes ( ) ) ; }


Input: Delimeter that separates role names in tag attribute [CODESPLIT] @ Override protected boolean showTagBody ( String roleName ) { boolean hasAnyRole = false ; Subject subject = getSubject ( ) ; if ( subject != null ) { // Iterate through roles and check to see if the user has one of the roles for ( String role : roleName . split ( StringPool . COMMA ) ) { if ( subject . hasRole ( role . trim ( ) ) ) { hasAnyRole = true ; break ; } } } return hasAnyRole ; }


Input: appConfig配置所有参数 重写freemarker中的 reader方法，读取该配置文件 [CODESPLIT] private static Configuration getAppConfiguration ( ) { if ( appConfig == null ) { //从freemarker 视图中获取所有配置 appConfig = ( Configuration ) FreeMarkerRender . getConfiguration ( ) . clone ( ) ; try { //设置模板路径 appConfig . setDirectoryForTemplateLoading ( new File ( PathKit . getWebRootPath ( ) + Goja . viewPath ) ) ; appConfig . setObjectWrapper ( new BeansWrapperBuilder ( Configuration . VERSION_2_3_21 ) . build ( ) ) ; } catch ( IOException e ) { logger . error ( "The Freemarkers has error!" , e ) ; } } return appConfig ; }


Input: 渲染模版为字符串，并制定参数 [CODESPLIT] public static String processString ( String tpl , Map < String , Object > renderParams ) { if ( appConfig == null ) { getAppConfiguration ( ) ; } StringWriter result = new StringWriter ( ) ; try { Template template = appConfig . getTemplate ( tpl ) ; template . process ( renderParams , result ) ; } catch ( IOException e ) { throw new RenderException ( e ) ; } catch ( TemplateException e ) { throw new RenderException ( e ) ; } return result . toString ( ) ; }


Input: 将Freemakrer的字符串模版，渲染参数为字符串形式的结果。 [CODESPLIT] public static String renderStrTemplate ( String strTemplat , Map < String , Object > renderParams ) { stringLoader . putTemplate ( UPDATE_RESPONSE_TEMPLATE , strTemplat ) ; stringConfig . setTemplateLoader ( stringLoader ) ; Writer out = new StringWriter ( 2048 ) ; try { Template tpl = stringConfig . getTemplate ( UPDATE_RESPONSE_TEMPLATE , StringPool . UTF_8 ) ; tpl . process ( renderParams , out ) ; } catch ( IOException e ) { Logger . error ( "Get update response template occurs error." , e ) ; } catch ( TemplateException e ) { Logger . error ( "Process template occurs error.template content is:\n {}" , e , strTemplat ) ; throw new IllegalArgumentException ( "Error update response template." , e ) ; } return out . toString ( ) ; }


Input: 生成HTML [CODESPLIT] public static void makeHtml ( String tlDirectory , String tlName , Map < String , Object > paramMap , String htmlPath ) { FileOutputStream fileOutputStream = null ; OutputStreamWriter outputStreamWriter = null ; try { Configuration configuration = new Configuration ( Configuration . VERSION_2_3_22 ) ; File file = new File ( tlDirectory ) ; // .ftl模板目录 configuration . setDirectoryForTemplateLoading ( file ) ; configuration . setObjectWrapper ( new DefaultObjectWrapper ( Configuration . VERSION_2_3_22 ) ) ; Template template = configuration . getTemplate ( tlName , StringPool . UTF_8 ) ; File file2 = new File ( htmlPath ) ; // 生成html目录 fileOutputStream = new FileOutputStream ( file2 ) ; outputStreamWriter = new OutputStreamWriter ( fileOutputStream , StringPool . UTF_8 ) ; BufferedWriter bufferedWriter = new BufferedWriter ( outputStreamWriter ) ; template . process ( paramMap , bufferedWriter ) ; bufferedWriter . flush ( ) ; outputStreamWriter . close ( ) ; fileOutputStream . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } catch ( TemplateException e ) { e . printStackTrace ( ) ; } finally { if ( null != fileOutputStream ) { try { fileOutputStream . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } if ( null != outputStreamWriter ) { try { outputStreamWriter . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } }


Input: Converts packing Long Int [CODESPLIT] public static int getInt ( Long l ) { return ( l == null || l > Integer . MAX_VALUE ) ? 0 : l . intValue ( ) ; }