私はハッシュマップを持っています:
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);
}
}
KeepAliveTimer:
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