In case of following code, run by multiple threads:
private static final Map<String, keyinfo> mapKeys = new ConcurrentHashMap<String, keyinfo>();
private static void purgeOldKeys() {
for (Map.Entry<String, keyinfo> key : mapKeys.entrySet()) {
if(key.getValue().createTime + keyCacheTime < getCurrentDBTime())
mapKeys.remove(key);
}
}
Can I avoid the synchronizer?
Or because removing already removed element, is not defined according to JavaDoc, the synchronizer will be still required?
In general, when removing from a collection, it is much cleaner (and faster!) to use a full
IteratorAPI instead of the lazy “foreach” notion.The
iterator.remove();will not invalidate the iterator; and it knows the position it was at. Use this pattern:It’s faster because it does not involve searching the object again. It’s more robust, because the iterator knows the object has been removed. In many collections, the code you showed above will “fast fail” because of a concurrent modification.