idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
29,000
public int waitForMessages ( int num_spins , final BiConsumer < Integer , Integer > wait_strategy ) throws InterruptedException { // try spinning first (experimental) for ( int i = 0 ; i < num_spins && count == 0 ; i ++ ) { if ( wait_strategy != null ) wait_strategy . accept ( i , num_spins ) ; else Thread . yield ( ) ; } if ( count == 0 ) _waitForMessages ( ) ; return count ; // whatever is the last count; could have been updated since lock release }
Blocks until messages are available
125
5
29,001
public ByteBuffer readLengthAndData ( SocketChannel ch ) throws Exception { if ( bufs [ 0 ] . hasRemaining ( ) && ch . read ( bufs [ 0 ] ) < 0 ) throw new EOFException ( ) ; if ( bufs [ 0 ] . hasRemaining ( ) ) return null ; int len = bufs [ 0 ] . getInt ( 0 ) ; if ( bufs [ 1 ] == null || len > bufs [ 1 ] . capacity ( ) ) bufs [ 1 ] = ByteBuffer . allocate ( len ) ; bufs [ 1 ] . limit ( len ) ; if ( bufs [ 1 ] . hasRemaining ( ) && ch . read ( bufs [ 1 ] ) < 0 ) throw new EOFException ( ) ; if ( bufs [ 1 ] . hasRemaining ( ) ) return null ; try { return ( ByteBuffer ) bufs [ 1 ] . duplicate ( ) . flip ( ) ; } finally { bufs [ 0 ] . clear ( ) ; bufs [ 1 ] . clear ( ) ; } }
Reads length and then length bytes into the data buffer which is grown if needed .
227
17
29,002
public Buffers copy ( ) { for ( int i = Math . max ( position , next_to_copy ) ; i < limit ; i ++ ) { this . bufs [ i ] = copyBuffer ( this . bufs [ i ] ) ; next_to_copy = ( short ) ( i + 1 ) ; } return this ; }
Copies the data that has not yet been written and moves last_copied . Typically done after an unsuccessful write if copying is required . This is typically needed if the output buffer is reused . Note that direct buffers will be converted to heap - based buffers
73
51
29,003
public static ByteBuffer copyBuffer ( final ByteBuffer buf ) { if ( buf == null ) return null ; int offset = buf . hasArray ( ) ? buf . arrayOffset ( ) + buf . position ( ) : buf . position ( ) , len = buf . remaining ( ) ; byte [ ] tmp = new byte [ len ] ; if ( ! buf . isDirect ( ) ) System . arraycopy ( buf . array ( ) , offset , tmp , 0 , len ) ; else { // buf.get(tmp, 0, len); for ( int i = 0 ; i < len ; i ++ ) tmp [ i ] = buf . get ( i + offset ) ; } return ByteBuffer . wrap ( tmp ) ; }
Copies a ByteBuffer by copying and wrapping the underlying array of a heap - based buffer . Direct buffers are converted to heap - based buffers
152
28
29,004
@ GuardedBy ( "lock" ) protected void sendBundledMessages ( ) { for ( Map . Entry < Address , List < Message > > entry : msgs . entrySet ( ) ) { List < Message > list = entry . getValue ( ) ; if ( list . isEmpty ( ) ) continue ; output . position ( 0 ) ; if ( list . size ( ) == 1 ) sendSingleMessage ( list . get ( 0 ) ) ; else { Address dst = entry . getKey ( ) ; sendMessageList ( dst , list . get ( 0 ) . getSrc ( ) , list ) ; if ( transport . statsEnabled ( ) ) transport . incrBatchesSent ( 1 ) ; } } clearMessages ( ) ; count = 0 ; }
Sends all messages in the map . Messages for the same destination are bundled into a message list . The map will be cleared when done .
164
28
29,005
@ ManagedOperation public V get ( K key ) { // 1. Try the L1 cache first if ( l1_cache != null ) { V val = l1_cache . get ( key ) ; if ( val != null ) { if ( log . isTraceEnabled ( ) ) log . trace ( "returned value " + val + " for " + key + " from L1 cache" ) ; return val ; } } // 2. Try the local cache Cache . Value < Value < V > > val = l2_cache . getEntry ( key ) ; Value < V > tmp ; if ( val != null ) { tmp = val . getValue ( ) ; if ( tmp != null ) { V real_value = tmp . getVal ( ) ; if ( real_value != null && l1_cache != null && val . getTimeout ( ) >= 0 ) l1_cache . put ( key , real_value , val . getTimeout ( ) ) ; return tmp . getVal ( ) ; } } // 3. Execute a cluster wide GET try { RspList < Object > rsps = disp . callRemoteMethods ( null , new MethodCall ( GET , key ) , new RequestOptions ( ResponseMode . GET_ALL , call_timeout ) ) ; for ( Rsp rsp : rsps . values ( ) ) { Object obj = rsp . getValue ( ) ; if ( obj == null || obj instanceof Throwable ) continue ; val = ( Cache . Value < Value < V > > ) rsp . getValue ( ) ; if ( val != null ) { tmp = val . getValue ( ) ; if ( tmp != null ) { V real_value = tmp . getVal ( ) ; if ( real_value != null && l1_cache != null && val . getTimeout ( ) >= 0 ) l1_cache . put ( key , real_value , val . getTimeout ( ) ) ; return real_value ; } } } return null ; } catch ( Throwable t ) { if ( log . isWarnEnabled ( ) ) log . warn ( "get() failed" , t ) ; return null ; } }
Returns the value associated with key
461
6
29,006
@ ManagedOperation public void remove ( K key , boolean synchronous ) { try { disp . callRemoteMethods ( null , new MethodCall ( REMOVE , key ) , new RequestOptions ( synchronous ? ResponseMode . GET_ALL : ResponseMode . GET_NONE , call_timeout ) ) ; if ( l1_cache != null ) l1_cache . remove ( key ) ; } catch ( Throwable t ) { if ( log . isWarnEnabled ( ) ) log . warn ( "remove() failed" , t ) ; } }
Removes key in all nodes in the cluster both from their local hashmaps and L1 caches
118
19
29,007
@ ManagedOperation public void clear ( ) { Set < K > keys = new HashSet <> ( l2_cache . getInternalMap ( ) . keySet ( ) ) ; mcastClear ( keys , false ) ; }
Removes all keys and values in the L2 and L1 caches
49
14
29,008
protected boolean installViewIfValidJoinRsp ( final Promise < JoinRsp > join_promise , boolean block_for_rsp ) { boolean success = false ; JoinRsp rsp = null ; try { if ( join_promise . hasResult ( ) ) rsp = join_promise . getResult ( 1 , true ) ; else if ( block_for_rsp ) rsp = join_promise . getResult ( gms . join_timeout , true ) ; return success = rsp != null && isJoinResponseValid ( rsp ) && installView ( rsp . getView ( ) , rsp . getDigest ( ) ) ; } finally { if ( success ) gms . sendViewAck ( rsp . getView ( ) . getCreator ( ) ) ; } }
go through discovery and JOIN - REQ again in a next iteration
175
14
29,009
private static List < Address > getCoords ( Iterable < PingData > mbrs ) { if ( mbrs == null ) return null ; List < Address > coords = null ; for ( PingData mbr : mbrs ) { if ( mbr . isCoord ( ) ) { if ( coords == null ) coords = new ArrayList <> ( ) ; if ( ! coords . contains ( mbr . getAddress ( ) ) ) coords . add ( mbr . getAddress ( ) ) ; } } return coords ; }
Returns all members whose PingData is flagged as coordinator
121
10
29,010
public static Protocol createProtocol ( String prot_spec , ProtocolStack stack ) throws Exception { ProtocolConfiguration config ; Protocol prot ; if ( prot_spec == null ) throw new Exception ( "Configurator.createProtocol(): prot_spec is null" ) ; // parse the configuration for this protocol config = new ProtocolConfiguration ( prot_spec ) ; // create an instance of the protocol class and configure it prot = createLayer ( stack , config ) ; prot . init ( ) ; return prot ; }
Creates a new protocol given the protocol specification . Initializes the properties and starts the up and down handler threads .
104
23
29,011
public static Protocol connectProtocols ( List < Protocol > protocol_list ) throws Exception { Protocol current_layer = null , next_layer = null ; for ( int i = 0 ; i < protocol_list . size ( ) ; i ++ ) { current_layer = protocol_list . get ( i ) ; if ( i + 1 >= protocol_list . size ( ) ) break ; next_layer = protocol_list . get ( i + 1 ) ; next_layer . setDownProtocol ( current_layer ) ; current_layer . setUpProtocol ( next_layer ) ; } // basic protocol sanity check sanityCheck ( protocol_list ) ; return current_layer ; }
Creates a protocol stack by iterating through the protocol list and connecting adjacent layers . The list starts with the topmost layer and has the bottommost layer at the tail .
145
35
29,012
public static List < Protocol > createProtocols ( List < ProtocolConfiguration > protocol_configs , final ProtocolStack stack ) throws Exception { List < Protocol > retval = new LinkedList <> ( ) ; for ( int i = 0 ; i < protocol_configs . size ( ) ; i ++ ) { ProtocolConfiguration protocol_config = protocol_configs . get ( i ) ; Protocol layer = createLayer ( stack , protocol_config ) ; if ( layer == null ) return null ; retval . add ( layer ) ; } return retval ; }
Takes vector of ProtocolConfigurations iterates through it creates Protocol for each ProtocolConfiguration and returns all Protocols in a list .
119
26
29,013
public static void sanityCheck ( List < Protocol > protocols ) throws Exception { // check for unique IDs Set < Short > ids = new HashSet <> ( ) ; for ( Protocol protocol : protocols ) { short id = protocol . getId ( ) ; if ( id > 0 && ! ids . add ( id ) ) throw new Exception ( "Protocol ID " + id + " (name=" + protocol . getName ( ) + ") is duplicate; protocol IDs have to be unique" ) ; } // For each protocol, get its required up and down services and check (if available) if they're satisfied for ( Protocol protocol : protocols ) { List < Integer > required_down_services = protocol . requiredDownServices ( ) ; List < Integer > required_up_services = protocol . requiredUpServices ( ) ; if ( required_down_services != null && ! required_down_services . isEmpty ( ) ) { // the protocols below 'protocol' have to provide the services listed in required_down_services List < Integer > tmp = new ArrayList <> ( required_down_services ) ; removeProvidedUpServices ( protocol , tmp ) ; if ( ! tmp . isEmpty ( ) ) throw new Exception ( "events " + printEvents ( tmp ) + " are required by " + protocol . getName ( ) + ", but not provided by any of the protocols below it" ) ; } if ( required_up_services != null && ! required_up_services . isEmpty ( ) ) { // the protocols above 'protocol' have to provide the services listed in required_up_services List < Integer > tmp = new ArrayList <> ( required_up_services ) ; removeProvidedDownServices ( protocol , tmp ) ; if ( ! tmp . isEmpty ( ) ) throw new Exception ( "events " + printEvents ( tmp ) + " are required by " + protocol . getName ( ) + ", but not provided by any of the protocols above it" ) ; } } }
Throws an exception if sanity check fails . Possible sanity check is uniqueness of all protocol names
425
18
29,014
protected static void removeProvidedUpServices ( Protocol protocol , List < Integer > events ) { if ( protocol == null || events == null ) return ; for ( Protocol prot = protocol . getDownProtocol ( ) ; prot != null && ! events . isEmpty ( ) ; prot = prot . getDownProtocol ( ) ) { List < Integer > provided_up_services = prot . providedUpServices ( ) ; if ( provided_up_services != null && ! provided_up_services . isEmpty ( ) ) events . removeAll ( provided_up_services ) ; } }
Removes all events provided by the protocol below protocol from events
123
12
29,015
protected static void removeProvidedDownServices ( Protocol protocol , List < Integer > events ) { if ( protocol == null || events == null ) return ; for ( Protocol prot = protocol . getUpProtocol ( ) ; prot != null && ! events . isEmpty ( ) ; prot = prot . getUpProtocol ( ) ) { List < Integer > provided_down_services = prot . providedDownServices ( ) ; if ( provided_down_services != null && ! provided_down_services . isEmpty ( ) ) events . removeAll ( provided_down_services ) ; } }
Removes all events provided by the protocol above protocol from events
123
12
29,016
public static Collection < InetAddress > getAddresses ( Map < String , Map < String , InetAddressInfo > > inetAddressMap ) throws Exception { Set < InetAddress > addrs = new HashSet <> ( ) ; for ( Map . Entry < String , Map < String , InetAddressInfo > > inetAddressMapEntry : inetAddressMap . entrySet ( ) ) { Map < String , InetAddressInfo > protocolInetAddressMap = inetAddressMapEntry . getValue ( ) ; for ( Map . Entry < String , InetAddressInfo > protocolInetAddressMapEntry : protocolInetAddressMap . entrySet ( ) ) { InetAddressInfo inetAddressInfo = protocolInetAddressMapEntry . getValue ( ) ; // add InetAddressInfo to sets based on IP version List < InetAddress > addresses = inetAddressInfo . getInetAddresses ( ) ; for ( InetAddress address : addresses ) { if ( address == null ) throw new RuntimeException ( "failed converting address info to IP address: " + inetAddressInfo ) ; addrs . add ( address ) ; } } } return addrs ; }
Returns all inet addresses found
252
6
29,017
public static void ensureValidBindAddresses ( List < Protocol > protocols ) throws Exception { for ( Protocol protocol : protocols ) { String protocolName = protocol . getName ( ) ; //traverse class hierarchy and find all annotated fields and add them to the list if annotated Field [ ] fields = Util . getAllDeclaredFieldsWithAnnotations ( protocol . getClass ( ) , LocalAddress . class ) ; for ( int i = 0 ; i < fields . length ; i ++ ) { Object val = getValueFromProtocol ( protocol , fields [ i ] ) ; if ( val == null ) continue ; if ( ! ( val instanceof InetAddress ) ) throw new Exception ( "field " + protocolName + "." + fields [ i ] . getName ( ) + " is not an InetAddress" ) ; Util . checkIfValidAddress ( ( InetAddress ) val , protocolName ) ; } } }
Makes sure that all fields annotated with
198
9
29,018
static void addPropertyToDependencyList ( List < AccessibleObject > orderedList , Map < String , AccessibleObject > props , Stack < AccessibleObject > stack , AccessibleObject obj ) { if ( orderedList . contains ( obj ) ) return ; if ( stack . search ( obj ) > 0 ) { throw new RuntimeException ( "Deadlock in @Property dependency processing" ) ; } // record the fact that we are processing obj stack . push ( obj ) ; // process dependencies for this object before adding it to the list Property annotation = obj . getAnnotation ( Property . class ) ; String dependsClause = annotation . dependsUpon ( ) ; StringTokenizer st = new StringTokenizer ( dependsClause , "," ) ; while ( st . hasMoreTokens ( ) ) { String token = st . nextToken ( ) . trim ( ) ; AccessibleObject dep = props . get ( token ) ; // if null, throw exception addPropertyToDependencyList ( orderedList , props , stack , dep ) ; } // indicate we're done with processing dependencies stack . pop ( ) ; // we can now add in dependency order orderedList . add ( obj ) ; }
DFS of dependency graph formed by Property annotations and dependsUpon parameter This is used to create a list of Properties in dependency order
249
25
29,019
public int length ( ) { if ( keys == null ) return 0 ; int retval = 0 ; for ( byte [ ] key : keys ) if ( key != null ) retval ++ ; return retval ; }
The number of non - null keys
45
7
29,020
protected void resize ( int new_length ) { if ( keys == null ) { keys = new byte [ Math . min ( new_length , 0xff ) ] [ ] ; values = new byte [ Math . min ( new_length , 0xff ) ] [ ] ; return ; } if ( new_length > 0xff ) { if ( keys . length < 0xff ) new_length = 0xff ; else throw new ArrayIndexOutOfBoundsException ( "the hashmap cannot exceed " + 0xff + " entries" ) ; } keys = Arrays . copyOf ( keys , new_length ) ; values = Arrays . copyOf ( values , new_length ) ; }
Resizes the arrays
145
4
29,021
public static Map < String , List < ProtocolConfiguration > > parse ( InputStream input ) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setValidating ( false ) ; // for now DocumentBuilder builder = factory . newDocumentBuilder ( ) ; Document document = builder . parse ( input ) ; Element root = document . getDocumentElement ( ) ; return parse ( root ) ; }
Parses the input and returns a map of fork - stack IDs and lists of ProtocolConfigurations
87
20
29,022
public static void writeInt ( int num , ByteBuffer buf ) { if ( num == 0 ) { buf . put ( ( byte ) 0 ) ; return ; } final byte bytes_needed = bytesRequiredFor ( num ) ; buf . put ( bytes_needed ) ; for ( int i = 0 ; i < bytes_needed ; i ++ ) buf . put ( getByteAt ( num , i ) ) ; }
Writes an int to a ByteBuffer
87
8
29,023
public static void writeInt ( int num , DataOutput out ) throws IOException { if ( num == 0 ) { out . write ( 0 ) ; return ; } final byte bytes_needed = bytesRequiredFor ( num ) ; out . write ( bytes_needed ) ; for ( int i = 0 ; i < bytes_needed ; i ++ ) out . write ( getByteAt ( num , i ) ) ; }
Writes an int to an output stream
87
8
29,024
public static int readInt ( ByteBuffer buf ) { byte len = buf . get ( ) ; if ( len == 0 ) return 0 ; return makeInt ( buf , len ) ; }
Reads an int from a buffer .
39
8
29,025
public static int readInt ( DataInput in ) throws IOException { byte len = in . readByte ( ) ; if ( len == 0 ) return 0 ; return makeInt ( in , len ) ; }
Reads an int from an input stream
43
8
29,026
public static long readLong ( ByteBuffer buf ) { byte len = buf . get ( ) ; if ( len == 0 ) return 0 ; return makeLong ( buf , len ) ; }
Reads a long from a buffer .
39
8
29,027
public static void writeFloat ( float num , DataOutput out ) throws IOException { writeInt ( Float . floatToIntBits ( num ) , out ) ; }
Writes a float to an output stream
35
8
29,028
public static void writeDouble ( double num , DataOutput out ) throws IOException { writeLong ( Double . doubleToLongBits ( num ) , out ) ; }
Writes a double to an output stream
35
8
29,029
public static int size ( AsciiString str ) { return str == null ? Global . SHORT_SIZE : Global . SHORT_SIZE + str . length ( ) ; }
Measures the number of bytes required to encode an AsciiSring .
38
16
29,030
protected void removeAndDispatchNonBundledMessages ( MessageBatch oob_batch ) { if ( oob_batch == null ) return ; AsciiString tmp = oob_batch . clusterName ( ) ; byte [ ] cname = tmp != null ? tmp . chars ( ) : null ; for ( Iterator < Message > it = oob_batch . iterator ( ) ; it . hasNext ( ) ; ) { Message msg = it . next ( ) ; if ( msg . isFlagSet ( Message . Flag . DONT_BUNDLE ) && msg . isFlagSet ( Message . Flag . OOB ) ) { boolean internal = msg . isFlagSet ( Message . Flag . INTERNAL ) ; it . remove ( ) ; if ( tp . statsEnabled ( ) ) tp . getMessageStats ( ) . incrNumOOBMsgsReceived ( 1 ) ; tp . submitToThreadPool ( new SingleMessageHandlerWithClusterName ( msg , cname ) , internal ) ; } } }
Removes messages with flags DONT_BUNDLE and OOB set and executes them in the oob or internal thread pool . JGRP - 1737
223
34
29,031
public void waitFor ( Condition condition ) { boolean intr = false ; lock . lock ( ) ; try { while ( ! condition . isMet ( ) ) { try { cond . await ( ) ; } catch ( InterruptedException e ) { intr = true ; } } } finally { lock . unlock ( ) ; if ( intr ) Thread . currentThread ( ) . interrupt ( ) ; } }
Blocks until condition is true .
82
6
29,032
public boolean waitFor ( Condition condition , long timeout , TimeUnit unit ) { boolean intr = false ; final long timeout_ns = TimeUnit . NANOSECONDS . convert ( timeout , unit ) ; lock . lock ( ) ; try { for ( long wait_time = timeout_ns , start = System . nanoTime ( ) ; wait_time > 0 && ! condition . isMet ( ) ; ) { try { wait_time = cond . awaitNanos ( wait_time ) ; } catch ( InterruptedException e ) { wait_time = timeout_ns - ( System . nanoTime ( ) - start ) ; intr = true ; } } return condition . isMet ( ) ; } finally { lock . unlock ( ) ; if ( intr ) Thread . currentThread ( ) . interrupt ( ) ; } }
Blocks until condition is true or the time elapsed
173
9
29,033
void deliverSingleDestinationMessage ( Message msg , MessageID messageID ) { synchronized ( deliverySet ) { long sequenceNumber = sequenceNumberManager . get ( ) ; MessageInfo messageInfo = new MessageInfo ( messageID , msg , sequenceNumber ) ; messageInfo . updateAndMarkReadyToDeliver ( sequenceNumber ) ; deliverySet . add ( messageInfo ) ; notifyIfNeeded ( ) ; } }
delivers a message that has only as destination member this node
85
12
29,034
@ Override public List < Message > getNextMessagesToDeliver ( ) throws InterruptedException { LinkedList < Message > toDeliver = new LinkedList <> ( ) ; synchronized ( deliverySet ) { while ( deliverySet . isEmpty ( ) || ! deliverySet . first ( ) . isReadyToDeliver ( ) ) { deliverySet . wait ( ) ; } Iterator < MessageInfo > iterator = deliverySet . iterator ( ) ; while ( iterator . hasNext ( ) ) { MessageInfo messageInfo = iterator . next ( ) ; if ( messageInfo . isReadyToDeliver ( ) ) { toDeliver . add ( messageInfo . getMessage ( ) ) ; iterator . remove ( ) ; } else { break ; } } } return toDeliver ; }
see the interface javadoc
167
7
29,035
public boolean containsMember ( Address mbr ) { if ( mbr == null || members == null ) return false ; for ( Address member : members ) if ( Objects . equals ( member , mbr ) ) return true ; return false ; }
Returns true if this view contains a certain member
50
9
29,036
public boolean containsMembers ( Address ... mbrs ) { if ( mbrs == null || members == null ) return false ; for ( Address mbr : mbrs ) { if ( ! containsMember ( mbr ) ) return false ; } return true ; }
Returns true if all mbrs are elements of this view false otherwise
56
14
29,037
public static List < Address > leftMembers ( View one , View two ) { if ( one == null || two == null ) return null ; List < Address > retval = new ArrayList <> ( one . getMembers ( ) ) ; retval . removeAll ( two . getMembers ( ) ) ; return retval ; }
Returns a list of members which left from view one to two
69
12
29,038
public static Address [ ] [ ] diff ( final View from , final View to ) { if ( to == null ) throw new IllegalArgumentException ( "the second view cannot be null" ) ; if ( from == to ) return new Address [ ] [ ] { { } , { } } ; if ( from == null ) { Address [ ] joined = new Address [ to . size ( ) ] ; int index = 0 ; for ( Address addr : to . getMembers ( ) ) joined [ index ++ ] = addr ; return new Address [ ] [ ] { joined , { } } ; } Address [ ] joined = null , left = null ; int num_joiners = 0 , num_left = 0 ; // determine joiners for ( Address addr : to ) if ( ! from . containsMember ( addr ) ) num_joiners ++ ; if ( num_joiners > 0 ) { joined = new Address [ num_joiners ] ; int index = 0 ; for ( Address addr : to ) if ( ! from . containsMember ( addr ) ) joined [ index ++ ] = addr ; } // determine leavers for ( Address addr : from ) if ( ! to . containsMember ( addr ) ) num_left ++ ; if ( num_left > 0 ) { left = new Address [ num_left ] ; int index = 0 ; for ( Address addr : from ) if ( ! to . containsMember ( addr ) ) left [ index ++ ] = addr ; } return new Address [ ] [ ] { joined != null ? joined : new Address [ ] { } , left != null ? left : new Address [ ] { } } ; }
Returns the difference between 2 views from and to . It is assumed that view from is logically prior to view to .
344
23
29,039
public static boolean sameViews ( View ... views ) { ViewId first_view_id = views [ 0 ] . getViewId ( ) ; return Stream . of ( views ) . allMatch ( v -> v . getViewId ( ) . equals ( first_view_id ) ) ; }
Returns true if all views are the same . Uses the view IDs for comparison
63
15
29,040
public byte [ ] getBuffer ( ) { if ( buf == null ) return null ; if ( offset == 0 && length == buf . length ) return buf ; else { byte [ ] retval = new byte [ length ] ; System . arraycopy ( buf , offset , retval , 0 , length ) ; return retval ; } }
Returns a copy of the buffer if offset and length are used otherwise a reference .
70
16
29,041
public Message setFlag ( Flag ... flags ) { if ( flags != null ) { short tmp = this . flags ; for ( Flag flag : flags ) { if ( flag != null ) tmp |= flag . value ( ) ; } this . flags = tmp ; } return this ; }
Sets a number of flags in a message
59
9
29,042
public Message clearFlag ( Flag ... flags ) { if ( flags != null ) { short tmp = this . flags ; for ( Flag flag : flags ) if ( flag != null ) tmp &= ~ flag . value ( ) ; this . flags = tmp ; } return this ; }
Clears a number of flags in a message
58
9
29,043
public Message putHeader ( short id , Header hdr ) { if ( id < 0 ) throw new IllegalArgumentException ( "An ID of " + id + " is invalid" ) ; if ( hdr != null ) hdr . setProtId ( id ) ; synchronized ( this ) { Header [ ] resized_array = Headers . putHeader ( this . headers , id , hdr , true ) ; if ( resized_array != null ) this . headers = resized_array ; } return this ; }
Puts a header given an ID into the hashmap . Overwrites potential existing entry .
111
19
29,044
public < T extends Header > T getHeader ( short ... ids ) { if ( ids == null || ids . length == 0 ) return null ; return Headers . getHeader ( this . headers , ids ) ; }
Returns a header for a range of IDs or null if not found
49
13
29,045
public Message copy ( boolean copy_buffer , short starting_id , short ... copy_only_ids ) { Message retval = copy ( copy_buffer , false ) ; for ( Map . Entry < Short , Header > entry : getHeaders ( ) . entrySet ( ) ) { short id = entry . getKey ( ) ; if ( id >= starting_id || Util . containsId ( id , copy_only_ids ) ) retval . putHeader ( id , entry . getValue ( ) ) ; } return retval ; }
Copies a message . Copies only headers with IDs > = starting_id or IDs which are in the copy_only_ids list
115
28
29,046
@ Override public void writeTo ( DataOutput out ) throws IOException { byte leading = 0 ; if ( dest != null ) leading = Util . setFlag ( leading , DEST_SET ) ; if ( sender != null ) leading = Util . setFlag ( leading , SRC_SET ) ; if ( buf != null ) leading = Util . setFlag ( leading , BUF_SET ) ; // 1. write the leading byte first out . write ( leading ) ; // 2. the flags (e.g. OOB, LOW_PRIO), skip the transient flags out . writeShort ( flags ) ; // 3. dest_addr if ( dest != null ) Util . writeAddress ( dest , out ) ; // 4. src_addr if ( sender != null ) Util . writeAddress ( sender , out ) ; // 5. headers Header [ ] hdrs = this . headers ; int size = Headers . size ( hdrs ) ; out . writeShort ( size ) ; if ( size > 0 ) { for ( Header hdr : hdrs ) { if ( hdr == null ) break ; out . writeShort ( hdr . getProtId ( ) ) ; writeHeader ( hdr , out ) ; } } // 6. buf if ( buf != null ) { out . writeInt ( length ) ; out . write ( buf , offset , length ) ; } }
Writes the message to the output stream
299
8
29,047
public void writeToNoAddrs ( Address src , DataOutput out , short ... excluded_headers ) throws IOException { byte leading = 0 ; boolean write_src_addr = src == null || sender != null && ! sender . equals ( src ) ; if ( write_src_addr ) leading = Util . setFlag ( leading , SRC_SET ) ; if ( buf != null ) leading = Util . setFlag ( leading , BUF_SET ) ; // 1. write the leading byte first out . write ( leading ) ; // 2. the flags (e.g. OOB, LOW_PRIO) out . writeShort ( flags ) ; // 4. src_addr if ( write_src_addr ) Util . writeAddress ( sender , out ) ; // 5. headers Header [ ] hdrs = this . headers ; int size = Headers . size ( hdrs , excluded_headers ) ; out . writeShort ( size ) ; if ( size > 0 ) { for ( Header hdr : hdrs ) { if ( hdr == null ) break ; short id = hdr . getProtId ( ) ; if ( Util . containsId ( id , excluded_headers ) ) continue ; out . writeShort ( id ) ; writeHeader ( hdr , out ) ; } } // 6. buf if ( buf != null ) { out . writeInt ( length ) ; out . write ( buf , offset , length ) ; } }
Writes the message to the output stream but excludes the dest and src addresses unless the src address given as argument is different from the message s src address
312
30
29,048
@ Override public void readFrom ( DataInput in ) throws IOException , ClassNotFoundException { // 1. read the leading byte first byte leading = in . readByte ( ) ; // 2. the flags flags = in . readShort ( ) ; // 3. dest_addr if ( Util . isFlagSet ( leading , DEST_SET ) ) dest = Util . readAddress ( in ) ; // 4. src_addr if ( Util . isFlagSet ( leading , SRC_SET ) ) sender = Util . readAddress ( in ) ; // 5. headers int len = in . readShort ( ) ; this . headers = createHeaders ( len ) ; for ( int i = 0 ; i < len ; i ++ ) { short id = in . readShort ( ) ; Header hdr = readHeader ( in ) . setProtId ( id ) ; this . headers [ i ] = hdr ; } // 6. buf if ( Util . isFlagSet ( leading , BUF_SET ) ) { len = in . readInt ( ) ; buf = new byte [ len ] ; in . readFully ( buf , 0 , len ) ; length = len ; } }
Reads the message s contents from an input stream
257
10
29,049
public void forEach ( Consumer < RouterStub > action ) { stubs . stream ( ) . filter ( RouterStub :: isConnected ) . forEach ( action :: accept ) ; }
Applies action to all RouterStubs that are connected
41
11
29,050
public void forAny ( Consumer < RouterStub > action ) { while ( ! stubs . isEmpty ( ) ) { RouterStub stub = Util . pickRandomElement ( stubs ) ; if ( stub != null && stub . isConnected ( ) ) { action . accept ( stub ) ; return ; } } }
Applies action to a randomly picked RouterStub that s connected
69
13
29,051
public Element < T > get ( ) { // start at a random index, so different threads don't all start at index 0 and compete for the lock int starting_index = ( ( int ) ( Math . random ( ) * pool . length ) ) & ( pool . length - 1 ) ; for ( int i = 0 ; i < locks . length ; i ++ ) { int index = ( starting_index + i ) & ( pool . length - 1 ) ; Lock lock = locks [ index ] ; if ( lock . tryLock ( ) ) { if ( pool [ index ] != null ) return new Element <> ( pool [ index ] , lock ) ; return new Element <> ( pool [ index ] = creator . get ( ) , lock ) ; } } return new Element <> ( creator . get ( ) , null ) ; }
Gets the next available resource for which the lock can be acquired and returns it and its associated lock which needs to be released when the caller is done using the resource . If no resource in the pool can be locked returns a newly created resource and a null lock . This means that no lock was acquired and thus doesn t need to be released .
176
69
29,052
protected static String toLowerCase ( String input ) { if ( Character . isUpperCase ( input . charAt ( 0 ) ) ) return input . substring ( 0 , 1 ) . toLowerCase ( ) + input . substring ( 1 ) ; return input ; }
Returns a string with the first letter being lowercase
58
10
29,053
private void handleTmpView ( View v ) { Address new_coord = v . getCoord ( ) ; if ( new_coord != null && ! new_coord . equals ( coord ) && local_addr != null && local_addr . equals ( new_coord ) ) handleViewChange ( v ) ; }
an immediate change of view . See JGRP - 1452 .
67
14
29,054
private void integrate ( HashMap < String , Float > state ) { if ( state != null ) state . keySet ( ) . forEach ( key -> stocks . put ( key , state . get ( key ) ) ) ; }
default stack from JChannel
48
5
29,055
protected static void sanityCheck ( byte [ ] buf , int offset , int length ) { if ( buf == null ) throw new NullPointerException ( "buffer is null" ) ; if ( offset + length > buf . length ) throw new ArrayIndexOutOfBoundsException ( "length (" + length + ") + offset (" + offset + ") > buf.length (" + buf . length + ")" ) ; }
Verifies that length doesn t exceed a buffer s length
89
11
29,056
public void setCertificate ( ) throws KeyStoreException , IOException , NoSuchAlgorithmException , CertificateException , NoSuchPaddingException , InvalidKeyException , IllegalBlockSizeException , BadPaddingException , UnrecoverableEntryException { KeyStore store = KeyStore . getInstance ( this . keystore_type ) ; InputStream inputStream = Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( this . keystore_path ) ; if ( inputStream == null ) inputStream = new FileInputStream ( this . keystore_path ) ; store . load ( inputStream , this . keystore_password ) ; this . cipher = Cipher . getInstance ( this . cipher_type ) ; this . certificate = ( X509Certificate ) store . getCertificate ( this . cert_alias ) ; log . debug ( "certificate = " + this . certificate . toString ( ) ) ; this . cipher . init ( Cipher . ENCRYPT_MODE , this . certificate ) ; this . encryptedToken = this . cipher . doFinal ( this . auth_value . getBytes ( ) ) ; KeyStore . PrivateKeyEntry privateKey = ( KeyStore . PrivateKeyEntry ) store . getEntry ( this . cert_alias , new KeyStore . PasswordProtection ( this . cert_password ) ) ; this . certPrivateKey = privateKey . getPrivateKey ( ) ; this . valueSet = true ; }
Used during setup to get the certification from the keystore and encrypt the auth_value with the private key
309
21
29,057
public static < T extends Header > T getHeader ( final Header [ ] hdrs , short id ) { if ( hdrs == null ) return null ; for ( Header hdr : hdrs ) { if ( hdr == null ) return null ; if ( hdr . getProtId ( ) == id ) return ( T ) hdr ; } return null ; }
Returns the header associated with an ID
80
7
29,058
public static Header [ ] putHeader ( final Header [ ] headers , short id , Header hdr , boolean replace_if_present ) { int i = 0 ; Header [ ] hdrs = headers ; boolean resized = false ; while ( i < hdrs . length ) { if ( hdrs [ i ] == null ) { hdrs [ i ] = hdr ; return resized ? hdrs : null ; } short hdr_id = hdrs [ i ] . getProtId ( ) ; if ( hdr_id == id ) { if ( replace_if_present || hdrs [ i ] == null ) hdrs [ i ] = hdr ; return resized ? hdrs : null ; } i ++ ; if ( i >= hdrs . length ) { hdrs = resize ( hdrs ) ; resized = true ; } } throw new IllegalStateException ( "unable to add element " + id + ", index=" + i ) ; // we should never come here }
Adds hdr at the next available slot . If none is available the headers array passed in will be copied and the copy returned
222
25
29,059
public static Header [ ] resize ( final Header [ ] headers ) { int new_capacity = headers . length + RESIZE_INCR ; Header [ ] new_hdrs = new Header [ new_capacity ] ; System . arraycopy ( headers , 0 , new_hdrs , 0 , headers . length ) ; return new_hdrs ; }
Increases the capacity of the array and copies the contents of the old into the new array
73
17
29,060
protected static String print ( BiConsumer < Integer , Integer > wait_strategy ) { if ( wait_strategy == null ) return null ; if ( wait_strategy == SPIN ) return "spin" ; else if ( wait_strategy == YIELD ) return "yield" ; else if ( wait_strategy == PARK ) return "park" ; else if ( wait_strategy == SPIN_PARK ) return "spin-park" ; else if ( wait_strategy == SPIN_YIELD ) return "spin-yield" ; else return wait_strategy . getClass ( ) . getSimpleName ( ) ; }
fast equivalent to %
139
4
29,061
public void leave ( Address mbr ) { if ( mbr == null ) { if ( log . isErrorEnabled ( ) ) log . error ( Util . getMessage ( "MemberSAddressIsNull" ) ) ; return ; } ViewHandler < Request > vh = gms . getViewHandler ( ) ; vh . add ( new Request ( Request . COORD_LEAVE , mbr ) ) ; // https://issues.jboss.org/browse/JGRP-2293 // If we're the coord leaving, ignore gms.leave_timeout: https://issues.jboss.org/browse/JGRP-1509 long timeout = ( long ) ( Math . max ( gms . leave_timeout , gms . view_ack_collection_timeout ) * 1.5 ) ; vh . waitUntilComplete ( timeout ) ; }
The coordinator itself wants to leave the group
189
8
29,062
private Message unfragment ( Message msg , FragHeader hdr ) { Address sender = msg . getSrc ( ) ; FragmentationTable frag_table = fragment_list . get ( sender ) ; if ( frag_table == null ) { frag_table = new FragmentationTable ( sender ) ; try { fragment_list . add ( sender , frag_table ) ; } catch ( IllegalArgumentException x ) { // the entry has already been added, probably in parallel from another thread frag_table = fragment_list . get ( sender ) ; } } num_received_frags ++ ; byte [ ] buf = frag_table . add ( hdr . id , hdr . frag_id , hdr . num_frags , msg . getBuffer ( ) ) ; if ( buf == null ) return null ; try { DataInput in = new ByteArrayDataInputStream ( buf ) ; Message assembled_msg = new Message ( false ) ; assembled_msg . readFrom ( in ) ; assembled_msg . setSrc ( sender ) ; // needed ? YES, because fragments have a null src !! if ( log . isTraceEnabled ( ) ) log . trace ( "assembled_msg is " + assembled_msg ) ; num_received_msgs ++ ; return assembled_msg ; } catch ( Exception e ) { log . error ( Util . getMessage ( "FailedUnfragmentingAMessage" ) , e ) ; return null ; } }
1 . Get all the fragment buffers 2 . When all are received - > Assemble them into one big buffer 3 . Read headers and byte buffer from big buffer 4 . Set headers and buffer in msg 5 . Pass msg up the stack
311
47
29,063
public boolean decrementIfEnoughCredits ( final Message msg , int credits , long timeout ) { lock . lock ( ) ; try { if ( queuing ) return addToQueue ( msg , credits ) ; if ( decrement ( credits ) ) return true ; // enough credits, message will be sent queuing = true ; // not enough credits, start queuing return addToQueue ( msg , credits ) ; } finally { lock . unlock ( ) ; } }
Decrements the sender s credits by the size of the message .
95
13
29,064
public static void add ( short magic , Class clazz ) { if ( magic < MIN_CUSTOM_MAGIC_NUMBER ) throw new IllegalArgumentException ( "magic ID (" + magic + ") must be >= " + MIN_CUSTOM_MAGIC_NUMBER ) ; if ( magicMapUser . containsKey ( magic ) || classMap . containsKey ( clazz ) ) alreadyInMagicMap ( magic , clazz . getName ( ) ) ; Object inst = null ; try { inst = clazz . getDeclaredConstructor ( ) . newInstance ( ) ; } catch ( Exception e ) { throw new IllegalStateException ( "failed creating instance " + clazz , e ) ; } Object val = clazz ; if ( Header . class . isAssignableFrom ( clazz ) ) { // class is a header checkSameId ( ( Header ) inst , magic ) ; val = ( ( Header ) inst ) . create ( ) ; } if ( Constructable . class . isAssignableFrom ( clazz ) ) { val = ( ( Constructable ) inst ) . create ( ) ; inst = ( ( Supplier < ? > ) val ) . get ( ) ; if ( ! inst . getClass ( ) . equals ( clazz ) ) throw new IllegalStateException ( String . format ( "%s.create() returned the wrong class: %s\n" , clazz . getSimpleName ( ) , inst . getClass ( ) . getSimpleName ( ) ) ) ; } magicMapUser . put ( magic , val ) ; classMap . put ( clazz , magic ) ; }
Method to register a user - defined header with jg - magic - map at runtime
345
17
29,065
public static Class get ( String clazzname , ClassLoader loader ) throws ClassNotFoundException { return Util . loadClass ( clazzname , loader != null ? loader : ClassConfigurator . class . getClassLoader ( ) ) ; }
Loads and returns the class from the class name
52
10
29,066
public static short getMagicNumber ( Class clazz ) { Short i = classMap . get ( clazz ) ; if ( i == null ) return - 1 ; else return i ; }
Returns the magic number for the class .
39
8
29,067
public void merge ( Map < Address , View > views ) { if ( views == null || views . isEmpty ( ) ) { log . warn ( "the views passed with the MERGE event were empty (or null); ignoring MERGE event" ) ; return ; } if ( View . sameViews ( views . values ( ) ) ) { log . debug ( "MERGE event is ignored because of identical views: %s" , Util . printListWithDelimiter ( views . values ( ) , ", " ) ) ; return ; } if ( isMergeInProgress ( ) ) { log . trace ( "%s: merge is already running (merge_id=%s)" , gms . local_addr , merge_id ) ; return ; } Address merge_leader = determineMergeLeader ( views ) ; if ( merge_leader == null ) return ; if ( merge_leader . equals ( gms . local_addr ) ) { log . debug ( "%s: I will be the merge leader. Starting the merge task. Views: %s" , gms . local_addr , views ) ; merge_task . start ( views ) ; } else log . trace ( "%s: I'm not the merge leader, waiting for merge leader (%s) to start merge" , gms . local_addr , merge_leader ) ; }
Invoked upon receiving a MERGE event from the MERGE layer . Starts the merge protocol . See description of protocol in DESIGN .
287
27
29,068
protected Address determineMergeLeader ( Map < Address , View > views ) { // we need the merge *coordinators* not merge participants because not everyone can lead a merge ! Collection < Address > coords = Util . determineActualMergeCoords ( views ) ; if ( coords . isEmpty ( ) ) coords = Util . determineMergeCoords ( views ) ; // https://issues.jboss.org/browse/JGRP-2092 if ( coords . isEmpty ( ) ) { log . error ( "%s: unable to determine merge leader from %s; not starting a merge" , gms . local_addr , views ) ; return null ; } return new Membership ( coords ) . sort ( ) . elementAt ( 0 ) ; // establish a deterministic order, so that coords can elect leader }
Returns the address of the merge leader
181
7
29,069
protected void sendMergeResponse ( Address sender , View view , Digest digest , MergeId merge_id ) { Message msg = new Message ( sender ) . setBuffer ( GMS . marshal ( view , digest ) ) . setFlag ( Message . Flag . OOB , Message . Flag . INTERNAL ) . putHeader ( gms . getId ( ) , new GMS . GmsHeader ( GMS . GmsHeader . MERGE_RSP ) . mergeId ( merge_id ) ) ; gms . getDownProtocol ( ) . down ( msg ) ; }
Send back a response containing view and digest to sender
124
10
29,070
protected void sendMergeView ( Collection < Address > coords , MergeData combined_merge_data , MergeId merge_id ) { if ( coords == null || coords . isEmpty ( ) || combined_merge_data == null ) return ; View view = combined_merge_data . view ; Digest digest = combined_merge_data . digest ; if ( view == null || digest == null ) { log . error ( Util . getMessage ( "ViewOrDigestIsNullCannotSendConsolidatedMergeView/Digest" ) ) ; return ; } int size = 0 ; if ( gms . flushProtocolInStack ) { gms . merge_ack_collector . reset ( coords ) ; size = gms . merge_ack_collector . size ( ) ; } Event install_merge_view_evt = new Event ( Event . INSTALL_MERGE_VIEW , view ) ; gms . getUpProtocol ( ) . up ( install_merge_view_evt ) ; gms . getDownProtocol ( ) . down ( install_merge_view_evt ) ; long start = System . currentTimeMillis ( ) ; for ( Address coord : coords ) { Message msg = new Message ( coord ) . setBuffer ( GMS . marshal ( view , digest ) ) . putHeader ( gms . getId ( ) , new GMS . GmsHeader ( GMS . GmsHeader . INSTALL_MERGE_VIEW ) . mergeId ( merge_id ) ) ; gms . getDownProtocol ( ) . down ( msg ) ; } //[JGRP-700] - FLUSH: flushing should span merge; if flush is in stack, wait for acks from subview coordinators if ( gms . flushProtocolInStack ) { try { gms . merge_ack_collector . waitForAllAcks ( gms . view_ack_collection_timeout ) ; log . trace ( "%s: received all ACKs (%d) for merge view %s in %d ms" , gms . local_addr , size , view , ( System . currentTimeMillis ( ) - start ) ) ; } catch ( TimeoutException e ) { log . warn ( "%s: failed to collect all ACKs (%d) for merge view %s after %d ms, missing ACKs from %s" , gms . local_addr , size , view , gms . view_ack_collection_timeout , gms . merge_ack_collector . printMissing ( ) ) ; } } }
Sends the new view and digest to all subgroup coordinators . Each coord will in turn broadcast the new view and digest to all the members of its subgroup
566
33
29,071
protected void fixDigests ( ) { Digest digest = fetchDigestsFromAllMembersInSubPartition ( gms . view , null ) ; Message msg = new Message ( ) . putHeader ( gms . getId ( ) , new GMS . GmsHeader ( GMS . GmsHeader . INSTALL_DIGEST ) ) . setBuffer ( GMS . marshal ( null , digest ) ) ; gms . getDownProtocol ( ) . down ( msg ) ; }
Fetches the digests from all members and installs them again . Used only for diagnosis and support ; don t use this otherwise !
104
27
29,072
public boolean allSet ( ) { for ( int i = 0 ; i < seqnos . length ; i += 2 ) if ( seqnos [ i ] == - 1 ) return false ; return true ; }
Returns true if all members have a corresponding seqno > = 0 else false
43
15
29,073
public Address [ ] getNonSetMembers ( ) { Address [ ] retval = new Address [ countNonSetMembers ( ) ] ; if ( retval . length == 0 ) return retval ; int index = 0 ; for ( int i = 0 ; i < members . length ; i ++ ) if ( seqnos [ i * 2 ] == - 1 ) retval [ index ++ ] = members [ i ] ; return retval ; }
Returns an array of members whose seqno is not set . Returns an empty array if all are set .
92
21
29,074
public long add ( T element ) { lock . lock ( ) ; try { long next = high + 1 ; if ( next - low > capacity ( ) ) _grow ( next - low ) ; int high_index = index ( high ) ; buffer [ high_index ] = element ; return high ++ ; } finally { lock . unlock ( ) ; } }
Adds a new element and returns the sequence number at which it was inserted . Advances the high pointer and grows the buffer if needed .
75
27
29,075
public T remove ( long seqno ) { lock . lock ( ) ; try { if ( seqno < low || seqno > high ) return null ; int index = index ( seqno ) ; T retval = buffer [ index ] ; if ( retval != null && removes_till_compaction > 0 ) num_removes ++ ; buffer [ index ] = null ; if ( seqno == low ) advanceLow ( ) ; if ( removes_till_compaction > 0 && num_removes >= removes_till_compaction ) { _compact ( ) ; num_removes = 0 ; } return retval ; } finally { lock . unlock ( ) ; } }
Removes the element at the index matching seqno . If seqno == low tries to advance low until a non - null element is encountered up to high
147
31
29,076
public RequestTable < T > grow ( int new_capacity ) { lock . lock ( ) ; try { _grow ( new_capacity ) ; return this ; } finally { lock . unlock ( ) ; } }
Grows the array to at least new_capacity . This method is mainly used for testing and is not typically called directly but indirectly when adding elements and the underlying array has no space left .
44
38
29,077
@ GuardedBy ( "lock" ) protected boolean _compact ( ) { int new_cap = buffer . length >> 1 ; // needs to be a power of 2 for efficient modulo operation, e.g. for index() // boolean compactable=this.buffer.length > 0 && (size() <= new_cap || (contiguousSpaceAvailable=_contiguousSpaceAvailable(new_cap))); boolean compactable = this . buffer . length > 0 && high - low <= new_cap ; if ( ! compactable ) return false ; // not enough space to shrink the buffer to half its size _copy ( new_cap ) ; return true ; }
Shrinks the array to half of its current size if the current number of elements fit into half of the capacity .
140
24
29,078
protected void _copy ( int new_cap ) { // copy elements from [low to high-1] into new indices in new array T [ ] new_buf = ( T [ ] ) new Object [ new_cap ] ; int new_len = new_buf . length ; int old_len = this . buffer . length ; for ( long i = low , num_iterations = 0 ; i < high && num_iterations < old_len ; i ++ , num_iterations ++ ) { int old_index = index ( i , old_len ) ; if ( this . buffer [ old_index ] != null ) { int new_index = index ( i , new_len ) ; new_buf [ new_index ] = this . buffer [ old_index ] ; } } this . buffer = new_buf ; }
Copies elements from old into new array
178
8
29,079
public T remove ( ) { lock . lock ( ) ; try { if ( queue . isEmpty ( ) ) return null ; El < T > el = queue . poll ( ) ; count -= el . size ; not_full . signalAll ( ) ; return el . el ; } finally { lock . unlock ( ) ; } }
Removes and returns the first element or null if the queue is empty
69
14
29,080
public void addNewMessageToSend ( MessageID messageID , Collection < Address > destinations , long initialSequenceNumber , boolean deliverToMyself ) { MessageInfo messageInfo = new MessageInfo ( destinations , initialSequenceNumber , deliverToMyself ) ; if ( deliverToMyself ) { messageInfo . setProposeReceived ( messageID . getAddress ( ) ) ; } sentMessages . put ( messageID , messageInfo ) ; }
Add a new message sent
95
5
29,081
public long addPropose ( MessageID messageID , Address from , long sequenceNumber ) { MessageInfo messageInfo = sentMessages . get ( messageID ) ; if ( messageInfo != null && messageInfo . addPropose ( from , sequenceNumber ) ) { return messageInfo . getAndMarkFinalSent ( ) ; } return NOT_READY ; }
Add a propose from a member in destination set
75
9
29,082
public boolean markSent ( MessageID messageID ) { MessageInfo messageInfo = sentMessages . remove ( messageID ) ; return messageInfo != null && messageInfo . toSelfDeliver ; }
Mark the message as sent
41
5
29,083
public Set < Address > getDestination ( MessageID messageID ) { MessageInfo messageInfo = sentMessages . get ( messageID ) ; Set < Address > destination ; if ( messageInfo != null ) { destination = new HashSet <> ( messageInfo . destinations ) ; } else { destination = Collections . emptySet ( ) ; } return destination ; }
obtains the destination set of a message
75
8
29,084
public < T extends Average > T merge ( T other ) { if ( Util . productGreaterThan ( count , ( long ) Math . ceil ( avg ) , Long . MAX_VALUE ) || Util . productGreaterThan ( other . count ( ) , ( long ) Math . ceil ( other . average ( ) ) , Long . MAX_VALUE ) ) { // the above computation is not correct as the sum of the 2 products can still lead to overflow // a non-weighted avg avg = avg + other . average ( ) / 2.0 ; } else { // compute the new average weighted by count long total_count = count + other . count ( ) ; avg = ( count * avg + other . count ( ) * other . average ( ) ) / total_count ; count = total_count / 2 ; } return ( T ) this ; }
Merges this average with another one
186
7
29,085
public Collection < Range > getBits ( boolean value ) { int index = 0 ; int start_range = 0 , end_range = 0 ; int size = ( int ) ( ( high - low ) + 1 ) ; final Collection < Range > retval = new ArrayList <> ( size ) ; while ( index < size ) { start_range = value ? bits . nextSetBit ( index ) : bits . nextClearBit ( index ) ; if ( start_range < 0 || start_range >= size ) break ; end_range = value ? bits . nextClearBit ( start_range ) : bits . nextSetBit ( start_range ) ; if ( end_range < 0 || end_range >= size ) { retval . add ( new Range ( start_range + low , size - 1 + low ) ) ; break ; } retval . add ( new Range ( start_range + low , end_range - 1 + low ) ) ; index = end_range ; } return retval ; }
Returns ranges of all bit set to value
215
8
29,086
public void installRule ( String name , long interval , Rule rule ) { rule . supervisor ( this ) . log ( log ) . init ( ) ; Future < ? > future = timer . scheduleAtFixedRate ( rule , interval , interval , TimeUnit . MILLISECONDS ) ; Tuple < Rule , Future < ? > > existing = rules . put ( name != null ? name : rule . name ( ) , new Tuple <> ( rule , future ) ) ; if ( existing != null ) existing . getVal2 ( ) . cancel ( true ) ; }
Installs a new rule
120
5
29,087
protected void handleStateRsp ( final Digest digest , Address sender , byte [ ] state ) { try { if ( isDigestNeeded ( ) ) { punchHoleFor ( sender ) ; closeBarrierAndSuspendStable ( ) ; // fix for https://jira.jboss.org/jira/browse/JGRP-1013 if ( digest != null ) down_prot . down ( new Event ( Event . OVERWRITE_DIGEST , digest ) ) ; // set the digest (e.g. in NAKACK) } waiting_for_state_response = false ; stop = System . currentTimeMillis ( ) ; log . debug ( "%s: received state, size=%s, time=%d milliseconds" , local_addr , ( state == null ? "0" : Util . printBytes ( state . length ) ) , stop - start ) ; StateTransferResult result = new StateTransferResult ( state ) ; up_prot . up ( new Event ( Event . GET_STATE_OK , result ) ) ; down_prot . down ( new Event ( Event . GET_VIEW_FROM_COORD ) ) ; // https://issues.jboss.org/browse/JGRP-1751 } catch ( Throwable t ) { handleException ( t ) ; } finally { if ( isDigestNeeded ( ) ) { closeHoleFor ( sender ) ; openBarrierAndResumeStable ( ) ; } } }
Set the digest and the send the state up to the application
321
12
29,088
protected int advanceWriteIndex ( ) { int num = 0 , start = write_index ; for ( ; ; ) { if ( buf [ start ] == null ) break ; num ++ ; start = index ( start + 1 ) ; if ( start == tmp_write_index . get ( ) ) break ; } write_index = start ; return num ; }
Advance write_index up to tmp_write_index as long as no null msg is found
75
20
29,089
void drawEmptyBoard ( Graphics g ) { int x = x_offset , y = y_offset ; Color old_col = g . getColor ( ) ; g . setFont ( def_font2 ) ; old_col = g . getColor ( ) ; g . setColor ( checksum_col ) ; g . drawString ( ( "Checksum: " + checksum ) , x_offset + field_size , y_offset - 20 ) ; g . setFont ( def_font ) ; g . setColor ( old_col ) ; for ( int i = 0 ; i < num_fields ; i ++ ) { for ( int j = 0 ; j < num_fields ; j ++ ) { // draws 1 row g . drawRect ( x , y , field_size , field_size ) ; x += field_size ; } g . drawString ( ( String . valueOf ( ( num_fields - i - 1 ) ) ) , x + 20 , y + field_size / 2 ) ; y += field_size ; x = x_offset ; } for ( int i = 0 ; i < num_fields ; i ++ ) { g . drawString ( ( String . valueOf ( i ) ) , x_offset + i * field_size + field_size / 2 , y + 30 ) ; } }
Draws the empty board no pieces on it yet just grid lines
286
13
29,090
private void onSuspend ( final List < Address > members ) { Message msg = null ; Collection < Address > participantsInFlush = null ; synchronized ( sharedLock ) { flushCoordinator = localAddress ; // start FLUSH only on group members that we need to flush participantsInFlush = members ; participantsInFlush . retainAll ( currentView . getMembers ( ) ) ; flushMembers . clear ( ) ; flushMembers . addAll ( participantsInFlush ) ; flushMembers . removeAll ( suspected ) ; msg = new Message ( null ) . src ( localAddress ) . setBuffer ( marshal ( participantsInFlush , null ) ) . putHeader ( this . id , new FlushHeader ( FlushHeader . START_FLUSH , currentViewId ( ) ) ) ; } if ( participantsInFlush . isEmpty ( ) ) { flush_promise . setResult ( SUCCESS_START_FLUSH ) ; } else { down_prot . down ( msg ) ; if ( log . isDebugEnabled ( ) ) log . debug ( localAddress + ": flush coordinator " + " is starting FLUSH with participants " + participantsInFlush ) ; } }
Starts the flush protocol
253
5
29,091
protected static Digest maxSeqnos ( final View view , List < Digest > digests ) { if ( view == null || digests == null ) return null ; MutableDigest digest = new MutableDigest ( view . getMembersRaw ( ) ) ; digests . forEach ( digest :: merge ) ; return digest ; }
Returns a digest which contains for all members of view the highest delivered and received seqno of all digests
70
21
29,092
public List < Address > getNewMembership ( final Collection < Collection < Address > > subviews ) { ArrayList < Collection < Address >> aSubviews = new ArrayList <> ( subviews ) ; int sLargest = 0 ; int iLargest = 0 ; for ( int i = 0 ; i < aSubviews . size ( ) ; i ++ ) { int size = aSubviews . get ( i ) . size ( ) ; if ( size > sLargest ) { sLargest = size ; iLargest = i ; } } Membership mbrs = new Membership ( aSubviews . get ( iLargest ) ) ; for ( int i = 0 ; i < aSubviews . size ( ) ; i ++ ) if ( i != iLargest ) mbrs . add ( aSubviews . get ( i ) ) ; return mbrs . getMembers ( ) ; }
Called when a merge happened . The largest subview wins .
199
13
29,093
protected void sendLocalAddress ( Address local_addr ) throws Exception { try { // write the cookie out . write ( cookie , 0 , cookie . length ) ; // write the version out . writeShort ( Version . version ) ; out . writeShort ( local_addr . serializedSize ( ) ) ; // address size local_addr . writeTo ( out ) ; out . flush ( ) ; // needed ? updateLastAccessed ( ) ; } catch ( Exception ex ) { server . socket_factory . close ( this . sock ) ; connected = false ; throw ex ; } }
Send the cookie first then the our port number . If the cookie doesn t match the receiver s cookie the receiver will reject the connection and close it .
122
30
29,094
protected Address readPeerAddress ( Socket client_sock ) throws Exception { int timeout = client_sock . getSoTimeout ( ) ; client_sock . setSoTimeout ( server . peerAddressReadTimeout ( ) ) ; try { // read the cookie first byte [ ] input_cookie = new byte [ cookie . length ] ; in . readFully ( input_cookie , 0 , input_cookie . length ) ; if ( ! Arrays . equals ( cookie , input_cookie ) ) throw new SocketException ( String . format ( "%s: BaseServer.TcpConnection.readPeerAddress(): cookie sent by " + "%s:%d does not match own cookie; terminating connection" , server . localAddress ( ) , client_sock . getInetAddress ( ) , client_sock . getPort ( ) ) ) ; // then read the version short version = in . readShort ( ) ; if ( ! Version . isBinaryCompatible ( version ) ) throw new IOException ( "packet from " + client_sock . getInetAddress ( ) + ":" + client_sock . getPort ( ) + " has different version (" + Version . print ( version ) + ") from ours (" + Version . printVersion ( ) + "); discarding it" ) ; in . readShort ( ) ; // address length is only needed by NioConnection Address client_peer_addr = new IpAddress ( ) ; client_peer_addr . readFrom ( in ) ; updateLastAccessed ( ) ; return client_peer_addr ; } finally { client_sock . setSoTimeout ( timeout ) ; } }
Reads the peer s address . First a cookie has to be sent which has to match my own cookie otherwise the connection will be refused
353
27
29,095
public static void unregister ( MBeanServer server , String object_name ) throws Exception { Set < ObjectName > mbeans = server . queryNames ( new ObjectName ( object_name ) , null ) ; if ( mbeans != null ) for ( ObjectName name : mbeans ) server . unregisterMBean ( name ) ; }
Unregisters object_name and everything under it
73
10
29,096
public void send ( Address dst , byte [ ] buf , int offset , int length ) throws Exception { ch . send ( dst , buf , offset , length ) ; }
Sends a message to a destination .
35
8
29,097
public Object down ( Event evt ) { if ( evt . type ( ) == 1 ) // MSG return ch . down ( ( Message ) evt . getArg ( ) ) ; return ch . down ( evt ) ; }
Enables access to event mechanism of a channel and is normally not used by clients directly .
49
18
29,098
public Value putIfAbsent ( T key , long expiry_time ) { if ( key == null ) key = NULL_KEY ; Value val = map . get ( key ) ; if ( val == null ) { val = new Value ( ) ; Value existing = map . putIfAbsent ( key , val ) ; if ( existing == null ) return val ; val = existing ; } // key already exists if ( val . update ( ) . age ( ) > expiry_time ) { map . remove ( key ) ; map . putIfAbsent ( key , new Value ( ) ) ; return val ; } return null ; }
Adds a new key to the hashmap or updates the Value associated with the existing key if present . If expiry_time is greater than the age of the Value the key will be removed .
134
39
29,099
public int size ( ) { int count = 0 ; for ( Value val : map . values ( ) ) count += val . count ( ) ; return count ; }
Returns the total count of all values
34
7