1 package org.sapia.ubik.mcast; 2 3 import org.sapia.ubik.net.ServerAddress; 4 5 import java.util.*; 6 7 8 23 public class View { 24 private Map _addresses = new HashMap(); 25 private Map _nodeToAddr = new HashMap(); 26 private long _timeout; 27 28 31 public View(long timeout) { 32 _timeout = timeout; 33 } 34 35 40 public synchronized List getHosts() { 41 return new AddressList(_addresses.keySet()); 42 } 43 44 50 public ServerAddress getAddressFor(String node) { 51 NodeInfo info = (NodeInfo) _nodeToAddr.get(node); 52 53 return info.addr; 54 } 55 56 60 public void setTimeout(long timeout){ 61 _timeout = timeout; 62 } 63 64 71 void addHost(ServerAddress addr, String node) { 72 NodeInfo info = new NodeInfo(addr, node); 73 _nodeToAddr.put(node, info); 74 _addresses.put(info, new Long (System.currentTimeMillis())); 75 } 76 77 84 void heartbeat(ServerAddress addr, String node) { 85 _addresses.put(new NodeInfo(addr, node), 86 new Long (System.currentTimeMillis())); 87 } 88 89 92 void removeDeadHosts() { 93 Map.Entry entry; 94 Map.Entry[] hosts; 95 96 synchronized (_addresses) { 97 hosts = (Map.Entry[]) _addresses.entrySet().toArray(new Map.Entry[_addresses.size()]); 98 99 NodeInfo info; 100 101 for (int i = 0; i < hosts.length; i++) { 102 if ((System.currentTimeMillis() - 103 ((Long ) hosts[i].getValue()).longValue()) > _timeout) { 104 info = (NodeInfo) hosts[i].getKey(); 105 _addresses.remove(info); 106 _nodeToAddr.remove(info.node); 107 } 108 } 109 } 110 } 111 112 115 static class NodeInfo { 116 final ServerAddress addr; 117 final String node; 118 119 NodeInfo(ServerAddress addr, String node) { 120 this.addr = addr; 121 this.node = node; 122 } 123 124 public boolean equals(Object obj) { 125 NodeInfo inf = (NodeInfo) obj; 126 127 return inf.addr.equals(addr) && inf.node.equals(node); 128 } 129 130 public int hashCode() { 131 return addr.hashCode(); 132 } 133 } 134 135 public static class AddressList extends ArrayList { 136 AddressList(Collection infos) { 137 super(infos); 138 } 139 140 public Object get(int idx) { 141 try { 142 return ((NodeInfo) super.get(idx)).addr; 143 } catch (ClassCastException e) { 144 throw e; 145 } 146 } 147 } 148 } 149 | Popular Tags |