idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
28,900
private final Class loadClass2 ( String name ) throws ClassNotFoundException { Class z = findLoadedClass ( name ) ; // Look for pre-existing class if ( z != null ) return z ; if ( _weaver == null ) _weaver = new Weaver ( ) ; z = _weaver . weaveAndLoad ( name , this ) ; // Try the Happy Class Loader if ( z != null ) { // Occasionally it's useful to print out class names that are actually Weaved. // Leave this commented out println here so I can easily find it for next time. // System.out.println("WEAVED: " + name); return z ; } z = getParent ( ) . loadClass ( name ) ; // Try the parent loader. Probably the System loader. if ( z != null ) return z ; return z ; }
Run the class lookups in my favorite non - default order .
178
13
28,901
private RequestArguments . Argument arg ( Request R ) { if ( _arg != null ) return _arg ; Class clzz = R . getClass ( ) ; // An amazing crazy API from the JDK again. Cannot search for protected // fields without either (1) throwing NoSuchFieldException if you ask in // a subclass, or (2) sorting through the list of ALL fields and EACH // level of the hierarchy. Sadly, I catch NSFE & loop. while ( true ) { try { Field field = clzz . getDeclaredField ( _name ) ; field . setAccessible ( true ) ; Object o = field . get ( R ) ; return _arg = ( ( RequestArguments . Argument ) o ) ; } catch ( NoSuchFieldException ie ) { clzz = clzz . getSuperclass ( ) ; } catch ( IllegalAccessException ie ) { break ; } catch ( ClassCastException ie ) { break ; } } return null ; }
Specific accessors for input arguments . Not valid for JSON output fields .
204
14
28,902
public static void launchEC2 ( Class < ? extends Job > job , int boxes ) throws Exception { EC2 ec2 = new EC2 ( ) ; ec2 . boxes = boxes ; Cloud c = ec2 . resize ( ) ; launch ( c , job ) ; }
Starts EC2 machines and builds a cluster .
57
10
28,903
@ Override public void compute2 ( ) { if ( Job . isRunning ( _jobKey ) ) { Timer timer = new Timer ( ) ; _stats [ 0 ] = new ThreadLocal < hex . singlenoderf . Statistic > ( ) ; _stats [ 1 ] = new ThreadLocal < hex . singlenoderf . Statistic > ( ) ; Data d = _sampler . sample ( _data , _seed , _modelKey , _local_mode ) ; hex . singlenoderf . Statistic left = getStatistic ( 0 , d , _seed , _exclusiveSplitLimit ) ; // calculate the split for ( Row r : d ) left . addQ ( r , _regression ) ; if ( ! _regression ) left . applyClassWeights ( ) ; // Weight the distributions hex . singlenoderf . Statistic . Split spl = left . split ( d , false ) ; if ( spl . isLeafNode ( ) ) { if ( _regression ) { float av = d . computeAverage ( ) ; _tree = new LeafNode ( - 1 , d . rows ( ) , av ) ; } else { _tree = new LeafNode ( _data . unmapClass ( spl . _split ) , d . rows ( ) , - 1 ) ; } } else { _tree = new FJBuild ( spl , d , 0 , _seed ) . compute ( ) ; } _stats = null ; // GC if ( _jobKey != null && ! Job . isRunning ( _jobKey ) ) throw new Job . JobCancelledException ( ) ; // Atomically improve the Model as well Key tkey = toKey ( ) ; Key dtreeKey = null ; if ( _score_pojo ) dtreeKey = toCompressedKey ( ) ; appendKey ( _modelKey , tkey , dtreeKey , _verbose > 10 ? _tree . toString ( new StringBuilder ( "" ) , Integer . MAX_VALUE ) . toString ( ) : "" , _data_id ) ; // appendKey(_modelKey, tkey, _verbose > 10 ? _tree.toString(new StringBuilder(""), Integer.MAX_VALUE).toString() : "", _data_id); StringBuilder sb = new StringBuilder ( "[RF] Tree : " ) . append ( _data_id + 1 ) ; sb . append ( " d=" ) . append ( _tree . depth ( ) ) . append ( " leaves=" ) . append ( _tree . leaves ( ) ) . append ( " done in " ) . append ( timer ) . append ( ' ' ) ; Log . info ( sb . toString ( ) ) ; if ( _verbose > 10 ) { // Log.info(Sys.RANDF, _tree.toString(sb, Integer.MAX_VALUE).toString()); // Log.info(Sys.RANDF, _tree.toJava(sb, Integer.MAX_VALUE).toString()); } } else throw new Job . JobCancelledException ( ) ; // Wait for completion tryComplete ( ) ; }
Actually build the tree
669
4
28,904
static void appendKey ( Key model , final Key tKey , final Key dtKey , final String tString , final int tree_id ) { final int selfIdx = H2O . SELF . index ( ) ; new TAtomic < SpeeDRFModel > ( ) { @ Override public SpeeDRFModel atomic ( SpeeDRFModel old ) { if ( old == null ) return null ; return SpeeDRFModel . make ( old , tKey , dtKey , selfIdx , tString , tree_id ) ; } } . invoke ( model ) ; }
which serializes for free .
129
6
28,905
public Key toKey ( ) { AutoBuffer bs = new AutoBuffer ( ) ; bs . put4 ( _data_id ) ; bs . put8 ( _seed ) ; bs . put1 ( _producerId ) ; _tree . write ( bs ) ; Key key = Key . make ( ( byte ) 1 , Key . DFJ_INTERNAL_USER , H2O . SELF ) ; DKV . put ( key , new Value ( key , bs . buf ( ) ) ) ; return key ; }
Write the Tree to a random Key homed here .
117
11
28,906
public static double classify ( AutoBuffer ts , double [ ] ds , double badat , boolean regression ) { ts . get4 ( ) ; // Skip tree-id ts . get8 ( ) ; // Skip seed ts . get1 ( ) ; // Skip producer id byte b ; while ( ( b = ( byte ) ts . get1 ( ) ) != ' ' ) { // While not a leaf indicator assert b == ' ' || b == ' ' || b == ' ' ; int col = ts . get2 ( ) ; // Column number in model-space float fcmp = ts . get4f ( ) ; // Float to compare against float fdat = Double . isNaN ( ds [ col ] ) ? fcmp - 1 : ( float ) ds [ col ] ; int skip = ( ts . get1 ( ) & 0xFF ) ; if ( skip == 0 ) skip = ts . get3 ( ) ; if ( b == ' ' ) { if ( fdat != fcmp ) ts . position ( ts . position ( ) + skip ) ; } else { // Picking right subtree? then skip left subtree if ( fdat > fcmp ) ts . position ( ts . position ( ) + skip ) ; } } if ( regression ) return ts . get4f ( ) ; return ts . get1 ( ) & 0xFF ; // Return the leaf's class }
Classify on the compressed tree bytes from the pre - packed double data
296
14
28,907
public TreeModel . CompressedTree compress ( ) { // Log.info(Sys.RANDF, _tree.toString(new StringBuilder(), Integer.MAX_VALUE).toString()); int size = _tree . dtreeSize ( ) ; if ( _tree instanceof LeafNode ) { size += 3 ; } AutoBuffer ab = new AutoBuffer ( size ) ; if ( _tree instanceof LeafNode ) ab . put1 ( 0 ) . put2 ( ( char ) 65535 ) ; _tree . compress ( ab ) ; assert ab . position ( ) == size : "Actual size doesn't agree calculated size." ; char _nclass = ( char ) _data . classes ( ) ; return new TreeModel . CompressedTree ( ab . buf ( ) , _nclass , _seed ) ; }
Build a compressed - tree struct
173
6
28,908
@ Override protected void execImpl ( ) { Frame frame = source ; if ( shuffle ) { // FIXME: switch to global shuffle frame = MRUtils . shuffleFramePerChunk ( Utils . generateShuffledKey ( frame . _key ) , frame , seed ) ; frame . delete_and_lock ( null ) . unlock ( null ) ; // save frame to DKV // delete frame on the end gtrash ( frame ) ; } FrameSplitter fs = new FrameSplitter ( frame , ratios ) ; H2O . submitTask ( fs ) ; Frame [ ] splits = fs . getResult ( ) ; split_keys = new Key [ splits . length ] ; split_rows = new long [ splits . length ] ; float rsum = Utils . sum ( ratios ) ; split_ratios = Arrays . copyOf ( ratios , splits . length ) ; split_ratios [ splits . length - 1 ] = 1f - rsum ; long sum = 0 ; for ( int i = 0 ; i < splits . length ; i ++ ) { sum += splits [ i ] . numRows ( ) ; split_keys [ i ] = splits [ i ] . _key ; split_rows [ i ] = splits [ i ] . numRows ( ) ; } assert sum == source . numRows ( ) : "Frame split produced wrong number of rows: nrows(source) != sum(nrows(splits))" ; }
Run the function
311
3
28,909
public static < T > String qlink ( Class < T > page , Key k , String content ) { return qlink ( page , "source" , k , content ) ; }
Return the query link to this page
38
7
28,910
public static Object malloc ( int elems , long bytes , int type , Object orig , int from ) { return malloc ( elems , bytes , type , orig , from , false ) ; }
Catches OutOfMemory clears cache & retries .
42
11
28,911
public static boolean tryReserveTaskMem ( long m ) { if ( ! CAN_ALLOC ) return false ; if ( m == 0 ) return true ; assert m >= 0 : "m < 0: " + m ; long current = _taskMem . addAndGet ( - m ) ; if ( current < 0 ) { _taskMem . addAndGet ( m ) ; return false ; } return true ; }
Try to reserve memory needed for task execution and return true if succeeded . Tasks have a shared pool of memory which they should ask for in advance before they even try to allocate it .
88
37
28,912
private static int [ ] determineSeparatorCounts ( String from , int single_quote ) { int [ ] result = new int [ separators . length ] ; byte [ ] bits = from . getBytes ( ) ; boolean in_quote = false ; for ( int j = 0 ; j < bits . length ; j ++ ) { byte c = bits [ j ] ; if ( ( c == single_quote ) || ( c == CHAR_DOUBLE_QUOTE ) ) in_quote ^= true ; if ( ! in_quote || c == HIVE_SEP ) for ( int i = 0 ; i < separators . length ; ++ i ) if ( c == separators [ i ] ) ++ result [ i ] ; } return result ; }
Dermines the number of separators in given line . Correctly handles quoted tokens .
162
18
28,913
private static String [ ] determineTokens ( String from , byte separator , int single_quote ) { ArrayList < String > tokens = new ArrayList ( ) ; byte [ ] bits = from . getBytes ( ) ; int offset = 0 ; int quotes = 0 ; while ( offset < bits . length ) { while ( ( offset < bits . length ) && ( bits [ offset ] == CHAR_SPACE ) ) ++ offset ; // skip first whitespace if ( offset == bits . length ) break ; StringBuilder t = new StringBuilder ( ) ; byte c = bits [ offset ] ; if ( ( c == CHAR_DOUBLE_QUOTE ) || ( c == single_quote ) ) { quotes = c ; ++ offset ; } while ( offset < bits . length ) { c = bits [ offset ] ; if ( ( c == quotes ) ) { ++ offset ; if ( ( offset < bits . length ) && ( bits [ offset ] == c ) ) { t . append ( ( char ) c ) ; ++ offset ; continue ; } quotes = 0 ; } else if ( ( quotes == 0 ) && ( ( c == separator ) || ( c == CHAR_CR ) || ( c == CHAR_LF ) ) ) { break ; } else { t . append ( ( char ) c ) ; ++ offset ; } } c = ( offset == bits . length ) ? CHAR_LF : bits [ offset ] ; tokens . add ( t . toString ( ) ) ; if ( ( c == CHAR_CR ) || ( c == CHAR_LF ) || ( offset == bits . length ) ) break ; if ( c != separator ) return new String [ 0 ] ; // an error ++ offset ; // Skip separator } // If we have trailing empty columns (split by seperators) such as ",,\n" // then we did not add the final (empty) column, so the column count will // be down by 1. Add an extra empty column here if ( bits [ bits . length - 1 ] == separator && bits [ bits . length - 1 ] != CHAR_SPACE ) tokens . add ( "" ) ; return tokens . toArray ( new String [ tokens . size ( ) ] ) ; }
Determines the tokens that are inside a line and returns them as strings in an array . Assumes the given separator .
470
26
28,914
protected static void summarizeAndEnhanceModel ( ModelSummary summary , Model model , boolean find_compatible_frames , Map < String , Frame > all_frames , Map < String , Set < String > > all_frames_cols ) { if ( model instanceof GLMModel ) { summarizeGLMModel ( summary , ( GLMModel ) model ) ; } else if ( model instanceof DRF . DRFModel ) { summarizeDRFModel ( summary , ( DRF . DRFModel ) model ) ; } else if ( model instanceof hex . deeplearning . DeepLearningModel ) { summarizeDeepLearningModel ( summary , ( hex . deeplearning . DeepLearningModel ) model ) ; } else if ( model instanceof hex . gbm . GBM . GBMModel ) { summarizeGBMModel ( summary , ( hex . gbm . GBM . GBMModel ) model ) ; } else if ( model instanceof hex . singlenoderf . SpeeDRFModel ) { summarizeSpeeDRFModel ( summary , ( hex . singlenoderf . SpeeDRFModel ) model ) ; } else if ( model instanceof NBModel ) { summarizeNBModel ( summary , ( NBModel ) model ) ; } else { // catch-all summarizeModelCommonFields ( summary , model ) ; } if ( find_compatible_frames ) { Map < String , Frame > compatible_frames = findCompatibleFrames ( model , all_frames , all_frames_cols ) ; summary . compatible_frames = compatible_frames . keySet ( ) ; } }
Summarize subclasses of water . Model .
333
10
28,915
private static void summarizeModelCommonFields ( ModelSummary summary , Model model ) { String [ ] names = model . _names ; summary . warnings = model . warnings ; summary . model_algorithm = model . getClass ( ) . toString ( ) ; // fallback only // model.job() is a local copy; on multinode clusters we need to get from the DKV Key job_key = ( ( Job ) model . job ( ) ) . self ( ) ; if ( null == job_key ) throw H2O . fail ( "Null job key for model: " + ( model == null ? "null model" : model . _key ) ) ; // later when we deserialize models from disk we'll relax this constraint Job job = DKV . get ( job_key ) . get ( ) ; summary . state = job . getState ( ) ; summary . model_category = model . getModelCategory ( ) ; UniqueId unique_id = model . getUniqueId ( ) ; summary . id = unique_id . getId ( ) ; summary . key = unique_id . getKey ( ) ; summary . creation_epoch_time_millis = unique_id . getCreationEpochTimeMillis ( ) ; summary . training_duration_in_ms = model . training_duration_in_ms ; summary . response_column_name = names [ names . length - 1 ] ; for ( int i = 0 ; i < names . length - 1 ; i ++ ) summary . input_column_names . ( names [ i ] ) ; // Ugh. VarImp vi = model . varimp ( ) ; if ( null != vi ) { summary . variable_importances = new LinkedHashMap ( ) ; summary . variable_importances . put ( "varimp" , vi . varimp ) ; summary . variable_importances . put ( "variables" , vi . getVariables ( ) ) ; summary . variable_importances . put ( "method" , vi . method ) ; summary . variable_importances . put ( "max_var" , vi . max_var ) ; summary . variable_importances . put ( "scaled" , vi . scaled ( ) ) ; } }
Summarize fields which are generic to water . Model .
479
12
28,916
private static void summarizeGLMModel ( ModelSummary summary , hex . glm . GLMModel model ) { // add generic fields such as column names summarizeModelCommonFields ( summary , model ) ; summary . model_algorithm = "GLM" ; JsonObject all_params = ( model . get_params ( ) ) . toJSON ( ) ; summary . critical_parameters = whitelistJsonObject ( all_params , GLM_critical_params ) ; summary . secondary_parameters = whitelistJsonObject ( all_params , GLM_secondary_params ) ; summary . expert_parameters = whitelistJsonObject ( all_params , GLM_expert_params ) ; }
Summarize fields which are specific to hex . glm . GLMModel .
153
17
28,917
private static void summarizeDRFModel ( ModelSummary summary , hex . drf . DRF . DRFModel model ) { // add generic fields such as column names summarizeModelCommonFields ( summary , model ) ; summary . model_algorithm = "BigData RF" ; JsonObject all_params = ( model . get_params ( ) ) . toJSON ( ) ; summary . critical_parameters = whitelistJsonObject ( all_params , DRF_critical_params ) ; summary . secondary_parameters = whitelistJsonObject ( all_params , DRF_secondary_params ) ; summary . expert_parameters = whitelistJsonObject ( all_params , DRF_expert_params ) ; }
Summarize fields which are specific to hex . drf . DRF . DRFModel .
157
20
28,918
private static void summarizeSpeeDRFModel ( ModelSummary summary , hex . singlenoderf . SpeeDRFModel model ) { // add generic fields such as column names summarizeModelCommonFields ( summary , model ) ; summary . model_algorithm = "Random Forest" ; JsonObject all_params = ( model . get_params ( ) ) . toJSON ( ) ; summary . critical_parameters = whitelistJsonObject ( all_params , SpeeDRF_critical_params ) ; summary . secondary_parameters = whitelistJsonObject ( all_params , SpeeDRF_secondary_params ) ; summary . expert_parameters = whitelistJsonObject ( all_params , SpeeDRF_expert_params ) ; }
Summarize fields which are specific to hex . drf . DRF . SpeeDRFModel .
165
22
28,919
private static void summarizeDeepLearningModel ( ModelSummary summary , hex . deeplearning . DeepLearningModel model ) { // add generic fields such as column names summarizeModelCommonFields ( summary , model ) ; summary . model_algorithm = "DeepLearning" ; JsonObject all_params = ( model . get_params ( ) ) . toJSON ( ) ; summary . critical_parameters = whitelistJsonObject ( all_params , DL_critical_params ) ; summary . secondary_parameters = whitelistJsonObject ( all_params , DL_secondary_params ) ; summary . expert_parameters = whitelistJsonObject ( all_params , DL_expert_params ) ; }
Summarize fields which are specific to hex . deeplearning . DeepLearningModel .
150
17
28,920
private static void summarizeGBMModel ( ModelSummary summary , hex . gbm . GBM . GBMModel model ) { // add generic fields such as column names summarizeModelCommonFields ( summary , model ) ; summary . model_algorithm = "GBM" ; JsonObject all_params = ( model . get_params ( ) ) . toJSON ( ) ; summary . critical_parameters = whitelistJsonObject ( all_params , GBM_critical_params ) ; summary . secondary_parameters = whitelistJsonObject ( all_params , GBM_secondary_params ) ; summary . expert_parameters = whitelistJsonObject ( all_params , GBM_expert_params ) ; }
Summarize fields which are specific to hex . gbm . GBM . GBMModel .
156
20
28,921
private static void summarizeNBModel ( ModelSummary summary , hex . nb . NBModel model ) { // add generic fields such as column names summarizeModelCommonFields ( summary , model ) ; summary . model_algorithm = "Naive Bayes" ; JsonObject all_params = ( model . get_params ( ) ) . toJSON ( ) ; summary . critical_parameters = whitelistJsonObject ( all_params , NB_critical_params ) ; summary . secondary_parameters = whitelistJsonObject ( all_params , NB_secondary_params ) ; summary . expert_parameters = whitelistJsonObject ( all_params , NB_expert_params ) ; }
Summarize fields which are specific to hex . nb . NBModel .
150
16
28,922
protected Map < String , Model > fetchAll ( ) { return H2O . KeySnapshot . globalSnapshot ( ) . fetchAll ( water . Model . class ) ; }
Fetch all Models from the KV store .
38
10
28,923
private Response serveOneOrAll ( Map < String , Model > modelsMap ) { // returns empty sets if !this.find_compatible_frames Pair < Map < String , Frame > , Map < String , Set < String > > > frames_info = fetchFrames ( ) ; Map < String , Frame > all_frames = frames_info . getFirst ( ) ; Map < String , Set < String > > all_frames_cols = frames_info . getSecond ( ) ; Map < String , ModelSummary > modelSummaries = Models . generateModelSummaries ( null , modelsMap , find_compatible_frames , all_frames , all_frames_cols ) ; Map resultsMap = new LinkedHashMap ( ) ; resultsMap . put ( "models" , modelSummaries ) ; // If find_compatible_frames then include a map of the Frame summaries. Should we put this on a separate switch? if ( this . find_compatible_frames ) { Set < String > all_referenced_frames = new TreeSet < String > ( ) ; for ( Map . Entry < String , ModelSummary > entry : modelSummaries . entrySet ( ) ) { ModelSummary summary = entry . getValue ( ) ; all_referenced_frames . addAll ( summary . compatible_frames ) ; } Map < String , FrameSummary > frameSummaries = Frames . generateFrameSummaries ( all_referenced_frames , all_frames , false , null , null ) ; resultsMap . put ( "frames" , frameSummaries ) ; } // TODO: temporary hack to get things going String json = gson . toJson ( resultsMap ) ; JsonObject result = gson . fromJson ( json , JsonElement . class ) . getAsJsonObject ( ) ; return Response . done ( result ) ; }
Fetch all the Models from the KV store sumamrize and enhance them and return a map of them .
401
24
28,924
static ParseProgress make ( Key [ ] fkeys ) { long total = 0 ; for ( Key fkey : fkeys ) total += getVec ( fkey ) . length ( ) ; return new ParseProgress ( 0 , total ) ; }
Total number of steps is equal to total bytecount across files
53
12
28,925
protected static String xml2jname ( String xml ) { // Convert pname to a valid java name StringBuilder nn = new StringBuilder ( ) ; char [ ] cs = xml . toCharArray ( ) ; if ( ! Character . isJavaIdentifierStart ( cs [ 0 ] ) ) nn . append ( ' ' ) ; for ( char c : cs ) { if ( ! Character . isJavaIdentifierPart ( c ) ) { nn . append ( ' ' ) ; } else { nn . append ( c ) ; } } String jname = nn . toString ( ) ; return jname ; }
Convert an XML name to a java name
133
9
28,926
protected static String uniqueClassName ( String name ) { // Make a unique class name String cname = xml2jname ( name ) ; if ( CLASS_NAMES . contains ( cname ) ) { int i = 0 ; while ( CLASS_NAMES . contains ( cname + i ) ) i ++ ; cname = cname + i ; } CLASS_NAMES . add ( cname ) ; return cname ; }
Make a unique class name for jit d subclasses of ScoreModel
91
14
28,927
public int [ ] columnMapping ( String [ ] features ) { int [ ] map = new int [ _colNames . length ] ; for ( int i = 0 ; i < _colNames . length ; i ++ ) { map [ i ] = - 1 ; // Assume it is missing for ( int j = 0 ; j < features . length ; j ++ ) { if ( _colNames [ i ] . equals ( features [ j ] ) ) { if ( map [ i ] != - 1 ) throw new IllegalArgumentException ( "duplicate feature " + _colNames [ i ] ) ; map [ i ] = j ; } } if ( map [ i ] == - 1 ) Log . warn ( Sys . SCORM , "Model feature " + _colNames [ i ] + " not in the provided feature list from the data" ) ; } return map ; }
needs then this map will contain a - 1 for the missing feature index .
189
15
28,928
public void setHdfs ( ) { assert onICE ( ) ; byte [ ] mem = memOrLoad ( ) ; // Get into stable memory _persist = Value . HDFS | Value . NOTdsk ; Persist . I [ Value . HDFS ] . store ( this ) ; removeIce ( ) ; // Remove from ICE disk assert onHDFS ( ) ; // Flip to HDFS _mem = mem ; // Close a race with the H2O cleaner zapping _mem while removing from ice }
Set persistence to HDFS from ICE
109
7
28,929
public InputStream openStream ( ProgressMonitor p ) throws IOException { if ( onNFS ( ) ) return PersistNFS . openStream ( _key ) ; if ( onHDFS ( ) ) return PersistHdfs . openStream ( _key , p ) ; if ( onS3 ( ) ) return PersistS3 . openStream ( _key , p ) ; if ( onTachyon ( ) ) return PersistTachyon . openStream ( _key , p ) ; if ( isFrame ( ) ) throw new IllegalArgumentException ( "Tried to pass a Frame to openStream (maybe tried to parse a (already-parsed) Frame?)" ) ; assert _type == TypeMap . PRIM_B : "Expected byte[] type but got " + TypeMap . className ( _type ) ; return new ByteArrayInputStream ( memOrLoad ( ) ) ; }
Creates a Stream for reading bytes
198
7
28,930
void lowerActiveGetCount ( H2ONode h2o ) { assert _key . home ( ) ; // Only the HOME node for a key tracks replicas assert h2o != H2O . SELF ; // Do not track self as a replica while ( true ) { // Repeat, in case racing GETs are bumping the counter int old = _rwlock . get ( ) ; // Read the lock-word assert old > 0 ; // Since lowering, must be at least 1 assert old != - 1 ; // Not write-locked, because we are an active reader assert _replicas . contains ( h2o . _unique_idx ) ; // Self-bit is set if ( RW_CAS ( old , old - 1 , "rlock-" ) ) { if ( old - 1 == 0 ) // GET count fell to zero? synchronized ( this ) { notifyAll ( ) ; } // Notify any pending blocked PUTs return ; // Repeat until count is lowered } } }
Atomically lower active GET count
211
7
28,931
void startRemotePut ( ) { assert ! _key . home ( ) ; int x = 0 ; // assert I am waiting on threads with higher priority? while ( ( x = _rwlock . get ( ) ) != - 1 ) // Spin until rwlock==-1 if ( x == 1 || RW_CAS ( 0 , 1 , "remote_need_notify" ) ) try { ForkJoinPool . managedBlock ( this ) ; } catch ( InterruptedException e ) { } }
Block this thread until all prior remote PUTs complete - to force remote - PUT ordering on the home node .
106
24
28,932
public void clear ( ) { for ( Placeholder p : _placeholders . values ( ) ) { p . start . removeTill ( p . end ) ; } }
they can be used again .
36
6
28,933
public void replace ( String what , Object with ) { if ( what . charAt ( 0 ) == ' ' ) throw new RuntimeException ( "$ is now control char that denotes URL encoding!" ) ; for ( Placeholder p : _placeholders . get ( what ) ) p . end . insertAndAdvance ( with . toString ( ) ) ; for ( Placeholder p : _placeholders . get ( "$" + what ) ) try { p . end . insertAndAdvance ( URLEncoder . encode ( with . toString ( ) , "UTF-8" ) ) ; } catch ( IOException e ) { p . end . insertAndAdvance ( e . toString ( ) ) ; } }
another in order .
151
4
28,934
public RString restartGroup ( String what ) { List < Placeholder > all = _placeholders . get ( what ) ; assert all . size ( ) == 1 ; Placeholder result = all . get ( 0 ) ; if ( result . group == null ) { throw new NoSuchElementException ( "Element " + what + " is not a group." ) ; } result . group . clear ( ) ; return result . group ; }
can be filled again .
91
5
28,935
protected boolean handleAuthHeader ( GMS . GmsHeader gms_hdr , AuthHeader auth_hdr , Message msg ) { if ( needsAuthentication ( gms_hdr ) ) { if ( this . auth_token . authenticate ( auth_hdr . getToken ( ) , msg ) ) return true ; // authentication passed, send message up the stack else { log . warn ( "%s: failed to validate AuthHeader (token: %s) from %s; dropping message and sending " + "rejection message" , local_addr , auth_token . getClass ( ) . getSimpleName ( ) , msg . src ( ) ) ; sendRejectionMessage ( gms_hdr . getType ( ) , msg . getSrc ( ) , "authentication failed" ) ; return false ; } } return true ; }
Handles a GMS header
181
6
28,936
public synchronized void stop ( ) { Thread tmp = runner ; runner = null ; if ( tmp != null ) { tmp . interrupt ( ) ; try { tmp . join ( 500 ) ; } catch ( InterruptedException e ) { } } // we may need to do multiple iterations as the iterator works on a copy and tasks might have been added just // after the iterator() call returned while ( ! queue . isEmpty ( ) ) for ( Task entry : queue ) { entry . cancel ( true ) ; queue . remove ( entry ) ; } queue . clear ( ) ; if ( pool instanceof ThreadPoolExecutor && shut_down_pool ) { ThreadPoolExecutor p = ( ThreadPoolExecutor ) pool ; List < Runnable > remaining_tasks = p . shutdownNow ( ) ; remaining_tasks . stream ( ) . filter ( task -> task instanceof Future ) . forEach ( task -> ( ( Future ) task ) . cancel ( true ) ) ; p . getQueue ( ) . clear ( ) ; try { p . awaitTermination ( Global . THREADPOOL_SHUTDOWN_WAIT_TIME , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException e ) { } } // clears the threads list (https://issues.jboss.org/browse/JGRP-1971) if ( timer_thread_factory instanceof LazyThreadFactory ) ( ( LazyThreadFactory ) timer_thread_factory ) . destroy ( ) ; }
Stops the timer cancelling all tasks
318
8
28,937
@ ManagedOperation ( description = "Prints the send and receive buffers" ) public String printBuffers ( ) { StringBuilder sb = new StringBuilder ( "\n" ) ; synchronized ( this ) { for ( Map . Entry < Address , Connection > entry : conns . entrySet ( ) ) { NioConnection val = ( NioConnection ) entry . getValue ( ) ; sb . append ( entry . getKey ( ) ) . append ( ":\n " ) . append ( "recv_buf: " ) . append ( val . recv_buf ) . append ( "\n send_buf: " ) . append ( val . send_buf ) . append ( "\n" ) ; } } return sb . toString ( ) ; }
Prints send and receive buffers for all connections
163
9
28,938
public void stable ( long seqno ) { lock . lock ( ) ; try { if ( seqno <= low ) return ; if ( seqno > hd ) throw new IllegalArgumentException ( "seqno " + seqno + " cannot be bigger than hd (" + hd + ")" ) ; int from = index ( low + 1 ) , length = ( int ) ( seqno - low ) , capacity = capacity ( ) ; for ( int i = from ; i < from + length ; i ++ ) { int index = i & ( capacity - 1 ) ; buf [ index ] = null ; } // Releases some of the blocked adders if ( seqno > low ) { low = seqno ; buffer_full . signalAll ( ) ; } } finally { lock . unlock ( ) ; } }
Nulls elements between low and seqno and forwards low
171
11
28,939
public void adjustNodes ( java . util . List < Address > v ) { Node n ; boolean removed = false ; synchronized ( nodes ) { for ( int i = 0 ; i < nodes . size ( ) ; i ++ ) { n = nodes . get ( i ) ; if ( ! v . contains ( n . addr ) ) { System . out . println ( "adjustNodes(): node " + n + " was removed" ) ; nodes . remove ( n ) ; removed = true ; } } if ( removed ) repaint ( ) ; } }
Removes nodes that are not in the view
117
9
28,940
public void start ( JChannel ch ) throws Exception { channel = ch ; channel . setReceiver ( this ) ; channel . connect ( "ChatCluster" ) ; eventLoop ( ) ; channel . close ( ) ; }
Method called from other app injecting channel
47
7
28,941
public boolean waitForAllResponses ( long timeout ) { if ( timeout <= 0 ) timeout = 2000L ; return cond . waitFor ( this :: hasAllResponses , timeout , TimeUnit . MILLISECONDS ) ; }
Waits until all responses have been received or until a timeout has elapsed .
51
15
28,942
public int deliveryTableSize ( ) { int retval = 0 ; for ( BoundedHashMap < Long , Long > val : delivery_table . values ( ) ) retval += val . size ( ) ; return retval ; }
Total size of all queues of the delivery table
49
9
28,943
protected boolean canDeliver ( Address sender , long seqno ) { BoundedHashMap < Long , Long > seqno_set = delivery_table . get ( sender ) ; if ( seqno_set == null ) { seqno_set = new BoundedHashMap <> ( delivery_table_max_size ) ; BoundedHashMap < Long , Long > existing = delivery_table . put ( sender , seqno_set ) ; if ( existing != null ) seqno_set = existing ; } return seqno_set . add ( seqno , seqno ) ; }
Checks if seqno has already been received from sender . This weeds out duplicates . Note that this method is never called concurrently for the same sender .
124
31
28,944
public static Subject generateSecuritySubject ( String jassLoginConfig , String username , String password ) throws LoginException { LoginContext loginCtx = null ; try { // "Client" references the JAAS configuration in the jaas.conf file. loginCtx = new LoginContext ( jassLoginConfig , new Krb5TokenUtils . LoginCallbackHandler ( username , password ) ) ; loginCtx . login ( ) ; log . debug ( " : Krb5Token Kerberos login succeeded against user: %s" , username ) ; return loginCtx . getSubject ( ) ; } catch ( LoginException e ) { log . debug ( " : Krb5Token Kerberos login failed against user: %s" , username ) ; throw e ; } }
Authenticate against the KDC using JAAS .
162
10
28,945
public static byte [ ] initiateSecurityContext ( Subject subject , String servicePrincipalName ) throws GSSException { GSSManager manager = GSSManager . getInstance ( ) ; GSSName serverName = manager . createName ( servicePrincipalName , GSSName . NT_HOSTBASED_SERVICE ) ; final GSSContext context = manager . createContext ( serverName , krb5Oid , null , GSSContext . DEFAULT_LIFETIME ) ; // The GSS context initiation has to be performed as a privileged action. return Subject . doAs ( subject , ( PrivilegedAction < byte [ ] > ) ( ) -> { try { byte [ ] token = new byte [ 0 ] ; // This is a one pass context initialization. context . requestMutualAuth ( false ) ; context . requestCredDeleg ( false ) ; return context . initSecContext ( token , 0 , token . length ) ; } catch ( GSSException e ) { log . error ( Util . getMessage ( "Krb5TokenKerberosContextProcessingException" ) , e ) ; return null ; } } ) ; }
Generate the service ticket that will be passed to the cluster master for authentication
245
15
28,946
public static String validateSecurityContext ( Subject subject , final byte [ ] serviceTicket ) throws GSSException { // Accept the context and return the client principal name. return Subject . doAs ( subject , ( PrivilegedAction < String > ) ( ) -> { try { // Identify the server that communications are being made // to. GSSManager manager = GSSManager . getInstance ( ) ; GSSContext context = manager . createContext ( ( GSSCredential ) null ) ; context . acceptSecContext ( serviceTicket , 0 , serviceTicket . length ) ; return context . getSrcName ( ) . toString ( ) ; } catch ( Exception e ) { log . error ( Util . getMessage ( "Krb5TokenKerberosContextProcessingException" ) , e ) ; return null ; } } ) ; }
Validate the service ticket by extracting the client principal name
181
11
28,947
public int compareTo ( ViewId other ) { return id > other . id ? 1 : id < other . id ? - 1 : creator . compareTo ( other . creator ) ; }
Establishes an order between 2 ViewIds . The comparison is done on the IDs if they are equal we use the creator .
39
27
28,948
public < T extends ViewHandler < R > > T processing ( boolean flag ) { lock . lock ( ) ; try { setProcessing ( flag ) ; return ( T ) this ; } finally { lock . unlock ( ) ; } }
To be used by testing only!
49
7
28,949
protected void process ( Collection < R > requests ) { for ( ; ; ) { while ( ! requests . isEmpty ( ) ) { removeAndProcess ( requests ) ; // remove matching requests and process them } lock . lock ( ) ; try { if ( requests . isEmpty ( ) ) { setProcessing ( false ) ; return ; } } finally { lock . unlock ( ) ; } } }
We re guaranteed that only one thread will be called with this method at any time
83
16
28,950
public void setResult ( T obj ) { lock . lock ( ) ; try { result = obj ; hasResult = true ; cond . signal ( true ) ; } finally { lock . unlock ( ) ; } }
Sets the result and notifies any threads waiting for it
44
12
28,951
protected T _getResultWithTimeout ( final long timeout ) throws TimeoutException { if ( timeout <= 0 ) cond . waitFor ( this :: hasResult ) ; else if ( ! cond . waitFor ( this :: hasResult , timeout , TimeUnit . MILLISECONDS ) ) throw new TimeoutException ( ) ; return result ; }
Blocks until a result is available or timeout milliseconds have elapsed . Needs to be called with lock held
72
19
28,952
public void handleViewChange ( View view , Digest digest ) { if ( gms . isLeaving ( ) && ! view . containsMember ( gms . local_addr ) ) return ; View prev_view = gms . view ( ) ; gms . installView ( view , digest ) ; Address prev_coord = prev_view != null ? prev_view . getCoord ( ) : null , curr_coord = view . getCoord ( ) ; if ( ! Objects . equals ( curr_coord , prev_coord ) ) coordChanged ( prev_coord , curr_coord ) ; }
Called by the GMS when a VIEW is received .
130
12
28,953
protected boolean sendLeaveReqToCoord ( final Address coord ) { if ( coord == null ) { log . warn ( "%s: cannot send LEAVE request to null coord" , gms . getLocalAddress ( ) ) ; return false ; } Promise < Address > leave_promise = gms . getLeavePromise ( ) ; gms . setLeaving ( true ) ; log . trace ( "%s: sending LEAVE request to %s" , gms . local_addr , coord ) ; long start = System . currentTimeMillis ( ) ; sendLeaveMessage ( coord , gms . local_addr ) ; Address sender = leave_promise . getResult ( gms . leave_timeout ) ; if ( ! Objects . equals ( coord , sender ) ) return false ; long time = System . currentTimeMillis ( ) - start ; if ( sender != null ) log . trace ( "%s: got LEAVE response from %s in %d ms" , gms . local_addr , coord , time ) ; else log . trace ( "%s: timed out waiting for LEAVE response from %s (after %d ms)" , gms . local_addr , coord , time ) ; return true ; }
Sends a leave request to coord and blocks until a leave response has been received or the leave timeout has elapsed
265
22
28,954
public static boolean isBinaryCompatible ( short ver ) { if ( version == ver ) return true ; short tmp_major = ( short ) ( ( ver & MAJOR_MASK ) >> MAJOR_SHIFT ) ; short tmp_minor = ( short ) ( ( ver & MINOR_MASK ) >> MINOR_SHIFT ) ; return major == tmp_major && minor == tmp_minor ; }
Checks whether ver is binary compatible with the current version . The rule for binary compatibility is that the major and minor versions have to match whereas micro versions can differ .
92
33
28,955
public void connect ( String group , Address addr , String logical_name , PhysicalAddress phys_addr ) throws Exception { synchronized ( this ) { _doConnect ( ) ; } try { writeRequest ( new GossipData ( GossipType . REGISTER , group , addr , logical_name , phys_addr ) ) ; } catch ( Exception ex ) { throw new Exception ( String . format ( "connection to %s failed: %s" , group , ex ) ) ; } }
Registers mbr with the GossipRouter under the given group with the given logical name and physical address . Establishes a connection to the GossipRouter and sends a CONNECT message .
101
41
28,956
public int compareTo ( Address o ) { int h1 , h2 , rc ; // added Nov 7 2005, makes sense with canonical addresses if ( this == o ) return 0 ; if ( ! ( o instanceof IpAddress ) ) throw new ClassCastException ( "comparison between different classes: the other object is " + ( o != null ? o . getClass ( ) : o ) ) ; IpAddress other = ( IpAddress ) o ; if ( ip_addr == null ) if ( other . ip_addr == null ) return port < other . port ? - 1 : ( port > other . port ? 1 : 0 ) ; else return - 1 ; h1 = ip_addr . hashCode ( ) ; h2 = other . ip_addr . hashCode ( ) ; rc = h1 < h2 ? - 1 : h1 > h2 ? 1 : 0 ; return rc != 0 ? rc : port < other . port ? - 1 : ( port > other . port ? 1 : 0 ) ; }
implements the java . lang . Comparable interface
219
11
28,957
public Membership add ( Collection < Address > v ) { if ( v != null ) v . forEach ( this :: add ) ; return this ; }
Adds a list of members to this membership
31
8
28,958
public Membership remove ( Address old_member ) { if ( old_member != null ) { synchronized ( members ) { members . remove ( old_member ) ; } } return this ; }
Removes an member from the membership . If this member doesn t exist no action will be performed on the existing membership
39
23
28,959
public Membership remove ( Collection < Address > v ) { if ( v != null ) { synchronized ( members ) { members . removeAll ( v ) ; } } return this ; }
Removes all the members contained in v from this membership
37
11
28,960
public Membership merge ( Collection < Address > new_mems , Collection < Address > suspects ) { remove ( suspects ) ; return add ( new_mems ) ; }
Merges membership with the new members and removes suspects . The Merge method will remove all the suspects and add in the new members . It will do it in the order 1 . Remove suspects 2 . Add new members the order is very important to notice .
35
50
28,961
public boolean contains ( Address member ) { if ( member == null ) return false ; synchronized ( members ) { return members . contains ( member ) ; } }
Returns true if the provided member belongs to this membership
32
10
28,962
public Set getChildrenNames ( String fqn ) { Node n = findNode ( fqn ) ; Map m ; if ( n == null ) return null ; m = n . getChildren ( ) ; if ( m != null ) return m . keySet ( ) ; else return null ; }
Returns all children of a given node
63
7
28,963
public boolean containsKeys ( Collection < K > keys ) { for ( K key : keys ) if ( ! map . containsKey ( key ) ) return false ; return true ; }
Returns true if all of the keys in keys are present . Returns false if one or more of the keys are absent
37
23
28,964
public Set < V > nonRemovedValues ( ) { return map . values ( ) . stream ( ) . filter ( entry -> ! entry . removable ) . map ( entry -> entry . val ) . collect ( Collectors . toSet ( ) ) ; }
Adds all value which have not been marked as removable to the returned set
53
14
28,965
public void removeMarkedElements ( boolean force ) { long curr_time = System . nanoTime ( ) ; for ( Iterator < Map . Entry < K , Entry < V > > > it = map . entrySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Map . Entry < K , Entry < V > > entry = it . next ( ) ; Entry < V > tmp = entry . getValue ( ) ; if ( tmp == null ) continue ; if ( tmp . removable && ( force || ( curr_time - tmp . timestamp ) >= max_age ) ) { it . remove ( ) ; } } }
Removes elements marked as removable
139
6
28,966
public void setResult ( T result ) { lock . lock ( ) ; try { if ( Objects . equals ( expected_result , result ) ) super . setResult ( result ) ; } finally { lock . unlock ( ) ; } }
Sets the result only if expected_result matches result
49
11
28,967
protected static String sanitize ( final String name ) { String retval = name ; retval = retval . replace ( ' ' , ' ' ) ; retval = retval . replace ( ' ' , ' ' ) ; return retval ; }
Sanitizes bucket and folder names according to AWS guidelines
53
11
28,968
public Map < Thread , Runnable > getCurrentRunningTasks ( ) { Map < Thread , Runnable > map = new HashMap <> ( ) ; for ( Entry < Thread , Holder < Runnable > > entry : _runnables . entrySet ( ) ) { map . put ( entry . getKey ( ) , entry . getValue ( ) . value ) ; } return map ; }
Returns a copy of the runners being used with the runner and what threads . If a thread is not currently running a task it will return with a null value . This map is a copy and can be modified if necessary without causing issues .
87
47
28,969
public boolean add ( T obj ) { if ( obj == null ) return false ; while ( size ( ) >= max_capacity && size ( ) > 0 ) { poll ( ) ; } return super . add ( obj ) ; }
Adds an element at the tail . Removes an object from the head if capacity is exceeded
48
18
28,970
protected static FORK getFORK ( JChannel ch , ProtocolStack . Position position , Class < ? extends Protocol > neighbor , boolean create_fork_if_absent ) throws Exception { ProtocolStack stack = ch . getProtocolStack ( ) ; FORK fork = stack . findProtocol ( FORK . class ) ; if ( fork == null ) { if ( ! create_fork_if_absent ) throw new IllegalArgumentException ( "FORK not found in main stack" ) ; fork = new FORK ( ) ; fork . setProtocolStack ( stack ) ; stack . insertProtocol ( fork , position , neighbor ) ; } return fork ; }
Creates a new FORK protocol or returns the existing one or throws an exception . Never returns null .
141
21
28,971
protected void copyFields ( ) { for ( Field field : copied_fields ) { Object value = Util . getField ( field , main_channel ) ; Util . setField ( field , this , value ) ; } }
Copies state from main - channel to this fork - channel
49
12
28,972
protected Map < String , Map < String , Object > > dumpAttrsSelectedProtocol ( String protocol_name , List < String > attrs ) { return ch . dumpStats ( protocol_name , attrs ) ; }
Dumps attributes and their values of a given protocol .
48
11
28,973
protected void handleOperation ( Map < String , String > map , String operation ) throws Exception { int index = operation . indexOf ( ' ' ) ; if ( index == - 1 ) throw new IllegalArgumentException ( "operation " + operation + " is missing the protocol name" ) ; String prot_name = operation . substring ( 0 , index ) ; Protocol prot = ch . getProtocolStack ( ) . findProtocol ( prot_name ) ; if ( prot == null ) { log . error ( "protocol %s not found" , prot_name ) ; return ; // less drastic than throwing an exception... } int args_index = operation . indexOf ( ' ' ) ; String method_name ; if ( args_index != - 1 ) method_name = operation . substring ( index + 1 , args_index ) . trim ( ) ; else method_name = operation . substring ( index + 1 ) . trim ( ) ; String [ ] args = null ; if ( args_index != - 1 ) { int end_index = operation . indexOf ( ' ' ) ; if ( end_index == - 1 ) throw new IllegalArgumentException ( "] not found" ) ; List < String > str_args = Util . parseCommaDelimitedStrings ( operation . substring ( args_index + 1 , end_index ) ) ; Object [ ] strings = str_args . toArray ( ) ; args = new String [ strings . length ] ; for ( int i = 0 ; i < strings . length ; i ++ ) args [ i ] = ( String ) strings [ i ] ; } Method method = findMethod ( prot , method_name , args ) ; MethodCall call = new MethodCall ( method ) ; Object [ ] converted_args = null ; if ( args != null ) { converted_args = new Object [ args . length ] ; Class < ? > [ ] types = method . getParameterTypes ( ) ; for ( int i = 0 ; i < args . length ; i ++ ) converted_args [ i ] = Util . convert ( args [ i ] , types [ i ] ) ; } Object retval = call . invoke ( prot , converted_args ) ; if ( retval != null ) map . put ( prot_name + "." + method_name , retval . toString ( ) ) ; }
Invokes an operation and puts the return value into map
503
11
28,974
public void send ( Message msg ) throws Exception { num_senders . incrementAndGet ( ) ; long size = msg . size ( ) ; lock . lock ( ) ; try { if ( count + size >= transport . getMaxBundleSize ( ) ) sendBundledMessages ( ) ; addMessage ( msg , size ) ; // at this point, we haven't sent our message yet ! if ( num_senders . decrementAndGet ( ) == 0 ) // no other sender threads present at this time sendBundledMessages ( ) ; // else there are other sender threads waiting, so our message will be sent by a different thread } finally { lock . unlock ( ) ; } }
current senders adding msgs to the bundler
148
10
28,975
public int getNumDeliverable ( ) { NumDeliverable visitor = new NumDeliverable ( ) ; lock . lock ( ) ; try { forEach ( hd + 1 , hr , visitor ) ; return visitor . getResult ( ) ; } finally { lock . unlock ( ) ; } }
Returns the number of messages that can be delivered
64
9
28,976
public boolean add ( final List < LongTuple < T > > list , boolean remove_added_elements ) { return add ( list , remove_added_elements , null ) ; }
Adds elements from list to the table removes elements from list that were not added to the table
41
18
28,977
public boolean add ( final List < LongTuple < T > > list , boolean remove_added_elements , T const_value ) { if ( list == null || list . isEmpty ( ) ) return false ; boolean added = false ; // find the highest seqno (unfortunately, the list is not ordered by seqno) long highest_seqno = findHighestSeqno ( list ) ; lock . lock ( ) ; try { if ( highest_seqno != - 1 && computeRow ( highest_seqno ) >= matrix . length ) resize ( highest_seqno ) ; for ( Iterator < LongTuple < T > > it = list . iterator ( ) ; it . hasNext ( ) ; ) { LongTuple < T > tuple = it . next ( ) ; long seqno = tuple . getVal1 ( ) ; T element = const_value != null ? const_value : tuple . getVal2 ( ) ; if ( _add ( seqno , element , false , null ) ) added = true ; else if ( remove_added_elements ) it . remove ( ) ; } return added ; } finally { lock . unlock ( ) ; } }
Adds elements from the list to the table
251
8
28,978
public T get ( long seqno ) { lock . lock ( ) ; try { if ( seqno - low <= 0 || seqno - hr > 0 ) return null ; int row_index = computeRow ( seqno ) ; if ( row_index < 0 || row_index >= matrix . length ) return null ; T [ ] row = matrix [ row_index ] ; if ( row == null ) return null ; int index = computeIndex ( seqno ) ; return index >= 0 ? row [ index ] : null ; } finally { lock . unlock ( ) ; } }
Returns an element at seqno
121
6
28,979
public T _get ( long seqno ) { lock . lock ( ) ; try { int row_index = computeRow ( seqno ) ; if ( row_index < 0 || row_index >= matrix . length ) return null ; T [ ] row = matrix [ row_index ] ; if ( row == null ) return null ; int index = computeIndex ( seqno ) ; return index >= 0 ? row [ index ] : null ; } finally { lock . unlock ( ) ; } }
To be used only for testing ; doesn t do any index or sanity checks
103
15
28,980
public T remove ( boolean nullify ) { lock . lock ( ) ; try { int row_index = computeRow ( hd + 1 ) ; if ( row_index < 0 || row_index >= matrix . length ) return null ; T [ ] row = matrix [ row_index ] ; if ( row == null ) return null ; int index = computeIndex ( hd + 1 ) ; if ( index < 0 ) return null ; T existing_element = row [ index ] ; if ( existing_element != null ) { hd ++ ; size = Math . max ( size - 1 , 0 ) ; // cannot be < 0 (well that would be a bug, but let's have this 2nd line of defense !) if ( nullify ) { row [ index ] = null ; if ( hd - low > 0 ) low = hd ; } } return existing_element ; } finally { lock . unlock ( ) ; } }
Removes the next non - null element and nulls the index if nullify = true
198
18
28,981
public < R > R removeMany ( boolean nullify , int max_results , Predicate < T > filter , Supplier < R > result_creator , BiConsumer < R , T > accumulator ) { lock . lock ( ) ; try { Remover < R > remover = new Remover <> ( nullify , max_results , filter , result_creator , accumulator ) ; forEach ( hd + 1 , hr , remover ) ; return remover . getResult ( ) ; } finally { lock . unlock ( ) ; } }
Removes elements from the table and adds them to the result created by result_creator . Between 0 and max_results elements are removed . If no elements were removed processing will be set to true while the table lock is held .
117
46
28,982
protected long findHighestSeqno ( List < LongTuple < T > > list ) { long seqno = - 1 ; for ( LongTuple < T > tuple : list ) { long val = tuple . getVal1 ( ) ; if ( val - seqno > 0 ) seqno = val ; } return seqno ; }
list must not be null or empty
72
7
28,983
public SeqnoList getMissing ( int max_msgs ) { lock . lock ( ) ; try { if ( size == 0 ) return null ; long start_seqno = getHighestDeliverable ( ) + 1 ; int capacity = ( int ) ( hr - start_seqno ) ; int max_size = max_msgs > 0 ? Math . min ( max_msgs , capacity ) : capacity ; if ( max_size <= 0 ) return null ; Missing missing = new Missing ( start_seqno , max_size ) ; long to = max_size > 0 ? Math . min ( start_seqno + max_size - 1 , hr - 1 ) : hr - 1 ; forEach ( start_seqno , to , missing ) ; return missing . getMissingElements ( ) ; } finally { lock . unlock ( ) ; } }
Returns a list of missing messages
184
6
28,984
public String dump ( ) { lock . lock ( ) ; try { return stream ( low , hr ) . filter ( Objects :: nonNull ) . map ( Object :: toString ) . collect ( Collectors . joining ( ", " ) ) ; } finally { lock . unlock ( ) ; } }
Dumps the seqnos in the table as a list
61
11
28,985
@ GuardedBy ( "lock" ) protected T [ ] getRow ( int index ) { T [ ] row = matrix [ index ] ; if ( row == null ) { row = ( T [ ] ) new Object [ elements_per_row ] ; matrix [ index ] = row ; } return row ; }
Returns a row . Creates a new row and inserts it at index if the row at index doesn t exist
66
22
28,986
protected Tuple < SecretKey , byte [ ] > getSecretKeyFromAbove ( ) { return ( Tuple < SecretKey , byte [ ] > ) up_prot . up ( new Event ( Event . GET_SECRET_KEY ) ) ; }
Fetches the secret key from a protocol above us
53
11
28,987
protected void setSecretKeyAbove ( Tuple < SecretKey , byte [ ] > key ) { up_prot . up ( new Event ( Event . SET_SECRET_KEY , key ) ) ; }
Sets the secret key in a protocol above us
43
10
28,988
public static ProtocolStackConfigurator getStackConfigurator ( File file ) throws Exception { checkJAXPAvailability ( ) ; InputStream input = getConfigStream ( file ) ; return XmlConfigurator . getInstance ( input ) ; }
Returns a protocol stack configurator based on the XML configuration provided by the specified File .
53
18
28,989
public static ProtocolStackConfigurator getStackConfigurator ( URL url ) throws Exception { checkForNullConfiguration ( url ) ; checkJAXPAvailability ( ) ; return XmlConfigurator . getInstance ( url ) ; }
Returns a protocol stack configurator based on the XML configuration provided at the specified URL .
50
18
28,990
public static ProtocolStackConfigurator getStackConfigurator ( Element element ) throws Exception { checkForNullConfiguration ( element ) ; return XmlConfigurator . getInstance ( element ) ; }
Returns a protocol stack configurator based on the XML configuration provided by the specified XML element .
41
19
28,991
public static ProtocolStackConfigurator getStackConfigurator ( String properties ) throws Exception { if ( properties == null ) properties = Global . DEFAULT_PROTOCOL_STACK ; // Attempt to treat the properties string as a pointer to an XML configuration. XmlConfigurator configurator = null ; checkForNullConfiguration ( properties ) ; configurator = getXmlConfigurator ( properties ) ; if ( configurator != null ) // did the properties string point to a JGroups XML configuration ? return configurator ; throw new IllegalStateException ( String . format ( "configuration %s not found or invalid" , properties ) ) ; }
Returns a protocol stack configurator based on the provided properties string .
141
14
28,992
public static InputStream getConfigStream ( String properties ) throws IOException { InputStream configStream = null ; // Check to see if the properties string is the name of a file. try { configStream = new FileInputStream ( properties ) ; } catch ( FileNotFoundException | AccessControlException fnfe ) { // the properties string is likely not a file } // Check to see if the properties string is a URL. if ( configStream == null ) { try { configStream = new URL ( properties ) . openStream ( ) ; } catch ( MalformedURLException mre ) { // the properties string is not a URL } } // Check to see if the properties string is the name of a resource, e.g. udp.xml. if ( configStream == null && properties . endsWith ( "xml" ) ) configStream = Util . getResourceAsStream ( properties , ConfiguratorFactory . class ) ; return configStream ; }
Returns a JGroups XML configuration InputStream based on the provided properties string .
201
16
28,993
static void checkJAXPAvailability ( ) { try { XmlConfigurator . class . getName ( ) ; } catch ( NoClassDefFoundError error ) { Error tmp = new NoClassDefFoundError ( JAXP_MISSING_ERROR_MSG ) ; tmp . initCause ( error ) ; throw tmp ; } }
Checks the availability of the JAXP classes on the classpath .
74
15
28,994
public T getValue ( Object key ) { Rsp < T > rsp = get ( key ) ; return rsp != null ? rsp . getValue ( ) : null ; }
Returns the value associated with address key
39
7
28,995
public T getFirst ( ) { Optional < Rsp < T >> retval = values ( ) . stream ( ) . filter ( rsp -> rsp . getValue ( ) != null ) . findFirst ( ) ; return retval . isPresent ( ) ? retval . get ( ) . getValue ( ) : null ; }
Returns the first value in the response set . This is random but we try to return a non - null value first
70
23
28,996
public List < T > getResults ( ) { return values ( ) . stream ( ) . filter ( rsp -> rsp . wasReceived ( ) && rsp . getValue ( ) != null ) . collect ( ( ) -> new ArrayList <> ( size ( ) ) , ( list , rsp ) -> list . add ( rsp . getValue ( ) ) , ( l , r ) -> { } ) ; }
Returns the results from non - suspected members that are not null .
91
13
28,997
public void renameThread ( String base_name , Thread thread , String addr , String cluster_name ) { String thread_name = getThreadName ( base_name , thread , addr , cluster_name ) ; if ( thread_name != null ) thread . setName ( thread_name ) ; }
Names a thread according to base_name cluster name and local address . If includeClusterName and includeLocalAddress are null but cluster_name is set then we assume we have a shared transport and name the thread shared = clusterName . In the latter case clusterName points to the singleton_name of TP .
63
64
28,998
public RingBuffer < T > put ( T element ) throws InterruptedException { if ( element == null ) return this ; lock . lock ( ) ; try { while ( count == buf . length ) not_full . await ( ) ; buf [ wi ] = element ; if ( ++ wi == buf . length ) wi = 0 ; count ++ ; not_empty . signal ( ) ; return this ; } finally { lock . unlock ( ) ; } }
Tries to add a new element at the current write index and advances the write index . If the write index is at the same position as the read index this will block until the read index is advanced .
94
41
28,999
public int drainTo ( T [ ] c ) { int num = Math . min ( count , c . length ) ; // count may increase in the mean time, but that's ok if ( num == 0 ) return num ; int read_index = ri ; // no lock as we're the only reader for ( int i = 0 ; i < num ; i ++ ) { int real_index = realIndex ( read_index + i ) ; c [ i ] = ( buf [ real_index ] ) ; buf [ real_index ] = null ; } publishReadIndex ( num ) ; return num ; }
Removes messages and adds them to c .
129
9