@ SuppressWarnings ( "PMD.UnnecessaryLocalBeforeReturn" ) < T > T putIfAbsent ( @ Nonnull final Key < T > key , @ Nonnull final Provider < T > valueComputer ) throws InterruptedException , ExecutionException { Preconditions . checkArgument ( key != null , "Key must not be null!" ) ; // Fast path, if the value exists, return it as fast as possible Future < ? > oldValue = contents . get ( key ) ; if ( oldValue != null ) { @ SuppressWarnings ( "unchecked" ) T value = ( T ) oldValue . get ( ) ; return value ; } FutureTask < T > task = new FutureTask <> ( new Callable < T > ( ) { @ Override public T call ( ) throws Exception { T value = valueComputer . get ( ) ; // Register the value if it listens to scoping events if ( value instanceof ScopeListener ) { final ScopeListener listener = ( ScopeListener ) value ; listeners . add ( listener ) ; // Send an "enter" event to notify the listener that it was put in scope. listener . event ( ScopeEvent . ENTER ) ; } return value ; } } ) ; Future < ? > existingTask = contents . putIfAbsent ( key , task ) ; if ( existingTask == null ) { // Now our task is in the map, so run it task . run ( ) ; return task . get ( ) ; } else { // Someone else beat us to it, make sure to throw our task away and use theirs @ SuppressWarnings ( "unchecked" ) T newValue = ( T ) existingTask . get ( ) ; return newValue ; } }
Compute and enter a value into the context unless the value has already been computed .