signature: public class EntitySelectorConfig { public EntityDescriptor extractEntityDescriptor ( HeuristicConfigPolicy configPolicy ) { } }

implementation: if ( entityClass != null ) { SolutionDescriptor solutionDescriptor = configPolicy . getSolutionDescriptor ( ) ; EntityDescriptor entityDescriptor = solutionDescriptor . getEntityDescriptorStrict ( entityClass ) ; if ( entityDescriptor == null ) { throw new IllegalArgumentException ( "The selectorConfig (" + this + ") has an entityClass (" + entityClass + ") that is not a known planning entity.\n" + "Check your solver configuration. If that class (" + entityClass . getSimpleName ( ) + ") is not in the entityClassSet (" + solutionDescriptor . getEntityClassSet ( ) + "), check your " + PlanningSolution . class . getSimpleName ( ) + " implementation's annotated methods too." ) ; } return entityDescriptor ; } else if ( mimicSelectorRef != null ) { return configPolicy . getEntityMimicRecorder ( mimicSelectorRef ) . getEntityDescriptor ( ) ; } else { return null ; }


signature:
public class ConfigUtils { /** * A relaxed version of { @ link # mergeProperty ( Object , Object ) } . Used primarily for merging failed benchmarks ,
 * where a property remains the same over benchmark runs ( for example : dataset problem size ) , but the property in
 * the failed benchmark isn ' t initialized , therefore null . When merging , we can still use the correctly initialized
 * property of the benchmark that didn ' t fail .
 * Null - handling :
 * < ul >
 * < li > if < strong > both < / strong > properties < strong > are null < / strong > , returns null < / li >
 * < li > if < strong > only one < / strong > of the properties < strong > is not null < / strong > , returns that property < / li >
 * < li > if < strong > both < / strong > properties < strong > are not null < / strong > , returns { @ link # mergeProperty ( Object , Object ) } < / li >
 * < / ul >
 * @ see # mergeProperty ( Object , Object )
 * @ param a property { @ code a }
 * @ param b property { @ code b }
 * @ param < T > the type of property { @ code a } and { @ code b }
 * @ return sometimes null */
public static < T > T meldProperty ( T a , T b ) { } }

implementation: if ( a == null && b == null ) { return null ; } else if ( a == null && b != null ) { return b ; } else if ( a != null && b == null ) { return a ; } else { return ConfigUtils . mergeProperty ( a , b ) ; }


signature:
public class ConfigUtils { /** * Divides and ceils the result without using floating point arithmetic . For floor division ,
 * see { @ link Math # floorDiv ( long , long ) } .
 * @ throws ArithmeticException if { @ code divisor = = 0}
 * @ param dividend the dividend
 * @ param divisor the divisor
 * @ return dividend / divisor , ceiled */
public static int ceilDivide ( int dividend , int divisor ) { } }

implementation: if ( divisor == 0 ) { throw new ArithmeticException ( "Cannot divide by zero: " + dividend + "/" + divisor ) ; } int correction ; if ( dividend % divisor == 0 ) { correction = 0 ; } else if ( Integer . signum ( dividend ) * Integer . signum ( divisor ) < 0 ) { correction = 0 ; } else { correction = 1 ; } return ( dividend / divisor ) + correction ;


signature: public class ConfigUtils { public static List < Class < ? > > getAllAnnotatedLineageClasses ( Class < ? > bottomClass , Class < ? extends Annotation > annotation ) { } }

implementation: if ( ! bottomClass . isAnnotationPresent ( annotation ) ) { return Collections . emptyList ( ) ; } List < Class < ? > > lineageClassList = new ArrayList < > ( ) ; lineageClassList . add ( bottomClass ) ; Class < ? > superclass = bottomClass . getSuperclass ( ) ; lineageClassList . addAll ( getAllAnnotatedLineageClasses ( superclass , annotation ) ) ; for ( Class < ? > superInterface : bottomClass . getInterfaces ( ) ) { lineageClassList . addAll ( getAllAnnotatedLineageClasses ( superInterface , annotation ) ) ; } return lineageClassList ;


signature: public class LateAcceptanceAcceptor { @ Override public void phaseStarted ( LocalSearchPhaseScope phaseScope ) { } }

implementation: super . phaseStarted ( phaseScope ) ; validate ( ) ; previousScores = new Score [ lateAcceptanceSize ] ; Score initialScore = phaseScope . getBestScore ( ) ; for ( int i = 0 ; i < previousScores . length ; i ++ ) { previousScores [ i ] = initialScore ; } lateScoreIndex = 0 ;


signature: public class ScanAnnotatedClassesConfig { public SolutionDescriptor buildSolutionDescriptor ( SolverConfigContext configContext , ScoreDefinition deprecatedScoreDefinition ) { } }

implementation: ClassLoader [ ] classLoaders ; if ( configContext . getClassLoader ( ) != null ) { classLoaders = new ClassLoader [ ] { configContext . getClassLoader ( ) } ; } else if ( configContext . getKieContainer ( ) != null ) { classLoaders = new ClassLoader [ ] { configContext . getKieContainer ( ) . getClassLoader ( ) } ; ReflectionsKieVfsUrlType . register ( configContext . getKieContainer ( ) ) ; } else { classLoaders = new ClassLoader [ 0 ] ; } ConfigurationBuilder builder = new ConfigurationBuilder ( ) ; if ( ! ConfigUtils . isEmptyCollection ( packageIncludeList ) ) { FilterBuilder filterBuilder = new FilterBuilder ( ) ; for ( String packageInclude : packageIncludeList ) { if ( StringUtils . isEmpty ( packageInclude ) ) { throw new IllegalArgumentException ( "The scanAnnotatedClasses (" + this + ") has a packageInclude (" + packageInclude + ") that is empty or null. Remove it or fill it in." ) ; } builder . addUrls ( ReflectionsWorkaroundClasspathHelper . forPackage ( packageInclude , classLoaders ) ) ; filterBuilder . includePackage ( packageInclude ) ; } builder . filterInputsBy ( filterBuilder ) ; } else { builder . addUrls ( ReflectionsWorkaroundClasspathHelper . forPackage ( "" , classLoaders ) ) ; } builder . setClassLoaders ( classLoaders ) ; Reflections reflections = new Reflections ( builder ) ; Class < ? > solutionClass = loadSolutionClass ( reflections ) ; List < Class < ? > > entityClassList = loadEntityClassList ( reflections ) ; return SolutionDescriptor . buildSolutionDescriptor ( solutionClass , entityClassList , deprecatedScoreDefinition ) ;


signature:
public class ScanAnnotatedClassesConfig { /** * TODO We need unit test for this : annotation scanning with TestdataUnannotatedExtendedEntity */
private void retainOnlyClassesWithDeclaredAnnotation ( Set < Class < ? > > classSet , Class < ? extends Annotation > annotation ) { } }

implementation: classSet . removeIf ( clazz -> ! clazz . isAnnotationPresent ( annotation ) ) ;


signature:
public class RandomUtils { /** * Mimics { @ link Random # nextInt ( int ) } for longs .
 * @ param random never null
 * @ param n { @ code > 0L }
 * @ return like { @ link Random # nextInt ( int ) } but for a long
 * @ see Random # nextInt ( int ) */
public static long nextLong ( Random random , long n ) { } }

implementation:
// This code is based on java . util . Random # nextInt ( int ) ' s javadoc .
if ( n <= 0L ) { throw new IllegalArgumentException ( "n must be positive" ) ; } if ( n < Integer . MAX_VALUE ) { return ( long ) random . nextInt ( ( int ) n ) ; } long bits ; long val ; do { bits = ( random . nextLong ( ) << 1 ) >>> 1 ; val = bits % n ; } while ( bits - val + ( n - 1L ) < 0L ) ; return val ;


signature: public class DefaultSolver { @ Override public final Solution_ solve ( Solution_ problem ) { } }

implementation: if ( problem == null ) { throw new IllegalArgumentException ( "The problem (" + problem + ") must not be null." ) ; } solverScope . setBestSolution ( problem ) ; outerSolvingStarted ( solverScope ) ; boolean restartSolver = true ; while ( restartSolver ) { solvingStarted ( solverScope ) ; runPhases ( solverScope ) ; solvingEnded ( solverScope ) ; restartSolver = checkProblemFactChanges ( ) ; } outerSolvingEnded ( solverScope ) ; return solverScope . getBestSolution ( ) ;


signature: public class AbstractCachingEntitySelector { @ Override public void constructCache ( DefaultSolverScope solverScope ) { } }

implementation: long childSize = childEntitySelector . getSize ( ) ; if ( childSize > ( long ) Integer . MAX_VALUE ) { throw new IllegalStateException ( "The selector (" + this + ") has a childEntitySelector (" + childEntitySelector + ") with childSize (" + childSize + ") which is higher than Integer.MAX_VALUE." ) ; } cachedEntityList = new ArrayList < > ( ( int ) childSize ) ; childEntitySelector . iterator ( ) . forEachRemaining ( cachedEntityList :: add ) ; logger . trace ( "    Created cachedEntityList: size ({}), entitySelector ({})." , cachedEntityList . size ( ) , this ) ;


signature: public class ScoreCalculationCountTermination { @ Override public ScoreCalculationCountTermination createChildThreadTermination ( DefaultSolverScope solverScope , ChildThreadType childThreadType ) { } }

implementation:
if ( childThreadType == ChildThreadType . PART_THREAD ) { // The ScoreDirector . calculationCount of partitions is maxed , not summed .
return new ScoreCalculationCountTermination ( scoreCalculationCountLimit ) ; } else { throw new IllegalStateException ( "The childThreadType (" + childThreadType + ") is not implemented." ) ; }


signature:
public class InvestmentSolution { /** * Not incremental . */
public long calculateStandardDeviationSquaredFemtos ( ) { } }

implementation:
long totalFemtos = 0L ; for ( AssetClassAllocation a : assetClassAllocationList ) { for ( AssetClassAllocation b : assetClassAllocationList ) { if ( a == b ) { totalFemtos += a . getQuantifiedStandardDeviationRiskMicros ( ) * b . getQuantifiedStandardDeviationRiskMicros ( ) * 1000L ; } else { // Matches twice : once for ( A , B ) and once for ( B , A )
long correlationMillis = a . getAssetClass ( ) . getCorrelationMillisMap ( ) . get ( b . getAssetClass ( ) ) ; totalFemtos += a . getQuantifiedStandardDeviationRiskMicros ( ) * b . getQuantifiedStandardDeviationRiskMicros ( ) * correlationMillis ; } } } return totalFemtos ;


signature: public class MimicReplayingValueSelector { @ Override public void phaseStarted ( AbstractPhaseScope phaseScope ) { } }

implementation:
super . phaseStarted ( phaseScope ) ; // Doing this in phaseStarted instead of stepStarted due to QueuedValuePlacer compatibility
hasRecordingCreated = false ; recordingCreated = false ;


signature: public class SimpleScoreHolder { @ Override public void configureConstraintWeight ( Rule rule , SimpleScore constraintWeight ) { } }

implementation: super . configureConstraintWeight ( rule , constraintWeight ) ; BiConsumer < RuleContext , Integer > matchExecutor ; if ( constraintWeight . equals ( SimpleScore . ZERO ) ) { matchExecutor = ( RuleContext kcontext , Integer matchWeight ) -> { } ; } else { matchExecutor = ( RuleContext kcontext , Integer matchWeight ) -> addConstraintMatch ( kcontext , constraintWeight . getScore ( ) * matchWeight ) ; } matchExecutorByNumberMap . put ( rule , matchExecutor ) ;


signature: public class UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination { @ Override public UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination createChildThreadTermination ( DefaultSolverScope solverScope , ChildThreadType childThreadType ) { } }

implementation: return new UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination ( unimprovedTimeMillisSpentLimit , unimprovedScoreDifferenceThreshold ) ;


signature: public class ConstraintMatchTotalBestScoreSubSingleStatistic { @ Override public void writeGraphFiles ( BenchmarkReport benchmarkReport ) { } }

implementation:
List < Map < String , XYSeries > > constraintIdToWeightSeriesMapList = new ArrayList < > ( BenchmarkReport . CHARTED_SCORE_LEVEL_SIZE ) ; for ( ConstraintMatchTotalBestScoreStatisticPoint point : getPointList ( ) ) { long timeMillisSpent = point . getTimeMillisSpent ( ) ; double [ ] levelValues = ScoreUtils . extractLevelDoubles ( point . getScoreTotal ( ) ) ; for ( int i = 0 ; i < levelValues . length && i < BenchmarkReport . CHARTED_SCORE_LEVEL_SIZE ; i ++ ) { if ( i >= constraintIdToWeightSeriesMapList . size ( ) ) { constraintIdToWeightSeriesMapList . add ( new LinkedHashMap < > ( ) ) ; } Map < String , XYSeries > constraintIdToWeightSeriesMap = constraintIdToWeightSeriesMapList . get ( i ) ; XYSeries weightSeries = constraintIdToWeightSeriesMap . computeIfAbsent ( point . getConstraintId ( ) , k -> new XYSeries ( point . getConstraintName ( ) + " weight" ) ) ; // Only add changes
if ( levelValues [ i ] != ( ( weightSeries . getItemCount ( ) == 0 ) ? 0.0 : weightSeries . getY ( weightSeries . getItemCount ( ) - 1 ) . doubleValue ( ) ) ) { weightSeries . add ( timeMillisSpent , levelValues [ i ] ) ; } } } long timeMillisSpent = subSingleBenchmarkResult . getTimeMillisSpent ( ) ; for ( Map < String , XYSeries > constraintIdToWeightSeriesMap : constraintIdToWeightSeriesMapList ) { for ( Iterator < Map . Entry < String , XYSeries > > it = constraintIdToWeightSeriesMap . entrySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { XYSeries weightSeries = it . next ( ) . getValue ( ) ; if ( weightSeries . getItemCount ( ) == 0 ) { // Only show the constraint type on the score levels that it affects
it . remove ( ) ; } else { // Draw a horizontal line from the last new best step to how long the solver actually ran
weightSeries . add ( timeMillisSpent , weightSeries . getY ( weightSeries . getItemCount ( ) - 1 ) . doubleValue ( ) ) ; } } } graphFileList = new ArrayList < > ( constraintIdToWeightSeriesMapList . size ( ) ) ; for ( int scoreLevelIndex = 0 ; scoreLevelIndex < constraintIdToWeightSeriesMapList . size ( ) ; scoreLevelIndex ++ ) { XYPlot plot = createPlot ( benchmarkReport , scoreLevelIndex ) ; // No direct ascending lines between 2 points , but a stepping line instead
XYItemRenderer renderer = new XYStepRenderer ( ) ; plot . setRenderer ( renderer ) ; XYSeriesCollection seriesCollection = new XYSeriesCollection ( ) ; for ( XYSeries series : constraintIdToWeightSeriesMapList . get ( scoreLevelIndex ) . values ( ) ) { seriesCollection . addSeries ( series ) ; } plot . setDataset ( seriesCollection ) ; String scoreLevelLabel = subSingleBenchmarkResult . getSingleBenchmarkResult ( ) . getProblemBenchmarkResult ( ) . findScoreLevelLabel ( scoreLevelIndex ) ; JFreeChart chart = new JFreeChart ( subSingleBenchmarkResult . getName ( ) + " constraint match total best " + scoreLevelLabel + " diff statistic" , JFreeChart . DEFAULT_TITLE_FONT , plot , true ) ; graphFileList . add ( writeChartToImageFile ( chart , "ConstraintMatchTotalBestScoreStatisticLevel" + scoreLevelIndex ) ) ; }


signature: public class ChildThreadPlumbingTermination { @ Override public synchronized boolean isSolverTerminated ( DefaultSolverScope solverScope ) { } }

implementation:
// Destroying a thread pool with solver threads will only cause it to interrupt those child solver threads
if ( Thread . currentThread ( ) . isInterrupted ( ) ) { // Does not clear the interrupted flag
logger . info ( "A child solver thread got interrupted, so these child solvers are terminating early." ) ; terminateChildren = true ; } return terminateChildren ;


signature: public class SolverConfigContext { public ClassLoader determineActualClassLoader ( ) { } }

implementation: if ( classLoader != null ) { return classLoader ; } else if ( kieContainer != null ) { return kieContainer . getClassLoader ( ) ; } return getClass ( ) . getClassLoader ( ) ;


signature: public class ProbabilityMoveSelector { @ Override public void constructCache ( DefaultSolverScope solverScope ) { } }

implementation: cachedMoveMap = new TreeMap < > ( ) ; ScoreDirector scoreDirector = solverScope . getScoreDirector ( ) ; double probabilityWeightOffset = 0L ; for ( Move entity : childMoveSelector ) { double probabilityWeight = probabilityWeightFactory . createProbabilityWeight ( scoreDirector , entity ) ; cachedMoveMap . put ( probabilityWeightOffset , entity ) ; probabilityWeightOffset += probabilityWeight ; } probabilityWeightTotal = probabilityWeightOffset ;


signature: public class CompositeMove { @ Override public String getSimpleMoveTypeDescription ( ) { } }

implementation: Set < String > childMoveTypeDescriptionSet = new TreeSet < > ( ) ; for ( Move < Solution_ > move : moves ) { childMoveTypeDescriptionSet . add ( move . getSimpleMoveTypeDescription ( ) ) ; } StringBuilder moveTypeDescription = new StringBuilder ( 20 * ( moves . length + 1 ) ) ; moveTypeDescription . append ( getClass ( ) . getSimpleName ( ) ) . append ( "(" ) ; String delimiter = "" ; for ( String childMoveTypeDescription : childMoveTypeDescriptionSet ) { moveTypeDescription . append ( delimiter ) . append ( "* " ) . append ( childMoveTypeDescription ) ; delimiter = ", " ; } moveTypeDescription . append ( ")" ) ; return moveTypeDescription . toString ( ) ;


signature: public class PillarSwapMoveSelectorConfig { @ Override public MoveSelector buildBaseMoveSelector ( HeuristicConfigPolicy configPolicy , SelectionCacheType minimumCacheType , boolean randomSelection ) { } }

implementation: PillarSelectorConfig pillarSelectorConfig_ = pillarSelectorConfig == null ? new PillarSelectorConfig ( ) : pillarSelectorConfig ; PillarSelector leftPillarSelector = pillarSelectorConfig_ . buildPillarSelector ( configPolicy , minimumCacheType , SelectionOrder . fromRandomSelectionBoolean ( randomSelection ) , variableNameIncludeList ) ; PillarSelectorConfig rightPillarSelectorConfig = defaultIfNull ( secondaryPillarSelectorConfig , pillarSelectorConfig_ ) ; PillarSelector rightPillarSelector = rightPillarSelectorConfig . buildPillarSelector ( configPolicy , minimumCacheType , SelectionOrder . fromRandomSelectionBoolean ( randomSelection ) , variableNameIncludeList ) ; List < GenuineVariableDescriptor > variableDescriptorList = deduceVariableDescriptorList ( leftPillarSelector . getEntityDescriptor ( ) , variableNameIncludeList ) ; return new PillarSwapMoveSelector ( leftPillarSelector , rightPillarSelector , variableDescriptorList , randomSelection ) ;


signature: public class NoChangePhaseConfig { @ Override public NoChangePhase buildPhase ( int phaseIndex , HeuristicConfigPolicy solverConfigPolicy , BestSolutionRecaller bestSolutionRecaller , Termination solverTermination ) { } }

implementation: HeuristicConfigPolicy phaseConfigPolicy = solverConfigPolicy . createPhaseConfigPolicy ( ) ; return new NoChangePhase ( phaseIndex , solverConfigPolicy . getLogIndentation ( ) , bestSolutionRecaller , buildPhaseTermination ( phaseConfigPolicy , solverTermination ) ) ;


signature: public class AbstractCachingValueSelector { @ Override public void constructCache ( DefaultSolverScope solverScope ) { } }

implementation:
long childSize = childValueSelector . getSize ( ) ; if ( childSize > ( long ) Integer . MAX_VALUE ) { throw new IllegalStateException ( "The selector (" + this + ") has a childValueSelector (" + childValueSelector + ") with childSize (" + childSize + ") which is higher than Integer.MAX_VALUE." ) ; } cachedValueList = new ArrayList < > ( ( int ) childSize ) ; // TODO Fail - faster if a non FromSolutionPropertyValueSelector is used
childValueSelector . iterator ( ) . forEachRemaining ( cachedValueList :: add ) ; logger . trace ( "    Created cachedValueList: size ({}), valueSelector ({})." , cachedValueList . size ( ) , this ) ;


signature: public class ConstructionHeuristicPhaseConfig { @ Override public ConstructionHeuristicPhase buildPhase ( int phaseIndex , HeuristicConfigPolicy solverConfigPolicy , BestSolutionRecaller bestSolutionRecaller , Termination solverTermination ) { } }

implementation:
HeuristicConfigPolicy phaseConfigPolicy = solverConfigPolicy . createPhaseConfigPolicy ( ) ; phaseConfigPolicy . setReinitializeVariableFilterEnabled ( true ) ; phaseConfigPolicy . setInitializedChainedValueFilterEnabled ( true ) ; DefaultConstructionHeuristicPhase phase = new DefaultConstructionHeuristicPhase ( phaseIndex , solverConfigPolicy . getLogIndentation ( ) , bestSolutionRecaller , buildPhaseTermination ( phaseConfigPolicy , solverTermination ) ) ; phase . setDecider ( buildDecider ( phaseConfigPolicy , phase . getTermination ( ) ) ) ; ConstructionHeuristicType constructionHeuristicType_ = defaultIfNull ( constructionHeuristicType , ConstructionHeuristicType . ALLOCATE_ENTITY_FROM_QUEUE ) ; phaseConfigPolicy . setEntitySorterManner ( entitySorterManner != null ? entitySorterManner : constructionHeuristicType_ . getDefaultEntitySorterManner ( ) ) ; phaseConfigPolicy . setValueSorterManner ( valueSorterManner != null ? valueSorterManner : constructionHeuristicType_ . getDefaultValueSorterManner ( ) ) ; EntityPlacerConfig entityPlacerConfig ; if ( ConfigUtils . isEmptyCollection ( entityPlacerConfigList ) ) { entityPlacerConfig = buildUnfoldedEntityPlacerConfig ( phaseConfigPolicy , constructionHeuristicType_ ) ; } else if ( entityPlacerConfigList . size ( ) == 1 ) { entityPlacerConfig = entityPlacerConfigList . get ( 0 ) ; if ( constructionHeuristicType != null ) { throw new IllegalArgumentException ( "The constructionHeuristicType (" + constructionHeuristicType + ") must not be configured if the entityPlacerConfig (" + entityPlacerConfig + ") is explicitly configured." ) ; } if ( moveSelectorConfigList != null ) { throw new IllegalArgumentException ( "The moveSelectorConfigList (" + moveSelectorConfigList + ") can not be configured if the entityPlacerConfig (" + entityPlacerConfig + ") is explicitly configured." ) ; } } else { // TODO entityPlacerConfigList is only a List because of XStream limitations .
throw new IllegalArgumentException ( "The entityPlacerConfigList (" + entityPlacerConfigList + ") must be a singleton or empty. Use multiple " + ConstructionHeuristicPhaseConfig . class + " elements to initialize multiple entity classes." ) ; } EntityPlacer entityPlacer = entityPlacerConfig . buildEntityPlacer ( phaseConfigPolicy ) ; phase . setEntityPlacer ( entityPlacer ) ; EnvironmentMode environmentMode = phaseConfigPolicy . getEnvironmentMode ( ) ; if ( environmentMode . isNonIntrusiveFullAsserted ( ) ) { phase . setAssertStepScoreFromScratch ( true ) ; } if ( environmentMode . isIntrusiveFastAsserted ( ) ) { phase . setAssertExpectedStepScore ( true ) ; phase . setAssertShadowVariablesAreNotStaleAfterStep ( true ) ; } return phase ;


signature: public class SimpleBigDecimalScoreHolder { @ Override public void configureConstraintWeight ( Rule rule , SimpleBigDecimalScore constraintWeight ) { } }

implementation: super . configureConstraintWeight ( rule , constraintWeight ) ; BiConsumer < RuleContext , BigDecimal > matchExecutor ; if ( constraintWeight . equals ( SimpleBigDecimalScore . ZERO ) ) { matchExecutor = ( RuleContext kcontext , BigDecimal matchWeight ) -> { } ; } else { matchExecutor = ( RuleContext kcontext , BigDecimal matchWeight ) -> addConstraintMatch ( kcontext , constraintWeight . getScore ( ) . multiply ( matchWeight ) ) ; } matchExecutorByNumberMap . put ( rule , matchExecutor ) ;


signature:
public class SolutionDescriptor { /** * Only called if Drools score calculation is used . */
public void checkIfProblemFactsExist ( ) { } }

implementation: if ( problemFactCollectionMemberAccessorMap . isEmpty ( ) && problemFactMemberAccessorMap . isEmpty ( ) ) { throw new IllegalStateException ( "The solutionClass (" + solutionClass + ") must have at least 1 member with a " + ProblemFactCollectionProperty . class . getSimpleName ( ) + " annotation or a " + ProblemFactProperty . class . getSimpleName ( ) + " annotation" + " when used with Drools score calculation." ) ; }


signature: public class SolutionDescriptor { public Collection < Object > getAllFacts ( Solution_ solution ) { } }

implementation:
Collection < Object > facts = new ArrayList < > ( ) ; // Adds both entities and facts
Arrays . asList ( entityMemberAccessorMap , problemFactMemberAccessorMap ) . forEach ( map -> map . forEach ( ( key , memberAccessor ) -> { Object object = extractMemberObject ( memberAccessor , solution ) ; if ( object != null ) { facts . add ( object ) ; } } ) ) ; entityCollectionMemberAccessorMap . forEach ( ( key , memberAccessor ) -> facts . addAll ( extractMemberCollectionOrArray ( memberAccessor , solution , false ) ) ) ; problemFactCollectionMemberAccessorMap . forEach ( ( key , memberAccessor ) -> facts . addAll ( extractMemberCollectionOrArray ( memberAccessor , solution , true ) ) ) ; return facts ;


signature:
public class SolutionDescriptor { /** * Calculates an indication on how big this problem instance is .
 * This is intentionally very loosely defined for now .
 * @ param solution never null
 * @ return { @ code > = 0} */
public long getProblemScale ( Solution_ solution ) { } }

implementation: long problemScale = 0L ; for ( Iterator < Object > it = extractAllEntitiesIterator ( solution ) ; it . hasNext ( ) ; ) { Object entity = it . next ( ) ; EntityDescriptor < Solution_ > entityDescriptor = findEntityDescriptorOrFail ( entity . getClass ( ) ) ; problemScale += entityDescriptor . getProblemScale ( solution , entity ) ; } return problemScale ;


signature: public class PillarSwapMove { @ Override public boolean isMoveDoable ( ScoreDirector < Solution_ > scoreDirector ) { } }

implementation: boolean movable = false ; for ( GenuineVariableDescriptor < Solution_ > variableDescriptor : variableDescriptorList ) { Object leftValue = variableDescriptor . getValue ( leftPillar . get ( 0 ) ) ; Object rightValue = variableDescriptor . getValue ( rightPillar . get ( 0 ) ) ; if ( ! Objects . equals ( leftValue , rightValue ) ) { movable = true ; if ( ! variableDescriptor . isValueRangeEntityIndependent ( ) ) { ValueRangeDescriptor < Solution_ > valueRangeDescriptor = variableDescriptor . getValueRangeDescriptor ( ) ; Solution_ workingSolution = scoreDirector . getWorkingSolution ( ) ; for ( Object rightEntity : rightPillar ) { ValueRange rightValueRange = valueRangeDescriptor . extractValueRange ( workingSolution , rightEntity ) ; if ( ! rightValueRange . contains ( leftValue ) ) { return false ; } } for ( Object leftEntity : leftPillar ) { ValueRange leftValueRange = valueRangeDescriptor . extractValueRange ( workingSolution , leftEntity ) ; if ( ! leftValueRange . contains ( rightValue ) ) { return false ; } } } } } return movable ;


signature:
public class MultiLocks { /** * { @ inheritDoc } */
@ Override public < T > Task < T > synchronize ( Task < T > task , long deadline ) { } }

implementation: for ( ZKLock lock : _locks ) { task = lock . synchronize ( task , deadline ) ; } return task ;


signature:
public class ParSeqRestClient { /** * Generates a task name for the request .
 * @ param request
 * @ return a task name */
static String generateTaskName ( final Request < ? > request ) { } }

implementation: return request . getBaseUriTemplate ( ) + " " + OperationNameGenerator . generate ( request . getMethod ( ) , request . getMethodName ( ) ) ;


signature:
public class ParSeqRestClient { /** * Check whether per - request timeout is specified in the given request context . */
private boolean hasRequestContextTimeout ( RequestContext requestContext ) { } }

implementation: Object requestTimeout = requestContext . getLocalAttr ( R2Constants . REQUEST_TIMEOUT ) ; return ( requestTimeout instanceof Number ) && ( ( ( Number ) requestTimeout ) . intValue ( ) > 0 ) ;


signature:
public class ParSeqRestClient { /** * check whether we need to apply timeout to a rest . li request task . */
private boolean needApplyTaskTimeout ( RequestContext requestContext , ConfigValue < Long > timeout ) { } }

implementation:
// return false if no timeout configured or per - request timeout already specified in request context
return timeout . getValue ( ) != null && timeout . getValue ( ) > 0 && ! hasRequestContextTimeout ( requestContext ) ;


signature:
public class ParSeqRestClient { /** * Apply timeout to a ParSeq rest . li request task through parseq timer task . */
private < T > Task < Response < T > > createTaskWithTimeout ( final String name , final Request < T > request , final RequestContext requestContext , RequestConfig config ) { } }

implementation: ConfigValue < Long > timeout = config . getTimeoutMs ( ) ; Task < Response < T > > requestTask ; if ( RequestGroup . isBatchable ( request , config ) ) { requestTask = createBatchableTask ( name , request , requestContext , config ) ; } else { requestTask = Task . async ( name , ( ) -> sendRequest ( request , requestContext ) ) ; } if ( ! needApplyTaskTimeout ( requestContext , timeout ) ) { return requestTask ; } else { return withTimeout ( requestTask , timeout ) ; }


signature:
public class ParSeqRestClient { /** * We will distinguish two cases in applying timeout to a ParSeq rest . li request task through D2 request timeout .
 * Case 1 : There is no per request timeout specified in request context of rest . li request , timeout is configured
 * through ParSeqRestClient configuration . For this case , we will update request context as :
 * REQUEST _ TIMEOUT = configured timeout value
 * REQUEST _ TIMEOUT _ IGNORE _ IF _ HIGHER _ THAN _ DEFAULT = true
 * since in this case , ParSeqRestClient just wants to timeout this request from client side within configured timeout
 * without disturbing any lower layer load balancing behaviors .
 * Case 2 : There is per request timeout specified in rest . li request , and there may or may not have timeout specified
 * through ParSeqRestClient configuration . For this case , per request timeout specified in rest . li request always
 * takes precedence , ParSeq will interpret that users would like to use this to impact lower layer LB behavior , and
 * thus will pass down request context unchanged down . */
private < T > Task < Response < T > > createTaskWithD2Timeout ( final String name , final Request < T > request , final RequestContext requestContext , RequestConfig config ) { } }

implementation:
ConfigValue < Long > timeout = config . getTimeoutMs ( ) ; boolean taskNeedTimeout = needApplyTaskTimeout ( requestContext , timeout ) ; if ( taskNeedTimeout ) { // configure request context before creating parseq task from the request
requestContext . putLocalAttr ( R2Constants . REQUEST_TIMEOUT , timeout . getValue ( ) . intValue ( ) ) ; requestContext . putLocalAttr ( R2Constants . REQUEST_TIMEOUT_IGNORE_IF_HIGHER_THAN_DEFAULT , true ) ; } Task < Response < T > > requestTask ; if ( RequestGroup . isBatchable ( request , config ) ) { requestTask = createBatchableTask ( name , request , requestContext , config ) ; } else { requestTask = Task . async ( name , ( ) -> sendRequest ( request , requestContext ) ) ; } if ( ! taskNeedTimeout ) { return requestTask ; } else { // still enforce parseq client timeout if for some reason downstream services are not timed out properly .
return withTimeout ( requestTask , timeout ) ; }


signature:
public class PlanContext { /** * Creates a new { @ link PlanContext } from the current plan for the given root
 * { @ link Task } . The new plan can be completed independently from the current plan .
 * @ param root root task of the sub plan
 * @ return a new PlanContext if this plan is not completed . Otherwise , returns null . */
public PlanContext fork ( Task < ? > root ) { } }

implementation: int pending ; while ( ( pending = _pending . get ( ) ) > 0 ) { if ( _pending . compareAndSet ( pending , pending + 1 ) ) { return new PlanContext ( root , _id , _engine , _taskExecutor , _timerScheduler , _planClass , _taskLogger , _relationshipsBuilder , p -> done ( ) ) ; } } return null ;


signature:
public class GraphvizEngine { /** * Return task that has general HTTP status and body information based on the build task ' s result . */
public Task < HttpResponse > build ( final String hash , final InputStream body ) throws IOException { } }

implementation:
if ( hash == null ) { // Missing hash
String content = "Missing hash." ; LOG . info ( content ) ; return Task . value ( new HttpResponse ( HttpServletResponse . SC_BAD_REQUEST , content ) ) ; } else { // Have cache
if ( _hashManager . contains ( hash ) ) { LOG . info ( "hash found in cache: " + hash ) ; return Task . value ( new HttpResponse ( HttpServletResponse . SC_OK , "" ) ) ; } else { if ( body == null ) { // Missing body
String content = "Missing body." ; LOG . info ( content ) ; return Task . value ( new HttpResponse ( HttpServletResponse . SC_BAD_REQUEST , content ) ) ; } else if ( _dotLocation == null ) { // Missing dot
String content = "Missing dot." ; LOG . info ( content ) ; return Task . value ( new HttpResponse ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , content ) ) ; } else { // Build task
final Task < Exec . Result > buildTask = getBuildTask ( hash , body ) ; return buildTask . transform ( "result" , result -> { Integer status = null ; String content = null ; if ( result . isFailed ( ) ) { // Task fail
status = HttpServletResponse . SC_INTERNAL_SERVER_ERROR ; content = result . getError ( ) . toString ( ) ; } else { // Task success
switch ( result . get ( ) . getStatus ( ) ) { // Success
case 0 : _hashManager . add ( hash ) ; status = HttpServletResponse . SC_OK ; content = "" ; break ; // Timeout
case 137 : status = HttpServletResponse . SC_INTERNAL_SERVER_ERROR ; content = "graphviz process was killed because it did not finish within " + _timeoutMs + "ms" ; break ; // Unknown
default : status = HttpServletResponse . SC_INTERNAL_SERVER_ERROR ; content = writeGenericFailureInfo ( result . get ( ) ) ; break ; } } // Clean up cache
_inFlightBuildTasks . remove ( hash , buildTask ) ; return Success . of ( new HttpResponse ( status , content ) ) ; } ) ; } } }


signature:
public class GraphvizEngine { /** * Returns task that builds graph using graphviz . Returned task might be shared with other concurrent requests . */
private Task < Exec . Result > getBuildTask ( final String hash , final InputStream body ) { } }

implementation: Task < Exec . Result > existing = _inFlightBuildTasks . get ( hash ) ; if ( existing != null ) { LOG . info ( "using in flight shareable: " + hash ) ; return existing . shareable ( ) ; } else { Task < Exec . Result > newBuildTask = createNewBuildTask ( hash , body ) ; existing = _inFlightBuildTasks . putIfAbsent ( hash , newBuildTask ) ; if ( existing != null ) { LOG . info ( "using in flight shareable: " + hash ) ; return existing . shareable ( ) ; } else { return newBuildTask ; } }


signature:
public class GraphvizEngine { /** * Returns new task that builds graph using graphviz . */
private Task < Exec . Result > createNewBuildTask ( final String hash , final InputStream body ) { } }

implementation:
LOG . info ( "building: " + hash ) ; final Task < Void > createDotFile = Task . action ( "createDotFile" , ( ) -> Files . copy ( body , pathToCacheFile ( hash , "dot" ) , StandardCopyOption . REPLACE_EXISTING ) ) ; // Task that runs a graphviz command .
// We give process TIMEOUT _ MS time to finish , after that
// it will be forcefully killed .
final Task < Exec . Result > graphviz = _exec . command ( "graphviz" , _timeoutMs , TimeUnit . MILLISECONDS , _dotLocation , "-T" + Constants . OUTPUT_TYPE , "-Grankdir=LR" , "-Gnewrank=true" , "-Gbgcolor=transparent" , pathToCacheFile ( hash , "dot" ) . toString ( ) , "-o" , pathToCacheFile ( hash , Constants . OUTPUT_TYPE ) . toString ( ) ) ; // Since Exec utility allows only certain number of processes
// to run in parallel and rest is enqueued , we also specify
// timeout on a task level equal to 2 * graphviz timeout .
final Task < Exec . Result > graphvizWithTimeout = graphviz . withTimeout ( _timeoutMs * 2 , TimeUnit . MILLISECONDS ) ; return createDotFile . andThen ( graphvizWithTimeout ) ;


signature:
public class GraphvizEngine { /** * Writes error info to a String . */
private String writeGenericFailureInfo ( final Exec . Result result ) throws IOException { } }

implementation: StringBuilder sb = new StringBuilder ( ) ; sb . append ( "graphviz process returned: " ) . append ( result . getStatus ( ) ) . append ( "\n" ) . append ( "stdout:\n" ) ; Files . lines ( result . getStdout ( ) ) . forEach ( sb :: append ) ; sb . append ( "stderr:\n" ) ; Files . lines ( result . getStderr ( ) ) . forEach ( sb :: append ) ; return sb . toString ( ) ;


signature:
public class Tuple11TaskDelegate { /** * { @ inheritDoc } */
@ Override public Tuple11 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 > getOrDefault ( Tuple11 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 > defaultValue ) throws PromiseUnresolvedException { } }

implementation: return _task . getOrDefault ( defaultValue ) ;


signature:
public class Tuple11TaskDelegate { /** * { @ inheritDoc } */
@ Override public void contextRun ( Context context , Task < ? > parent , Collection < Task < ? > > predecessors ) { } }

implementation: _task . contextRun ( context , parent , predecessors ) ;


signature:
public class Tuple11TaskDelegate { /** * { @ inheritDoc } */
@ Override public boolean await ( long time , TimeUnit unit ) throws InterruptedException { } }

implementation: return _task . await ( time , unit ) ;


signature:
public class GetRequestGroup { /** * Tuple3 : ( keys , fields , contains - batch - get ) */
private static Tuple3 < Set < Object > , Set < PathSpec > , Boolean > reduceRequests ( final Tuple3 < Set < Object > , Set < PathSpec > , Boolean > state , final Request < ? > rq ) { } }

implementation: return reduceContainsBatch ( reduceIds ( reduceFields ( state , rq ) , rq ) , rq ) ;


signature:
public class GetRequestGroup { /** * Tuple3 : ( keys , fields , contains - batch - get ) */
private static Tuple3 < Set < Object > , Set < PathSpec > , Boolean > reduceContainsBatch ( Tuple3 < Set < Object > , Set < PathSpec > , Boolean > state , Request < ? > request ) { } }

implementation: if ( request instanceof GetRequest ) { return state ; } else if ( request instanceof BatchRequest ) { return Tuples . tuple ( state . _1 ( ) , state . _2 ( ) , true ) ; } else { throw unsupportedGetRequestType ( request ) ; }


signature:
public class GetRequestGroup { /** * Tuple3 : ( keys , fields , contains - batch - get ) */
private static Tuple3 < Set < Object > , Set < PathSpec > , Boolean > reduceIds ( Tuple3 < Set < Object > , Set < PathSpec > , Boolean > state , Request < ? > request ) { } }

implementation: if ( request instanceof GetRequest ) { GetRequest < ? > getRequest = ( GetRequest < ? > ) request ; state . _1 ( ) . add ( getRequest . getObjectId ( ) ) ; return state ; } else if ( request instanceof BatchRequest ) { BatchRequest < ? > batchRequest = ( BatchRequest < ? > ) request ; state . _1 ( ) . addAll ( batchRequest . getObjectIds ( ) ) ; return state ; } else { throw unsupportedGetRequestType ( request ) ; }


signature:
public class GetRequestGroup { /** * Tuple3 : ( keys , fields , contains - batch - get ) */
private static Tuple3 < Set < Object > , Set < PathSpec > , Boolean > reduceFields ( Tuple3 < Set < Object > , Set < PathSpec > , Boolean > state , Request < ? > request ) { } }

implementation: if ( request instanceof GetRequest || request instanceof BatchRequest ) { final Set < PathSpec > requestFields = request . getFields ( ) ; if ( requestFields != null && ! requestFields . isEmpty ( ) ) { if ( state . _2 ( ) != null ) { state . _2 ( ) . addAll ( requestFields ) ; } return state ; } else { return Tuples . tuple ( state . _1 ( ) , null , state . _3 ( ) ) ; } } else { throw unsupportedGetRequestType ( request ) ; }


signature:
public class GetRequestGroup { /** * Tuple3 : ( keys , fields , contains - batch - get ) */
private Tuple3 < Set < Object > , Set < PathSpec > , Boolean > reduceRequests ( final Batch < RestRequestBatchKey , Response < Object > > batch ) { } }

implementation: return batch . entries ( ) . stream ( ) . map ( Entry :: getKey ) . map ( RestRequestBatchKey :: getRequest ) . reduce ( Tuples . tuple ( new HashSet < > ( ) , new HashSet < > ( ) , false ) , GetRequestGroup :: reduceRequests , GetRequestGroup :: combine ) ;


signature:
public class ZKClientImpl { /** * { @ inheritDoc } */
@ Override public Promise < Void > start ( ) { } }

implementation: AtomicBoolean committed = new AtomicBoolean ( false ) ; SettablePromise < Void > promise = Promises . settable ( ) ; _listener . subscribe ( KeeperState . SyncConnected , ( Promise p ) -> { if ( committed . compareAndSet ( false , true ) ) { if ( p . isFailed ( ) ) { promise . fail ( p . getError ( ) ) ; } else { promise . done ( null ) ; } } } ) ; try { _zkClient = new ZooKeeper ( _connectionString , _sessionTimeout , _defaultWatcher ) ; _reaper = new Reaper ( _engine ) ; } catch ( IOException ex ) { if ( committed . compareAndSet ( false , true ) ) { promise . fail ( ex ) ; } } return promise ;


signature:
public class ZKClientImpl { /** * { @ inheritDoc } */
@ Override public Task < String > create ( String path , byte [ ] data , List < ACL > acl , CreateMode createMode ) { } }

implementation: return Task . async ( "zkCreate: " + path , ( ) -> { SettablePromise < String > promise = Promises . settable ( ) ; _zkClient . create ( path , data , acl , createMode , ( int rc , String p , Object ctx , String name ) -> { KeeperException . Code code = KeeperException . Code . get ( rc ) ; switch ( code ) { case OK : promise . done ( name ) ; break ; default : promise . fail ( KeeperException . create ( code , p ) ) ; } } , null ) ; return promise ; } ) ;


signature:
public class ZKClientImpl { /** * { @ inheritDoc } */
@ Override public WatchableTask < ZKData > getData ( String path ) { } }

implementation: return new WatchableTask < ZKData > ( "zkGetData: " + path ) { @ Override protected Promise < ? extends ZKData > run ( Context context ) throws Throwable { SettablePromise < ZKData > promise = Promises . settable ( ) ; _zkClient . getData ( path , _watcher , ( int rc , String p , Object ctx , byte [ ] data , Stat stat ) -> { KeeperException . Code code = KeeperException . Code . get ( rc ) ; switch ( code ) { case OK : _zkClient . getACL ( path , stat , ( int rc1 , String p1 , Object ctx1 , List < ACL > acls , Stat stat1 ) -> { KeeperException . Code code1 = KeeperException . Code . get ( rc1 ) ; switch ( code1 ) { case OK : promise . done ( new ZKData ( p , data , stat , acls ) ) ; break ; default : promise . fail ( KeeperException . create ( code1 , p1 ) ) ; } } , null ) ; break ; default : promise . fail ( KeeperException . create ( code , p ) ) ; } } , null ) ; return promise ; } } ;


signature:
public class ZKClientImpl { /** * { @ inheritDoc } */
@ Override public WatchableTask < List < String > > getChildren ( String path ) { } }

implementation: return new WatchableTask < List < String > > ( "zkGetChildren: " + path ) { @ Override protected Promise run ( Context context ) throws Throwable { SettablePromise < List < String > > promise = Promises . settable ( ) ; _zkClient . getChildren ( path , _watcher , ( int rc , String p , Object ctx , List < String > children ) -> { KeeperException . Code code = KeeperException . Code . get ( rc ) ; switch ( code ) { case OK : promise . done ( children ) ; break ; default : promise . fail ( KeeperException . create ( code , p ) ) ; } } , null ) ; return promise ; } } ;


signature:
public class ZKClientImpl { /** * { @ inheritDoc } */
@ Override public WatchableTask < Optional < Stat > > exists ( String path ) { } }

implementation: return new WatchableTask < Optional < Stat > > ( "zkExists: " + path ) { @ Override protected Promise run ( Context context ) throws Throwable { SettablePromise < Optional < Stat > > promise = Promises . settable ( ) ; _zkClient . exists ( path , _watcher , ( int rc , String p , Object ctx , Stat stat ) -> { KeeperException . Code code = KeeperException . Code . get ( rc ) ; switch ( code ) { case OK : promise . done ( Optional . of ( stat ) ) ; break ; case NONODE : promise . done ( Optional . empty ( ) ) ; break ; default : promise . fail ( KeeperException . create ( code , p ) ) ; } } , null ) ; return promise ; } } ;


signature:
public class ZKClientImpl { /** * { @ inheritDoc } */
@ Override public Task < Void > delete ( String path , int version ) { } }

implementation: return Task . async ( "zkDelete: " + path , ( ) -> { SettablePromise < Void > promise = Promises . settable ( ) ; _zkClient . delete ( path , version , ( int rc , String p , Object ctx ) -> { KeeperException . Code code = KeeperException . Code . get ( rc ) ; switch ( code ) { case OK : promise . done ( null ) ; break ; default : promise . fail ( KeeperException . create ( code , p ) ) ; } } , null ) ; return promise ; } ) ;


signature:
public class ZKClientImpl { /** * { @ inheritDoc } */
@ Override public Task < List < OpResult > > multi ( List < Op > ops , Executor executor ) { } }

implementation: return Task . blocking ( ( ) -> _zkClient . multi ( ops ) , executor ) ;


signature:
public class ZKClientImpl { /** * Returns task that will wait for the given { @ link KeeperState } to fulfill .
 * The task will be failed if the underlying zookeeper session expires .
 * @ param state keeper state to wait for .
 * @ return task that waits for a certain keeper state . */
public Task < Void > waitFor ( KeeperState state ) { } }

implementation: return Task . async ( "waitFor " + state . toString ( ) , ( ) -> { SettablePromise < Void > promise = Promises . settable ( ) ; synchronized ( _mutex ) { if ( _currentState == state ) { return Promises . VOID ; } else { _listener . subscribe ( state , ( p ) -> { if ( p . isFailed ( ) ) { promise . fail ( p . getError ( ) ) ; } else { promise . done ( null ) ; } } ) ; } } return promise ; } ) ;


signature:
public class ZKClientImpl { /** * { @ inheritDoc } */
@ Override public Task < Void > waitFor ( KeeperState state , long deadline ) { } }

implementation: return waitFor ( state ) . withTimeout ( deadline - System . currentTimeMillis ( ) , TimeUnit . MILLISECONDS ) ;


signature:
public class ZKClientImpl { /** * { @ inheritDoc } */
@ Override public Task < String > ensurePathExists ( String path ) { } }

implementation:
return exists ( path ) . flatMap ( stat -> { if ( ! stat . isPresent ( ) ) { Task < String > createIfAbsent = create ( path , null , ZooDefs . Ids . OPEN_ACL_UNSAFE , CreateMode . PERSISTENT ) . recoverWith ( "recover from NodeExistsException" , e -> { if ( e instanceof KeeperException . NodeExistsException ) { return Task . value ( path ) ; } else { return Task . failure ( e ) ; } } ) ; String parent = path . substring ( 0 , path . lastIndexOf ( '/' ) ) ; if ( parent . isEmpty ( ) ) { // parent is root
return createIfAbsent ; } else { return ensurePathExists ( parent ) . flatMap ( unused -> createIfAbsent ) ; } } else { return Task . value ( path ) ; } } ) ;


signature:
public class ZKClientImpl { /** * { @ inheritDoc } */
@ Override public void deleteNodeHasUUID ( String path , String uuid ) { } }

implementation: _reaper . submit ( ( ) -> getChildren ( path ) . map ( children -> ZKUtil . findNodeWithUUID ( children , uuid ) ) . flatMap ( node -> { if ( node != null ) { return delete ( node , - 1 ) ; } else { return Task . value ( null ) ; } } ) ) ;


signature:
public class Trace { /** * Need to fix in the next major version release . */
public static Trace single ( ShallowTrace shallowTrace ) { } }

implementation: return single ( shallowTrace , TraceBuilder . UNKNOWN_PLAN_CLASS , TraceBuilder . UNKNOWN_PLAN_ID ) ;


signature:
public class RequestConfigTree { /** * This method recursively uses given resolver to resolve a config by given name taking into account
 * syntax of sub - resource names . For example , for given name : Optional . of ( " foo : bar : baz " ) it will make
 * the following resolver calls :
 * - resolver ( Optional . of ( " foo : bar : baz " ) )
 * - resolver ( Optional . of ( " foo : bar " ) )
 * - resolver ( Optional . of ( " foo " ) )
 * - resolver ( Optional . empty ( ) ) */
Optional < ConfigValue < T > > resolveNameRecursively ( Optional < String > name , Function < Optional < String > , Optional < ConfigValue < T > > > resolver ) { } }

implementation: Optional < ConfigValue < T > > value = resolver . apply ( name ) ; if ( value . isPresent ( ) ) { return value ; } else { if ( name . isPresent ( ) ) { return resolveNameRecursively ( name . filter ( s -> s . lastIndexOf ( ':' ) > 0 ) . map ( s -> s . substring ( 0 , s . lastIndexOf ( ':' ) ) ) , resolver ) ; } else { return Optional . empty ( ) ; } }


signature:
public class LockUtil { /** * Returns lock data in a form of " hostname : threadName " */
public static byte [ ] getLockData ( ) { } }

implementation: String str = String . format ( "%s:%s" , HOST_NAME , Thread . currentThread ( ) . getName ( ) ) ; return str . getBytes ( UTF8 ) ;


signature:
public class BatchingStrategy { /** * This method returns Task that returns value for a single key allowing this strategy to batch operations .
 * @ param desc description of the task
 * @ param key key
 * @ return Task that returns value for a single key allowing this strategy to batch operations */
public Task < T > batchable ( final String desc , final K key ) { } }

implementation:
Task < T > batchableTask = Task . async ( desc , ctx -> { final BatchPromise < T > result = new BatchPromise < > ( ) ; final Long planId = ctx . getPlanId ( ) ; final GroupBatchBuilder builder = _batches . computeIfAbsent ( planId , k -> new GroupBatchBuilder ( ) ) ; final G group = classify ( key ) ; Batch < K , T > fullBatch = builder . add ( group , key , ctx . getShallowTraceBuilder ( ) , result ) ; if ( fullBatch != null ) { try { ctx . run ( taskForBatch ( group , fullBatch , true ) ) ; } catch ( Throwable t ) { // we don ' t care if some of promises have already been completed
// all we care is that all remaining promises have been failed
fullBatch . failAll ( t ) ; } } return result ; } ) ; batchableTask . getShallowTraceBuilder ( ) . setTaskType ( "batched" ) ; return batchableTask ;


signature:
public class BatchingStrategy { /** * Overriding this method allows providing custom name for a batch . Name will appear in the
 * ParSeq trace as a description of the task that executes the batch .
 * @ param batch batch to be described
 * @ param group group to be described
 * @ return name for the batch and group */
public String getBatchName ( G group , Batch < K , T > batch ) { } }

implementation: return "batch(keys: " + batch . keySize ( ) + ", size: " + batch . batchSize ( ) + ")" ;


signature:
public class BatchAggregationTimeMetric { /** * Allows consuming histogram and returning a result .
 * Histogram passed to the consumer includes stable , consistent view
 * of all values accumulated since last harvest .
 * This method is thread safe .
 * @ param consumer consumer for a harvested histogram
 * @ param < T > return type of a passed in function
 * @ return a result of a passed in function */
public synchronized < T > T harvest ( Function < Histogram , T > consumer ) { } }

implementation: initializeRecorder ( ) ; _recycle = _recorder . getIntervalHistogram ( _recycle ) ; return consumer . apply ( _recycle ) ;


signature:
public class Tuple6TaskDelegate { /** * { @ inheritDoc } */
@ Override public Tuple6 < T1 , T2 , T3 , T4 , T5 , T6 > get ( ) throws PromiseException { } }

implementation: return _task . get ( ) ;


signature:
public class Tuple6TaskDelegate { /** * { @ inheritDoc } */
@ Override public Tuple6 < T1 , T2 , T3 , T4 , T5 , T6 > getOrDefault ( Tuple6 < T1 , T2 , T3 , T4 , T5 , T6 > defaultValue ) throws PromiseUnresolvedException { } }

implementation: return _task . getOrDefault ( defaultValue ) ;


signature:
public class Tuple6TaskDelegate { /** * { @ inheritDoc } */
@ Override public void addListener ( PromiseListener < Tuple6 < T1 , T2 , T3 , T4 , T5 , T6 > > listener ) { } }

implementation: _task . addListener ( listener ) ;


signature:
public class Tuple13TaskDelegate { /** * { @ inheritDoc } */
@ Override public Tuple13 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 > get ( ) throws PromiseException { } }


signature:
public class Tuple13TaskDelegate { /** * { @ inheritDoc } */
@ Override public void addListener ( PromiseListener < Tuple13 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 > > listener ) { } }


signature:
public class RequestConfigProviderImpl { /** * Default configuration map must specify default values for all properties . */
private static ParSeqRestliClientConfig createDefaultConfig ( ) { } }

implementation: ParSeqRestliClientConfigBuilder builder = new ParSeqRestliClientConfigBuilder ( ) ; builder . addTimeoutMs ( "*.*/*.*" , DEFAULT_TIMEOUT ) ; builder . addBatchingEnabled ( "*.*/*.*" , DEFAULT_BATCHING_ENABLED ) ; builder . addMaxBatchSize ( "*.*/*.*" , DEFAULT_MAX_BATCH_SIZE ) ; return builder . build ( ) ;


signature:
public class SelectedBackoff { /** * { @ inheritDoc } */
@ Override public long nextBackoff ( int attempts , Throwable error ) { } }

implementation: return _policyFunction . apply ( error ) . nextBackoff ( attempts , error ) ;


signature:
public class InternalUtil { /** * Invokes the { @ code listener } once all given { @ code promises } have been resolved .
 * @ param listener the listener to invoke when the promises have finished .
 * @ param promises the set of promises that must be resolved
 * @ see com . linkedin . parseq . promise . PromiseListener */
public static void after ( final PromiseListener < ? > listener , final Promise < ? > ... promises ) { } }

implementation: final SettablePromise < Object > afterPromise = Promises . settable ( ) ; final PromiseListener < Object > countDownListener = new CountDownPromiseListener < Object > ( promises . length , afterPromise , null ) ; for ( Promise < ? > promise : promises ) { unwildcardPromise ( promise ) . addListener ( countDownListener ) ; } afterPromise . addListener ( unwildcardListener ( listener ) ) ;


signature:
public class Tuple5TaskDelegate { /** * { @ inheritDoc } */
@ Override public Tuple5 < T1 , T2 , T3 , T4 , T5 > get ( ) throws PromiseException { } }


signature:
public class Tuple5TaskDelegate { /** * { @ inheritDoc } */
@ Override public Tuple5 < T1 , T2 , T3 , T4 , T5 > getOrDefault ( Tuple5 < T1 , T2 , T3 , T4 , T5 > defaultValue ) throws PromiseUnresolvedException { } }


signature:
public class Tuple5TaskDelegate { /** * { @ inheritDoc } */
@ Override public void addListener ( PromiseListener < Tuple5 < T1 , T2 , T3 , T4 , T5 > > listener ) { } }


signature:
public class Tuple3TaskDelegate { /** * { @ inheritDoc } */
@ Override public Tuple3 < T1 , T2 , T3 > getOrDefault ( Tuple3 < T1 , T2 , T3 > defaultValue ) throws PromiseUnresolvedException { } }


signature:
public class Tuple3TaskDelegate { /** * { @ inheritDoc } */
@ Override public void addListener ( PromiseListener < Tuple3 < T1 , T2 , T3 > > listener ) { } }


signature:
public class SourcePointer { /** * / * package private */
static Optional < SourcePointer > get ( ) { } }

implementation:
// create an exception , discard known elements from stack trace and find first element with suspect
return Arrays . stream ( new Exception ( ) . getStackTrace ( ) ) . filter ( SourcePointer :: notLambdaStuff ) . findFirst ( ) . map ( SourcePointer :: sourcePointer ) ;


signature:
public class FusionTask { /** * Drops FusionTraceContext on the floor . This method adapts pure transformation to be used within FusionTask
 * that needs additional information ( FusionTraceContext ) to build trace . */
private static < A , B > Consumer3 < FusionTraceContext , Promise < A > , Settable < B > > adaptToAcceptTraceContext ( final PromisePropagator < A , B > propagator ) { } }

implementation: return ( traceContext , src , dest ) -> propagator . accept ( src , dest ) ;


signature:
public class FusionTask { /** * Composes transformation with the transformation of the predecessor . */
private < R > Consumer3 < FusionTraceContext , Promise < S > , Settable < T > > compose ( final Consumer3 < FusionTraceContext , Promise < S > , Settable < R > > predecessor , final Consumer3 < FusionTraceContext , Promise < R > , Settable < T > > propagator ) { } }

implementation:
return ( traceContext , src , dst ) -> { /* * At this point we know that transformation chain ' s length > 1.
 * This code is executed during task execution , not when task is constructed . */
traceContext . createSurrogate ( ) ; predecessor . accept ( traceContext , src , new Settable < R > ( ) { @ Override public void done ( R value ) throws PromiseResolvedException { try { /* Track start time of the transformation . End time is tracked by closure created by completing ( ) */
getEffectiveShallowTraceBuilder ( traceContext ) . setStartNanos ( System . nanoTime ( ) ) ; propagator . accept ( traceContext , Promises . value ( value ) , dst ) ; } catch ( Exception e ) { /* This can only happen if there is an internal problem . Propagators should not throw any exceptions . */
LOGGER . error ( "ParSeq ingternal error. An exception was thrown by propagator" , e ) ; } } @ Override public void fail ( Throwable error ) throws PromiseResolvedException { try { /* Track start time of the transformation . End time is tracked by closure created by completing ( ) */
getEffectiveShallowTraceBuilder ( traceContext ) . setStartNanos ( System . nanoTime ( ) ) ; propagator . accept ( traceContext , Promises . error ( error ) , dst ) ; } catch ( Exception e ) { /* This can only happen if there is an internal problem . Propagators should not throw any exceptions . */
LOGGER . error ( "ParSeq ingternal error. An exception was thrown by propagator." , e ) ; } } } ) ; } ;


signature:
public class FusionTask { /** * Adds closure to the propagator that maintains correct state of the task e . g . transitions between states ,
 * adds trace etc . */
private Consumer3 < FusionTraceContext , Promise < S > , Settable < T > > completing ( final Consumer3 < FusionTraceContext , Promise < S > , Settable < T > > propagator ) { } }

implementation:
return ( traceContext , src , dest ) -> { final SettablePromise < T > settable = FusionTask . this . getSettableDelegate ( ) ; if ( isPropagationInitiator ( traceContext ) ) { /* BaseTask ' s code handles completing the parent task
 * we need to handle tracing of a surrogate task here */
propagator . accept ( traceContext , src , new Settable < T > ( ) { @ Override public void done ( T value ) throws PromiseResolvedException { final ShallowTraceBuilder shallowTraceBuilder = traceContext . getSurrogate ( ) ; if ( shallowTraceBuilder != null ) { addRelationships ( traceContext ) ; final long endNanos = System . nanoTime ( ) ; shallowTraceBuilder . setPendingNanos ( endNanos ) ; shallowTraceBuilder . setEndNanos ( endNanos ) ; final Function < T , String > traceValueProvider = _traceValueProvider ; shallowTraceBuilder . setResultType ( ResultType . SUCCESS ) ; if ( traceValueProvider != null ) { try { shallowTraceBuilder . setValue ( traceValueProvider . apply ( value ) ) ; } catch ( Exception e ) { shallowTraceBuilder . setValue ( Exceptions . failureToString ( e ) ) ; } } } dest . done ( value ) ; } @ Override public void fail ( Throwable error ) throws PromiseResolvedException { final ShallowTraceBuilder shallowTraceBuilder = traceContext . getSurrogate ( ) ; if ( shallowTraceBuilder != null ) { addRelationships ( traceContext ) ; final long endNanos = System . nanoTime ( ) ; shallowTraceBuilder . setPendingNanos ( endNanos ) ; shallowTraceBuilder . setEndNanos ( endNanos ) ; if ( Exceptions . isEarlyFinish ( error ) ) { shallowTraceBuilder . setResultType ( ResultType . EARLY_FINISH ) ; } else { shallowTraceBuilder . setResultType ( ResultType . ERROR ) ; shallowTraceBuilder . setValue ( Exceptions . failureToString ( error ) ) ; } } dest . fail ( error ) ; } } ) ; } else if ( transitionRun ( traceContext . getParent ( ) . getTraceBuilder ( ) ) ) { markTaskStarted ( ) ; // non - parent task executed for the first time
traceContext . getParent ( ) . getTaskLogger ( ) . logTaskStart ( this ) ; Settable < T > next = new Settable < T > ( ) { @ Override public void done ( final T value ) throws PromiseResolvedException { try { transitionDone ( traceContext ) ; final Function < T , String > traceValueProvider = _traceValueProvider ; _shallowTraceBuilder . setResultType ( ResultType . SUCCESS ) ; if ( traceValueProvider != null ) { try { _shallowTraceBuilder . setValue ( traceValueProvider . apply ( value ) ) ; } catch ( Exception e ) { _shallowTraceBuilder . setValue ( Exceptions . failureToString ( e ) ) ; } } settable . done ( value ) ; traceContext . getParent ( ) . getTaskLogger ( ) . logTaskEnd ( FusionTask . this , _traceValueProvider ) ; CONTINUATIONS . submit ( ( ) -> dest . done ( value ) ) ; } catch ( Exception e ) { CONTINUATIONS . submit ( ( ) -> dest . fail ( e ) ) ; } } @ Override public void fail ( final Throwable error ) throws PromiseResolvedException { try { transitionDone ( traceContext ) ; traceFailure ( error ) ; settable . fail ( error ) ; traceContext . getParent ( ) . getTaskLogger ( ) . logTaskEnd ( FusionTask . this , _traceValueProvider ) ; CONTINUATIONS . submit ( ( ) -> dest . fail ( error ) ) ; } catch ( Exception e ) { CONTINUATIONS . submit ( ( ) -> dest . fail ( e ) ) ; } } } ; CONTINUATIONS . submit ( ( ) -> { try { propagator . accept ( traceContext , src , next ) ; } catch ( Exception e ) { /* This can only happen if there is an internal problem . Propagators should not throw any exceptions . */
LOGGER . error ( "ParSeq ingternal error. An exception was thrown by propagator." , e ) ; } } ) ; } else { // non - parent tasks subsequent executions
addPotentialRelationships ( traceContext , traceContext . getParent ( ) . getTraceBuilder ( ) ) ; Promises . propagateResult ( settable , dest ) ; } } ;


signature:
public class FusionTask { /** * Create new FusionTask with an async predecessor . */
public static < S , T > FusionTask < ? , T > create ( final String name , final Task < S > task , final PromisePropagator < S , T > propagator ) { } }

implementation: return new FusionTask < S , T > ( name , task , propagator ) ;


signature:
public class Util { /** * / * package private */
static String extractSimpleName ( String fqcn , String separator ) { } }

implementation: if ( fqcn . contains ( separator ) ) { return fqcn . substring ( fqcn . lastIndexOf ( separator ) + 1 , fqcn . length ( ) ) ; } else { return fqcn ; }


signature:
public class Util { /** * / * package private */
static String getArgumentsInformation ( String insnDesc ) { } }

implementation: if ( insnDesc == null ) { return "" ; } Type methodType = Type . getMethodType ( insnDesc ) ; int argSize = methodType . getArgumentTypes ( ) . length ; StringJoiner sj = new StringJoiner ( "," , "(" , ")" ) ; for ( int i = 0 ; i < argSize ; i ++ ) { sj . add ( "_" ) ; } return sj . toString ( ) ;


signature:
public class Util { /** * / * package private */
static String getDescriptionForMethodInsnNode ( MethodInsnNode methodInstr ) { } }

implementation: if ( methodInstr . getOpcode ( ) == Opcodes . INVOKESPECIAL && methodInstr . name . equals ( "<init>" ) ) { return "new " + Util . extractSimpleName ( methodInstr . owner , "/" ) + "()" ; } else { Type methodType = Type . getMethodType ( methodInstr . desc ) ; int retSize = methodType . getArgumentsAndReturnSizes ( ) & 0x03 ; if ( retSize > 0 ) { return methodInstr . name + Util . getArgumentsInformation ( methodInstr . desc ) ; } } return "" ;


signature:
public class Util { /** * / * package private */
static String getDescriptionForTypeInsnNode ( TypeInsnNode typeInsnNode ) { } }

implementation:
AbstractInsnNode nextInsn = typeInsnNode . getNext ( ) ; StringJoiner argsDesc = new StringJoiner ( "," , "(" , ")" ) ; while ( nextInsn != null ) { if ( nextInsn instanceof LdcInsnNode ) { argsDesc . add ( "_" ) ; } else if ( nextInsn . getOpcode ( ) == Opcodes . DUP ) { // ignore
} else { break ; } nextInsn = nextInsn . getNext ( ) ; } if ( typeInsnNode . getOpcode ( ) == Opcodes . NEW ) { return "new " + Util . extractSimpleName ( typeInsnNode . desc , "/" ) + argsDesc . toString ( ) ; } return "" ;


signature:
public class EngineBuilder { /** * Sets the timer scheduler for the engine .
 * The lifecycle of the scheduler is not managed by the engine .
 * @ param timerScheduler the scheduler to use for the engine
 * @ return this builder */
public EngineBuilder setTimerScheduler ( final ScheduledExecutorService timerScheduler ) { } }

implementation: ArgumentUtil . requireNotNull ( timerScheduler , "timerScheduler" ) ; setTimerScheduler ( adaptTimerScheduler ( timerScheduler ) ) ; return this ;


signature:
public class EngineBuilder { /** * Sets an engine related property on the engine .
 * That property can then be accessed by tasks via the Context .
 * @ param key
 * @ param value
 * @ return this builder */
public EngineBuilder setEngineProperty ( String key , Object value ) { } }

implementation: _properties . put ( key , value ) ; return this ;


signature:
public class EngineBuilder { /** * Checks that the require configuration has been set and then constructs
 * and returns a new { @ link Engine } .
 * @ return a new { @ link Engine } using the configuration in this builder .
 * @ throws IllegalStateException if the configuration in this builder is invalid . */
public Engine build ( ) { } }

implementation: if ( _taskExecutor == null ) { throw new IllegalStateException ( "Task executor is required to create an Engine, but it is not set" ) ; } if ( _timerScheduler == null ) { throw new IllegalStateException ( "Timer scheduler is required to create an Engine, but it is not set" ) ; } return new Engine ( _taskExecutor , new IndirectDelayedExecutor ( _timerScheduler ) , _loggerFactory != null ? _loggerFactory : new CachedLoggerFactory ( LoggerFactory . getILoggerFactory ( ) ) , _properties , _planDeactivationListener != null ? _planDeactivationListener : planContext -> { } , _planCompletionListener != null ? _planCompletionListener : planContext -> { } , _taskQueueFactory , _planClassRateLimiter ) ;


signature:
public class Promises { /** * Creates a new promise that is already resolved with the given value .
 * @ param value the value for the new promise
 * @ param < T > the type of the value for the promise
 * @ return the promise */
@ SuppressWarnings ( "unchecked" ) public static < T > Promise < T > value ( final T value ) { } }

implementation: if ( value == null ) { if ( VOID == null ) { return new ResolvedValue < T > ( value ) ; } else { return ( Promise < T > ) VOID ; } } return new ResolvedValue < T > ( value ) ;


signature:
public class Promises { /** * Copies the value or error from the source promise to the destination
 * promise .
 * @ param source the source promise
 * @ param dest the destination promise
 * @ param < T > the value type for both promises */
public static < T > void propagateResult ( final Promise < T > source , final Settable < T > dest ) { } }

implementation: source . addListener ( new TransformingPromiseListener < T , T > ( dest , PromiseTransformer . identity ( ) ) ) ;


signature:
public class Promises { /** * Returns instance of { @ link Try } that represents result a promise has completed with .
 * This method throws { @ link PromiseUnresolvedException } if teh promise has not been resolved yet .
 * @ return instance of { @ link Try } that represents result the promise has completed with
 * @ see Try */
public static < T > Try < T > toTry ( final Promise < T > promise ) { } }

implementation: if ( promise . isFailed ( ) ) { return Failure . of ( promise . getError ( ) ) ; } else { return Success . of ( promise . get ( ) ) ; }


signature:
public class Examples { /** * handles failures delivering degraded experience */
Task < String > createResilientSummary ( int id ) { } }

implementation: return fetchPerson ( id ) . map ( this :: shortSummary ) . recover ( e -> "Member " + id ) ;


signature:
public class Examples { /** * handles failures delivering degraded experience in timely fashion */
Task < String > createResponsiveSummary ( int id ) { } }

implementation: return fetchPerson ( id ) . withTimeout ( 100 , TimeUnit . MILLISECONDS ) . map ( this :: shortSummary ) . recover ( e -> "Member " + id ) ;


signature:
public class Examples { /** * create mailbox summary for a person : " < first name > < last name > has < X > messages " */
Task < String > createMailboxSummary ( int id ) { } }

implementation: return Task . par ( createExtendedSummary ( id ) , fetchMailbox ( id ) ) . map ( "createMailboxSummary" , ( summary , mailbox ) -> summary + " has " + mailbox . size ( ) + " messages" ) ;


signature:
public class Examples { /** * create list of summaries , one per each connection */
Task < List < String > > createConnectionsSummaries ( int id ) { } }

implementation: return fetchPerson ( id ) . flatMap ( "createConnectionsSummaries" , person -> createConnectionsSummaries ( person . getConnections ( ) ) ) ;


signature: public class Examples { Task < Tuple2 < String , List < String > > > createFullSummary ( int id ) { } }

implementation: return Task . par ( createMailboxSummary ( id ) , createConnectionsSummaries ( id ) ) ;


signature: public class Examples { @ Override protected void doRunExample ( final Engine engine ) throws Exception { } }

implementation:
Task < ? > task = createExtendedSummary ( 1 ) ; // Task < ? > task = Task . par ( createExtendedSummary ( 1 ) , createExtendedSummary ( 2 ) ) ;
engine . run ( task ) ; runTaskAndPrintResults ( engine , task ) ;


signature:
public class Tuple4TaskDelegate { /** * { @ inheritDoc } */
@ Override public Tuple4 < T1 , T2 , T3 , T4 > get ( ) throws PromiseException { } }

implementation: return _task . get ( ) ;


signature:
public class Tuple4TaskDelegate { /** * { @ inheritDoc } */
@ Override public Tuple4 < T1 , T2 , T3 , T4 > getOrDefault ( Tuple4 < T1 , T2 , T3 , T4 > defaultValue ) throws PromiseUnresolvedException { } }

implementation: return _task . getOrDefault ( defaultValue ) ;


signature:
public class Tuple4TaskDelegate { /** * { @ inheritDoc } */
@ Override public void addListener ( PromiseListener < Tuple4 < T1 , T2 , T3 , T4 > > listener ) { } }

implementation: _task . addListener ( listener ) ;


signature:
public class ASMBasedTaskDescriptor { /** * / * package private */
Optional < String > getLambdaClassDescription ( String className ) { } }

implementation: int slashIndex = className . lastIndexOf ( '/' ) ; if ( slashIndex > 0 ) { String name = className . substring ( 0 , slashIndex ) ; String desc = _names . get ( name ) ; if ( desc == null || desc . isEmpty ( ) ) { return Optional . empty ( ) ; } else { return Optional . of ( desc ) ; } } return Optional . empty ( ) ;


signature:
public class Tuple2TaskDelegate { /** * { @ inheritDoc } */
@ Override public Tuple2 < T1 , T2 > getOrDefault ( Tuple2 < T1 , T2 > defaultValue ) throws PromiseUnresolvedException { } }


signature:
public class Tuple2TaskDelegate { /** * { @ inheritDoc } */
@ Override public void addListener ( PromiseListener < Tuple2 < T1 , T2 > > listener ) { } }


signature:
public class Tasks { /** * Creates a new { @ link Task } that have a value of type Void . Because the
 * returned task has no value , it is typically used to produce side - effects .
 * @ deprecated As of 2.0.0 , replaced by { @ link Task # action ( String , com . linkedin . parseq . function . Action ) Task . action }
 * @ param name a name that describes the action
 * @ param runnable the action that will be executed when the task is run
 * @ return the new task
 * @ see Task # action ( String , com . linkedin . parseq . function . Action ) Task . action */
@ Deprecated public static Task < Void > action ( final String name , final Runnable runnable ) { } }

implementation: return Task . action ( name , runnable :: run ) ;


signature:
public class Tasks { /** * Creates a new { @ link Task } that ' s value will be set to the value returned
 * from the supplied callable . This task is useful when doing basic
 * computation that does not require asynchrony . It is not appropriate for
 * long running or blocking tasks .
 * @ deprecated As of 2.0.0 , replaced by { @ link Task # callable ( String , Callable ) Task . callable }
 * @ param name a name that describes the action
 * @ param callable the callable to execute when this task is run
 * @ param < T > the type of the return value for this task
 * @ return the new task
 * @ see Task # callable ( String , Callable ) Task . callable */
@ Deprecated public static < T > Task < T > callable ( final String name , final Callable < ? extends T > callable ) { } }

implementation: return Task . callable ( name , ( ) -> callable . call ( ) ) ;


signature:
public class Tasks { /** * Creates a new { @ link Task } that ' s value will be set to the value returned
 * from the supplied callable . This task is useful when doing basic
 * computation that does not require asynchrony . It is not appropriate for
 * long running or blocking tasks .
 * @ deprecated As of 2.0.0 , replaced by { @ link Task # callable ( String , Callable ) Task . callable }
 * @ param name a name that describes the action
 * @ param callable the callable to execute when this task is run
 * @ param < T > the type of the return value for this task
 * @ return the new task
 * @ see Task # callable ( String , Callable ) Task . callable */
@ Deprecated public static < T > Task < T > callable ( final String name , final ThrowableCallable < ? extends T > callable ) { } }

implementation: return new CallableTask < T > ( name , callable ) ;


signature:
public class Tasks { /** * Creates a new task that will run the given tasks sequentially ( e . g .
 * task1 will be finished before task2 starts ) . The value of the seq task will
 * be the result of the last task in the sequence .
 * @ deprecated As of 2.0.0 , replaced by { @ link Task # map ( String , com . linkedin . parseq . function . Function1 ) Task . map } ,
 * { @ link Task # flatMap ( String , com . linkedin . parseq . function . Function1 ) Task . flatMap } ,
 * { @ link Task # andThen ( String , Task ) Task . andThen } and other methods in { @ link Task } .
 * @ see Task # map ( String , com . linkedin . parseq . function . Function1 ) Task . map
 * @ see Task # flatMap ( String , com . linkedin . parseq . function . Function1 ) Task . flatMap
 * @ see Task # andThen ( String , Task ) Task . andThen
 * @ see Task */
@ Deprecated public static < T > Task < T > seq ( Task < ? > task1 , Task < T > task2 ) { } }

implementation: return vaseq ( task1 , task2 ) ;


signature:
public class Tasks { /** * Creates a new task that , when run , will run each of the supplied tasks in
 * order . The value of this new task is the value of the last task in the
 * sequence . < strong > This method is not type - safe < / strong > .
 * @ param tasks the tasks to run sequentially
 * @ param < T > the result value for the sequence of tasks
 * @ return a new task that will run the given tasks sequentially */
@ SuppressWarnings ( "deprecation" ) public static < T > Task < T > seq ( final Iterable < ? extends Task < ? > > tasks ) { } }

implementation: return new SeqTask < T > ( "seq" , tasks ) ;


signature:
public class Tasks { /** * Creates a task that will run another task as a side effect once the primary task
 * completes successfully . The side effect will not be run if the primary task fails or
 * is canceled . The entire task is marked done once the base task completes , even if
 * the side effect has not been run .
 * @ param parent the primary task .
 * @ param sideEffect the side effect of the primary task .
 * @ param < T > the result value of the parent task , and the resulting task .
 * @ return a new task that will be done once parent completes , but has the given side effect .
 * @ deprecated As of 2.0.0 , replaced by { @ link Task # withSideEffect ( String , com . linkedin . parseq . function . Function1 ) Task . withSideEffect }
 * @ see Task # withSideEffect ( String , com . linkedin . parseq . function . Function1 ) Task . withSideEffect */
@ Deprecated public static < T > Task < T > withSideEffect ( final Task < T > parent , final Task < ? > sideEffect ) { } }

implementation: return parent . withSideEffect ( t -> sideEffect ) ;


signature:
public class Tasks { /** * Creates a new task that wraps the given task . If the given task finishes
 * before the timeout occurs then this task takes on the value of the task .
 * If the task does not complete in the given time then this task will
 * have a TimeoutException . The wrapped task may be cancelled when a timeout
 * occurs .
 * @ param time the time to wait before timing out
 * @ param unit the units for the time
 * @ param task the task to wrap
 * @ param < T > the value type for the task
 * @ return the new timeout task
 * @ deprecated As of 2.0.0 , replaced by { @ link Task # withTimeout ( long , TimeUnit ) Task . withTimeout } .
 * @ see Task # withTimeout ( long , TimeUnit ) Task . withTimeout */
@ Deprecated public static < T > Task < T > timeoutWithError ( final long time , final TimeUnit unit , final Task < T > task ) { } }

implementation: return task . withTimeout ( time , unit ) ;


signature:
public class Tasks { /** * Creates a new task that will run the given array of tasks sequentially
 * ( e . g . tasks [ 0 ] will be finished before tasks [ 1 ] is run ) . < strong > This
 * method is not type - safe < / strong > - prefer one of the { @ code seq } options
 * when possible . The value of this new task is the value of the last task in
 * the sequence .
 * @ param tasks the tasks to run sequentially
 * @ param < T > the result value for the sequence of tasks
 * @ return a new task that will run the given tasks sequentially */
@ SuppressWarnings ( "deprecation" ) private static < T > Task < T > vaseq ( final Task < ? > ... tasks ) { } }

implementation: return new SeqTask < T > ( "seq" , Arrays . asList ( tasks ) ) ;


signature:
public class Tasks { /** * Creates a new task that will run each of the supplied tasks in parallel ( e . g .
 * tasks [ 0 ] can be run at the same time as task2 ) . < strong > This method is not
 * type - safe < / strong > - prefer one of the { @ code par } options when possible .
 * When all tasks complete successfully , you can use
 * { @ link com . linkedin . parseq . ParTask # get ( ) } to get a list of the results . If
 * at least one task failed , then this task will also be marked as failed . Use
 * { @ link com . linkedin . parseq . ParTask # getTasks ( ) } or
 * { @ link com . linkedin . parseq . ParTask # getSuccessful ( ) } to get results in this
 * case .
 * @ param tasks the tasks to run in parallel
 * @ return a new task that will run the given tasks in parallel */
private static < T > ParTask < T > vapar ( final Task < ? > ... tasks ) { } }

implementation: final List < Task < T > > taskList = new ArrayList < Task < T > > ( tasks . length ) ; for ( Task < ? > task : tasks ) { @ SuppressWarnings ( "unchecked" ) final Task < T > typedTask = ( Task < T > ) task ; taskList . add ( typedTask ) ; } return par ( taskList ) ;


signature:
public class ZKUtil { /** * Decides whether the given { @ link Throwable throwable } is recoverable or not .
 * Recoverable exceptions are defined as such :
 * http : / / wiki . apache . org / hadoop / ZooKeeper / ErrorHandling
 * @ param t the { @ link Throwable }
 * @ return { @ code true } if { @ code t } is recoverable and { @ code false } otherwise . */
public static boolean isRecoverable ( Throwable t ) { } }

implementation: if ( t instanceof KeeperException ) { KeeperException ex = ( KeeperException ) t ; if ( ex . code ( ) == KeeperException . Code . CONNECTIONLOSS || ex . code ( ) == KeeperException . Code . OPERATIONTIMEOUT ) { return true ; } } return false ;


signature:
public class ZKUtil { /** * Finds node with next lowest sequence number than the given node within
 * the given list of nodes .
 * @ param children list of children
 * @ param node the given node to compare sequence number with
 * @ return the node with next lowest sequence number */
public static String findNodeWithNextLowestSN ( List < String > children , String node ) { } }

implementation: List < String > sortedChildren = children . stream ( ) . sorted ( ( String o1 , String o2 ) -> Long . compare ( getSequenceNumber ( o1 ) , getSequenceNumber ( o2 ) ) ) . collect ( Collectors . toList ( ) ) ; int index = sortedChildren . indexOf ( node ) ; if ( index > 0 ) { return sortedChildren . get ( index - 1 ) ; } else if ( index == 0 ) { return node ; } else { return null ; }


signature:
public class ZKUtil { /** * Gets 10 digit sequence number from the given znode per :
 * http : / / zookeeper . apache . org / doc / trunk / zookeeperProgrammers . html # Sequence + Nodes + - - + Unique + Naming */
private static long getSequenceNumber ( String node ) { } }

implementation: final int length = node . length ( ) ; try { String seqNumStr = node . substring ( length - 10 , length ) ; return Long . valueOf ( seqNumStr ) ; } catch ( IndexOutOfBoundsException | NumberFormatException ex ) { throw new IllegalArgumentException ( String . format ( "znode %s doesn't have sequence number" , node ) ) ; }


signature:
public class BaseTask { /** * Concatenate stack traces if kept the original stack trace from the task creation */
private void appendTaskStackTrace ( final Throwable error ) { } }

implementation:
StackTraceElement [ ] taskStackTrace = _taskStackTraceHolder != null ? _taskStackTraceHolder . getStackTrace ( ) : null ; // At a minimum , any stack trace should have at least 3 stack frames ( caller + BaseTask + getStackTrace ) .
// So if there are less than 3 stack frames available then there ' s something fishy and it ' s better to ignore them .
if ( ! ParSeqGlobalConfiguration . isCrossThreadStackTracesEnabled ( ) || error == null || taskStackTrace == null || taskStackTrace . length <= 2 ) { return ; } StackTraceElement [ ] errorStackTrace = error . getStackTrace ( ) ; if ( errorStackTrace . length <= 2 ) { return ; } // Skip stack frames up to the BaseTask ( useless java . util . concurrent stuff )
int skipErrorFrames = 1 ; while ( skipErrorFrames < errorStackTrace . length ) { int index = errorStackTrace . length - 1 - skipErrorFrames ; if ( ! errorStackTrace [ index ] . getClassName ( ) . equals ( CANONICAL_NAME ) && errorStackTrace [ index + 1 ] . getClassName ( ) . equals ( CANONICAL_NAME ) ) { break ; } skipErrorFrames ++ ; } // Safeguard against accidentally removing entire stack trace
if ( skipErrorFrames == errorStackTrace . length ) { skipErrorFrames = 0 ; } // Skip stack frames up to the BaseTask ( useless Thread . getStackTrace stuff )
int skipTaskFrames = 1 ; while ( skipTaskFrames < taskStackTrace . length ) { if ( ! taskStackTrace [ skipTaskFrames ] . getClassName ( ) . equals ( CANONICAL_NAME ) && taskStackTrace [ skipTaskFrames - 1 ] . getClassName ( ) . equals ( CANONICAL_NAME ) ) { break ; } skipTaskFrames ++ ; } // Safeguard against accidentally removing entire stack trace
if ( skipTaskFrames == taskStackTrace . length ) { skipTaskFrames = 0 ; } int combinedLength = errorStackTrace . length - skipErrorFrames + taskStackTrace . length - skipTaskFrames ; if ( combinedLength <= 0 ) { return ; } StackTraceElement [ ] concatenatedStackTrace = new StackTraceElement [ combinedLength + 1 ] ; System . arraycopy ( errorStackTrace , 0 , concatenatedStackTrace , 0 , errorStackTrace . length - skipErrorFrames ) ; concatenatedStackTrace [ errorStackTrace . length - skipErrorFrames ] = new StackTraceElement ( "********** Task \"" + getName ( ) + "\" (above) was instantiated as following (below): **********" , "" , null , 0 ) ; System . arraycopy ( taskStackTrace , skipTaskFrames , concatenatedStackTrace , errorStackTrace . length - skipErrorFrames + 1 , taskStackTrace . length - skipTaskFrames ) ; error . setStackTrace ( concatenatedStackTrace ) ;


signature:
public class ExecutionMonitor { /** * Main loop of monitoring thread . */
private void monitor ( ) { } }

implementation: _lastMonitoringStep = _clock . nanoTime ( ) ; _nextAllowedLogging = _lastMonitoringStep ; while ( ! _stopped ) { try { _clock . sleepNano ( _checkIntervalNano ) ; } catch ( InterruptedException e ) { break ; } monitorStep ( ) ; }


signature:
public class ExecutionMonitor { /** * Check how much we missed scheduled wake up and if it is larger than _ minStallNano
 * then consider it a stall and remember it . */
private void checkForStall ( long currentTime ) { } }

implementation: long delta = currentTime - _lastMonitoringStep ; if ( delta < _shortestObservedDelta ) { _shortestObservedDelta = delta ; } long stall = Math . max ( 0 , delta - _shortestObservedDelta ) ; if ( stall > _minStallNano ) { _stalls . put ( _lastMonitoringStep , stall ) ; if ( _stalls . size ( ) > _stallsHistorySize ) { _stalls . pollFirstEntry ( ) ; } }


signature:
public class RandomizedBackoff { /** * { @ inheritDoc } */
@ Override public long nextBackoff ( int attempts , Throwable error ) { } }

implementation: return _policy . nextBackoff ( attempts , error ) + _minRange + Math . round ( ( _maxRange - _minRange ) * ThreadLocalRandom . current ( ) . nextDouble ( ) ) ;


signature:
public class RequireEither { /** * { @ inheritDoc } */
@ Override public boolean shouldTerminate ( int attempts , long nextAttemptAt ) { } }

implementation: return _first . shouldTerminate ( attempts , nextAttemptAt ) || _second . shouldTerminate ( attempts , nextAttemptAt ) ;


signature:
public class RetriableTask { /** * A helper for creating task wrapper with associated retry policy .
 * @ param name A name of the task that needs to be retried .
 * @ param policy Retry policy that will control this task ' s behavior .
 * @ param taskFunction A task generator function . It will receive a zero - based attempt number as a parameter .
 * @ param < U > Type of a task result . */
public static < U > Task < U > withRetryPolicy ( String name , RetryPolicy policy , Function1 < Integer , Task < U > > taskFunction ) { } }

implementation: RetriableTask < U > retriableTask = new RetriableTask < > ( name , policy , taskFunction ) ; Task < U > retryTaskWrapper = Task . async ( name + " retriableTask" , retriableTask :: run ) ; retryTaskWrapper . getShallowTraceBuilder ( ) . setTaskType ( TaskType . WITH_RETRY . getName ( ) ) ; return retryTaskWrapper ;


signature:
public class RetriableTask { /** * Create a wrapped task with associated recovery task that will retry if necessary . */
private Task < T > wrap ( int attempt ) { } }

implementation:
Task < T > retryTask = Task . async ( _policy . getName ( ) + ", attempt " + attempt , context -> { final SettablePromise < T > result = Promises . settable ( ) ; Task < T > task = _taskFunction . apply ( attempt ) ; final Task < T > recovery = Task . async ( _name + " recovery" , recoveryContext -> { final SettablePromise < T > recoveryResult = Promises . settable ( ) ; if ( task . isFailed ( ) ) { // Failed task will cause retry to be scheduled .
ErrorClassification errorClassification = _policy . getErrorClassifier ( ) . apply ( task . getError ( ) ) ; retry ( attempt + 1 , task . getError ( ) , errorClassification , recoveryContext , recoveryResult ) ; } else { recoveryResult . done ( task . get ( ) ) ; } return recoveryResult ; } ) ; // Recovery task should run immediately after the original task to process its error .
recovery . setPriority ( Priority . MAX_PRIORITY ) ; recovery . getShallowTraceBuilder ( ) . setSystemHidden ( true ) ; Promises . propagateResult ( recovery , result ) ; context . after ( task ) . run ( recovery ) ; context . run ( task ) ; return result ; } ) ; retryTask . getShallowTraceBuilder ( ) . setTaskType ( TaskType . RETRY . getName ( ) ) ; return retryTask ;


signature:
public class RetriableTask { /** * Invoke event monitors and schedule a retry if policy allows . */
private void retry ( int attempt , Throwable error , ErrorClassification errorClassification , Context recoveryContext , SettablePromise < T > recoveryResult ) { } }

implementation:
long backoffTime = _policy . getBackoffPolicy ( ) . nextBackoff ( attempt , error ) ; if ( errorClassification == ErrorClassification . UNRECOVERABLE ) { // For fatal errors there are no retries .
LOGGER . debug ( String . format ( "Attempt %s of %s interrupted: %s" , attempt , _name , error . getMessage ( ) ) ) ; recoveryResult . fail ( error ) ; } else if ( _policy . getTerminationPolicy ( ) . shouldTerminate ( attempt , System . currentTimeMillis ( ) - _startedAt + backoffTime ) ) { // Retry policy commands that no more retries should be done .
LOGGER . debug ( String . format ( "Too many exceptions after attempt %s of %s, aborting: %s" , attempt , _name , error . getMessage ( ) ) ) ; recoveryResult . fail ( error ) ; } else { // Schedule a new retry task after a computed backoff timeout .
LOGGER . debug ( String . format ( "Attempt %s of %s failed and will be retried after %s millis: %s" , attempt , _name , backoffTime , error . getMessage ( ) ) ) ; Task < T > retryTask = wrap ( attempt ) ; Promises . propagateResult ( retryTask , recoveryResult ) ; recoveryContext . createTimer ( backoffTime , TimeUnit . MILLISECONDS , retryTask ) ; }


signature:
public class RetriableTask { /** * Starts a retriable task */
private Promise < ? extends T > run ( Context context ) { } }

implementation: _startedAt = System . currentTimeMillis ( ) ; Task < T > task = wrap ( 0 ) ; context . run ( task ) ; return task ;


signature:
public class ConfigValueCoercers { /** * Determine whether the given value String indicates a hex number , i . e . needs to be
 * passed into < code > Integer . decode < / code > instead of < code > Integer . valueOf < / code > ( etc ) . */
private static boolean isHexNumber ( String value ) { } }

implementation: int index = ( value . startsWith ( "-" ) ? 1 : 0 ) ; return ( value . startsWith ( "0x" , index ) || value . startsWith ( "0X" , index ) || value . startsWith ( "#" , index ) ) ;


signature:
public class ConfigValueCoercers { /** * Generates a consistent exception that can be used if coercion fails . */
private static Exception failCoercion ( final Object object , final Class < ? > targetType ) { } }

implementation: return new Exception ( "Could not convert object to " + targetType . getSimpleName ( ) + ". Object is instance of: " + object . getClass ( ) . getName ( ) + ", value: " + object . toString ( ) ) ;


signature:
public class ParSeqRestliClientBuilder { /** * This method may throw RuntimeException e . g . when there is a problem with configuration .
 * @ throws RuntimeException e . g . when there is a problem with configuration
 * @ return instance of ParSeqRestClient */
public ParSeqRestClient build ( ) { } }

implementation: if ( _inboundRequestContextFinder == null ) { LOGGER . debug ( "InboundRequestContextFinder not specified, using default one" ) ; } InboundRequestContextFinder inboundRequestContextFinder = _inboundRequestContextFinder == null ? ( ) -> Optional . empty ( ) : _inboundRequestContextFinder ; if ( _config != null ) { LOGGER . debug ( "One config specified" ) ; _configs = Collections . singletonMap ( DEFAULT_CONFIG , _config ) ; _configChooser = ( irc , r ) -> DEFAULT_CONFIG ; } else if ( _configs == null ) { throw new IllegalStateException ( "One type of config has to be specified using either setConfig() or setMultipleConfigs()." ) ; } else { LOGGER . debug ( "Multiple configs specified" ) ; } RequestConfigProvider configProvider = new MultipleRequestConfigProvider ( _configs , _configChooser , inboundRequestContextFinder ) ; Function < Request < ? > , RequestContext > requestContextProvider = ( _requestContextProvider == null ) ? request -> new RequestContext ( ) : _requestContextProvider ; ParSeqRestClient parseqClient = new ParSeqRestClient ( _client , configProvider , requestContextProvider , _d2RequestTimeoutEnabled ) ; if ( _batchingSupport != null ) { LOGGER . debug ( "Found batching support" ) ; _batchingSupport . registerStrategy ( parseqClient ) ; } else { LOGGER . debug ( "Did not find batching support" ) ; } return parseqClient ;


signature:
public class ParSeqRestliClientBuilder { /** * Sets the underlying Rest . li client implementation .
 * @ param client The underlying Rest . li client
 * @ deprecated Use # setClient instead
 * @ return The builder itself */
@ Deprecated public ParSeqRestliClientBuilder setRestClient ( RestClient client ) { } }

implementation: ArgumentUtil . requireNotNull ( client , "client" ) ; _client = client ; return this ;


signature:
public class Tuple7TaskDelegate { /** * { @ inheritDoc } */
@ Override public Tuple7 < T1 , T2 , T3 , T4 , T5 , T6 , T7 > get ( ) throws PromiseException { } }

implementation: return _task . get ( ) ;


signature:
public class ZKLock { /** * { @ inheritDoc } */
@ Override public < T > Task < T > synchronize ( Task < T > task , long deadline ) { } }

implementation:
return PlanLocal . get ( getPlanLocalKey ( ) , LockInternal . class ) . flatMap ( lockInternal -> { if ( lockInternal != null ) { // we already acquire the lock , add count only .
lockInternal . _lockCount ++ ; return Task . value ( lockInternal . _lockNode ) ; } else { // try acquire .
return acquire ( deadline ) ; } } ) /* run the given task with toTry ( ) */
. flatMap ( unused -> task ) . toTry ( ) /* release the lock and unwind the result */
. flatMap ( result -> release ( ) . andThen ( unwind ( result ) ) ) ;


signature:
public class ZKLock { /** * Unwinds the result from { @ link Task # toTry ( ) } .
 * @ return task with the raw result . */
private < T > Task < T > unwind ( Try < T > result ) { } }

implementation: if ( result . isFailed ( ) ) { return Task . failure ( result . getError ( ) ) ; } else { return Task . value ( result . get ( ) ) ; }


signature:
public class ZKLock { /** * Try to acquire the lock within the given deadline . */
private Task < String > acquire ( long deadline ) { } }

implementation:
final String uuid = UUID . randomUUID ( ) . toString ( ) ; return /* Step 1 : create znode with a pathname of " _ locknode _ / guid - lock - "
 * and the sequence and ephemeral flags set . */
safeCreateLockNode ( uuid , deadline , false ) . onFailure ( e -> _zkClient . deleteNodeHasUUID ( _lockPath , uuid ) ) . flatMap ( lockNode -> tryAcquire ( lockNode , deadline ) . withTimeout ( deadline - System . currentTimeMillis ( ) , TimeUnit . MILLISECONDS ) . onFailure ( e -> _zkClient . deleteNode ( lockNode ) ) ) ;


signature:
public class ZKLock { /** * Try to release the lock . */
private Task < Void > release ( ) { } }

implementation:
return PlanLocal . get ( getPlanLocalKey ( ) , LockInternal . class ) . flatMap ( lockInternal -> { // should never be null .
if ( lockInternal == null ) { LOG . error ( "LockInternal is null when releasing lock: " , _lockPath ) ; } else { lockInternal . _lockCount -- ; if ( lockInternal . _lockCount == 0 ) { return PlanLocal . remove ( getPlanLocalKey ( ) ) . flatMap ( unused -> _zkClient . delete ( lockInternal . _lockNode , - 1 ) . recover ( e -> { _zkClient . deleteNode ( lockInternal . _lockNode ) ; return null ; } ) ) ; } } return Task . value ( null ) ; } ) ;


signature:
public class Engine { /** * Runs the given task . Task passed in as a parameter becomes a root on a new Plan .
 * All tasks created and started as a consequence of a root task will belong to that plan and will share a Trace .
 * This method throws { @ code IllegalStateException } if Engine does not have capacity to run the task .
 * Engine ' s capacity is specified by a { @ value # MAX _ CONCURRENT _ PLANS } configuration property . Use
 * { @ link EngineBuilder # setEngineProperty ( String , Object ) } to set this property .
 * For the sake of backwards compatibility default value for a { @ value # MAX _ CONCURRENT _ PLANS } is
 * { @ value # DEFUALT _ MAX _ CONCURRENT _ PLANS } which essentially means " unbounded capacity " .
 * @ param task the task to run
 * @ param planClass string that identifies a " class " of the Plan . Plan class ends up in a ParSeq
 * Trace and can be used to group traces into " classes " when traces are statistically analyzed .
 * @ throws IllegalStateException */
public void run ( final Task < ? > task , final String planClass ) { } }

implementation: if ( ! tryRun ( task , planClass ) ) { throw new IllegalStateException ( "Starting new plan rejected, exceeded limit of concurrent plans: " + _maxConcurrentPlans ) ; }


signature:
public class Engine { /** * Runs the given task . Task passed in as a parameter becomes a root on a new Plan .
 * All tasks created and started as a consequence of a root task will belong to that plan and will share a Trace .
 * This method blocks until Engine has a capacity to run the task . Engine ' s capacity is
 * specified by a { @ value # MAX _ CONCURRENT _ PLANS } configuration property . Use
 * { @ link EngineBuilder # setEngineProperty ( String , Object ) } to set this property .
 * For the sake of backwards compatibility default value for a { @ value # MAX _ CONCURRENT _ PLANS } is
 * { @ value # DEFUALT _ MAX _ CONCURRENT _ PLANS } which essentially means " unbounded capacity " .
 * @ param task the task to run
 * @ param planClass string that identifies a " class " of the Plan . Plan class ends up in a ParSeq
 * Trace and can be used to group traces into " classes " when traces are statistically analyzed . */
public void blockingRun ( final Task < ? > task , final String planClass ) { } }

implementation: try { acquirePermit ( planClass ) ; runWithPermit ( task , planClass ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; }


signature:
public class Engine { /** * Runs the given task if Engine has a capacity to start new plan as specified by
 * { @ value # MAX _ CONCURRENT _ PLANS } configuration parameter .
 * For the sake of backwards compatibility default value for a { @ value # MAX _ CONCURRENT _ PLANS } is
 * { @ value # DEFUALT _ MAX _ CONCURRENT _ PLANS } which essentially means " unbounded capacity " .
 * Task passed in as a parameter becomes a root on a new Plan .
 * All tasks created and started as a consequence of a root task will belong to that plan and will share a Trace .
 * This method returns immediately and does not block . It returns { @ code true } if Plan was successfully started .
 * @ param task the task to run
 * @ param planClass string that identifies a " class " of the Plan
 * @ return true if Plan was started */
public boolean tryRun ( final Task < ? > task , final String planClass ) { } }

implementation: if ( tryAcquirePermit ( planClass ) ) { runWithPermit ( task , planClass ) ; return true ; } else { return false ; }