Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.apache.catalina.tribes.membership;
 
 
 import java.util.Map;
 
A membership implementation using simple multicast. This is the representation of a multicast membership. This class is responsible for maintaining a list of active cluster nodes in the cluster. If a node fails to send out a heartbeat, the node will be dismissed.

Author(s):
Peter Rossbach
 
 public class Membership implements Cloneable {
 
     protected static final Member[] EMPTY_MEMBERS = new Member[0];
 
     private final Object membersLock = new Object();

    
The name of this membership, has to be the same as the name for the local member
 
     protected final Member local;

    
A map of all the members in the cluster.
 
     protected HashMap<MemberMbrEntrymap = new HashMap<>();

    
A list of all the members in the cluster.
 
     protected Member[] members = ;

    
sort members by alive time
 
     protected final Comparator<MembermemberComparator;
 
     @Override
     public Object clone() {
         synchronized () {
             Membership clone = new Membership();
             @SuppressWarnings("unchecked")
             final HashMap<MemberMbrEntrytmpclone = (HashMap<MemberMbrEntry>) .clone();
             clone.map = tmpclone;
             clone.members = new Member[.];
             System.arraycopy(,0,clone.members,0,.);
             return clone;
         }
     }

    
Constructs a new membership

Parameters:
local - has to be the name of the local member. Used to filter the local member from the cluster membership
includeLocal - TBA
 
     public Membership(Member localboolean includeLocal) {
         this(localnew MemberComparator(), includeLocal);
     }
 
     public Membership(Member local) {
         this(localfalse);
     }
 
     public Membership(Member localComparator<Membercomp) {
         this(localcompfalse);
     }
 
     public Membership(Member localComparator<Membercompboolean includeLocal) {
         this. = local;
         if ( includeLocal ) addMember(local);
         this. = comp;
    }
    
Reset the membership and start over fresh. Ie, delete all the members and wait for them to ping again and join this membership
    public synchronized void reset() {
        .clear();
         =  ;
    }

    
Notify the membership that this member has announced itself.

Parameters:
member - the member that just pinged us
Returns:
- true if this member is new to the cluster, false otherwise.
- false if this member is the local member or updated.
    public synchronized boolean memberAlive(Member member) {
        boolean result = false;
        //ignore ourselves
        if (  member.equals() ) return result;
        //return true if the membership has changed
        MbrEntry entry = .get(member);
        if ( entry == null ) {
            entry = addMember(member);
            result = true;
       } else {
            //update the member alive time
            Member updateMember = entry.getMember() ;
            if(updateMember.getMemberAliveTime() != member.getMemberAliveTime()) {
                //update fields that can change
                updateMember.setMemberAliveTime(member.getMemberAliveTime());
                updateMember.setPayload(member.getPayload());
                updateMember.setCommand(member.getCommand());
                Arrays.sort();
            }
        }
        entry.accessed();
        return result;
    }

    
Add a member to this component and sort array with memberComparator

Parameters:
member The member to add
    public synchronized MbrEntry addMember(Member member) {
      synchronized () {
          MbrEntry entry = new MbrEntry(member);
          if (!.containsKey(member) ) {
              .put(memberentry);
              Member results[] = new Member[. + 1];
              for (int i = 0; i < .i++) results[i] = [i];
              results[.] = member;
               = results;
              Arrays.sort();
          }
          return entry;
      }
    }

    
Remove a member from this component.

Parameters:
member The member to remove
    public void removeMember(Member member) {
        .remove(member);
        synchronized () {
            int n = -1;
            for (int i = 0; i < .i++) {
                if ([i] == member || [i].equals(member)) {
                    n = i;
                    break;
                }
            }
            if (n < 0) return;
            Member results[] = new Member[. - 1];
            int j = 0;
            for (int i = 0; i < .i++) {
                if (i != n)
                    results[j++] = [i];
            }
             = results;
        }
    }

    
Runs a refresh cycle and returns a list of members that has expired. This also removes the members from the membership, in such a way that getMembers() = getMembers() - expire()

Parameters:
maxtime - the max time a member can remain unannounced before it is considered dead.
Returns:
the list of expired members
    public synchronized Member[] expire(long maxtime) {
        if(!hasMembers() )
           return ;
        ArrayList<Memberlist = null;
        Iterator<MbrEntryi = .values().iterator();
        while(i.hasNext()) {
            MbrEntry entry = i.next();
            ifentry.hasExpired(maxtime) ) {
                if(list == null// only need a list when members are expired (smaller gc)
                    list = new java.util.ArrayList<>();
                list.add(entry.getMember());
            }
        }
        if(list != null) {
            Member[] result = new Member[list.size()];
            list.toArray(result);
            forint j=0; j<result.lengthj++) {
                removeMember(result[j]);
            }
            return result;
        } else {
            return  ;
        }
    }

    
Returning that service has members or not
    public boolean hasMembers() {
        return . > 0 ;
    }
    public Member getMember(Member mbr) {
        if(hasMembers()) {
            Member result = null;
            for ( int i=0; i<this..length && result==nulli++ ) {
                if ( [i].equals(mbr) ) result = [i];
            }//for
            return result;
        } else {
            return null;
        }
    }
    public boolean contains(Member mbr) {
        return getMember(mbr)!=null;
    }

    
Returning a list of all the members in the membership We not need a copy: add and remove generate new arrays.
    public Member[] getMembers() {
        if(hasMembers()) {
            return ;
        } else {
            return ;
        }
    }

    
get a copy from all member entries
    protected synchronized MbrEntry[] getMemberEntries()
    {
        MbrEntry[] result = new MbrEntry[.size()];
        Iterator<Map.Entry<Member,MbrEntry>> i = .entrySet().iterator();
        int pos = 0;
        while ( i.hasNext() )
            result[pos++] = i.next().getValue();
        return result;
    }
    // --------------------------------------------- Inner Class
    private static class MemberComparator implements Comparator<Member>,
            Serializable {
        private static final long serialVersionUID = 1L;
        @Override
        public int compare(Member m1Member m2) {
            //longer alive time, means sort first
            long result = m2.getMemberAliveTime() - m1.getMemberAliveTime();
            if (result < 0)
                return -1;
            else if (result == 0)
                return 0;
            else
                return 1;
        }
    }

    
Inner class that represents a member entry
    protected static class MbrEntry {
        protected final Member mbr;
        protected long lastHeardFrom;
        public MbrEntry(Member mbr) {
           this. = mbr;
        }

        
Indicate that this member has been accessed.
        public void accessed(){
            = System.currentTimeMillis();
        }

        
Return the actual Member object
        public Member getMember() {
            return ;
        }

        
Check if this dude has expired

Parameters:
maxtime The time threshold
        public boolean hasExpired(long maxtime) {
            long delta = System.currentTimeMillis() - ;
            return delta > maxtime;
        }
    }
New to GrepCode? Check out our FAQ X