我有一个HashMap:
public static HashMap<Long, KeepAliveTimer> kaTimer;
它存储一个 MACAddress 和一个 Timer。
我创建了 HashMap:
if(kaTimer == null) {
//init the Hash
kaTimer = new HashMap<Long, keepAliveTimer>();
KeepAliveTimer keepAliveTimer = new KeepAliveTimer(macaddress, ipaddress);
kaTimer.put(macaddress, keepAliveTimer);
} else {
//The Hash exists
if(kaTimer.containsKey(macaddress)) {
//The MAC exists into the map
System.out.println(kaTimer.size());
Collection col = kaTimer.values();
for (Object obj : col) {
System.out.println(obj);
}
System.out.println(String.valueOf(macddress));
KeepAliveTimer keepAliveTimer = kaTimer.get(macaddress);
keepAliveTimer.update();
} else {
//The MAC doesn't exist in the Hash
KeepAliveTimer keepAliveTimer = new KeepAliveTimer(macddress, ipaddress);
kaTimer.put(macaddress, keepAliveTimer);
}
}
KeepAlive定时器:
public KeepAliveTimer(long mac, String ipAddress){
this.macaddress = mac;
this.ip = ipAddress;
timer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
timerFinished();
}
};
log.info(String.valueOf(macaddress) + " con la ip " + ip);
timer.schedule(timerTask, 3*60*1000);
}
public void update() {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
timerFinished();
}
};
log.info(String.valueOf(macaddress) + " con la ip " + ip);
timer.cancel();
timer.purge();
timer = new Timer();
timer.schedule(timerTask, 3*60*1000);
}
public void timerFinished() {
KeepAlive keep = new KeepAlive(macddress, ip);
keep.removeFromHash();
//Actions
}
创建 KeepAliveTimer 元素后一切正常,我创建了 2 个 KeepAliveTimer 元素:
KeepAliveTimer keepAliveTimer = new KeepAliveTimer(macddress, ipaddress);
kaTimer.put(macaddress, keepAliveTimer);
当所有这些都被创建后,我必须使用 KeepAliveTimer 元素,因此,我从哈希中提取它们:
KeepAliveTimer keepAliveTimer = kaTimer.get(macaddress);
keepAliveTimer.update();
每个元素都是用一个 mac 和一个 ip 创建的,但是在提取最后一个创建的 ip 时总是使用
我添加了以下几行:
System.out.println(kaTimer.size());
Collection col = kaTimer.values();
for (Object obj : col) {
System.out.println(obj);
}
System.out.println(String.valueOf(macddress));
我得到:
//First element
//In the HashMap
spb.KeepAliveTimer@105bd58
spb.KeepAliveTimer@edf3f6
//MAC
26954208388119
//KeepAliveTimer I get
spb.KeepAliveTimer@edf3f6
//MAC + IP
INFO: 26954208388119 con la ip 178.139.7.27
//Second element
//In the HasMaP
spb.KeepAliveTimer@105bd58
spb.KeepAliveTimer@edf3f6
//MAC
26954208388118
//Timer I get
spb.KeepAliveTimer@105bd58
//MAC+IP
INFO: 26954208388118 con la ip 178.139.7.27