I tried to use ExpringMap to auto expire the map object. This is the first time I use this jar, I know there is a Guava which is popular, but I do not need cache for that and I don't know how to use the Guava either.
And I happen to know the ExpiringMap from the mina project so I tested it below, but it didn't not work. Why is that?
I hope to have a hign-performace and easy-to-use way to remove my object from the map after several minutes. Can any body give me an example for that? Thank you!
ExpiringMap<String, String> map2=new ExpiringMap<String, String>(2,1);
ExpiringMap<String, String> map10=new ExpiringMap<String, String>( 10,1);
ExpiringMap<String, String> map5=new ExpiringMap<String, String>(5,1);
map2.put("1", "1");
map5.put("1","1");
map10.put("1", "1");
map2.put("2", "2");
map5.put("2","2");
map10.put("2", "2");
int n=0;
while(true){
System.out.println("----"+3*n+"seconds----");
Set<String> set2=map2.keySet();
System.out.println("----map2----");
for (String key : set2) {
System.out.println(map2.get(key));
}
Set<String> set5=map5.keySet();
System.out.println("----map5----");
for (String key : set5) {
System.out.println(map5.get(key));
}
Set<String> set10=map10.keySet();
System.out.println("----map10----");
for (String key : set10) {
System.out.println(map10.get(key));
}
Thread.sleep(3000);//sleep 3 seconds
n++;
}
The out put is obious that the object is still in the map
----0seconds----
----map2----
1
2
----map5----
1
2
----map10----
1
2
----3seconds----
----map2----
1
2
----map5----
1
2
----map10----
1
2
----6seconds----
----map2----
1
2
----map5----
1
2
----map10----
1
2
----9seconds----
----map2----
1
2
----map5----
1
2
----map10----
1
2
----12seconds----
----map2----
1
2
----map5----
1
2
----map10----
1
2
The get is causing the reference time to be reset so the timeout is never happening. the map2 is borderline because the time is 2 seconds and the check interval is 1 second. so its could skew to almost 3 seconds and not timeout before its read again I think. try putting the sleep first and try lengthening it by 3 seconds each loop and see what happens.
The following lines need to also be added before things will start expiring:
map2.getExpirer().startExpiring();
map10.getExpirer().startExpiring();
map5.getExpirer().startExpiring();
with that the 2 second expires. the other two maps do not because the interval between references is never long enough with current code.