The problem is occurring because you are iterating over the maps set of keys and modifying the map at the same time. In your second attempt you copy the map and get the keyset from the copy and hence modifying the original map works. Another way of gettig this to work would be to make a copy of the set of keys and iterate over the copy or you could just use the iterator returned by the map which has a remove method.
Campbell Ritchie wrote:Why are you using string tokenizer, which has been regarded as legacy code for about 13 years?
Could you post a source for this? Everybody I know uses Strings, and I have never had an issue with them. What is so bad about using them, and since when where they legacy?
From the Javadoc page of StringTokenizer itself:
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
Now String.split and the java.util.regex package have been added in Java 1.4, so I'd say that's the moment StringTokenizer became legacy code.
Joe Thatcher wrote:Or, if you really want to read and write at the same time, use a ConcurrentHashMap which will allow you to both read and write at the same time, but in my experience can use slightly more CPU.
If you only need to remove elements, you can also use an explicit Iterator. That's a lot cheaper than using a ConcurrentHashMap.
Sujoy, this works because keySet() doesn't "extract all the keys from the map and stores them in a set", it returns a set that is a direct view of the map. If you remove anything from this set, you remove the matching entry from the map. If you add anything to the map, you add an entry to the key set as well. (You can't add anything to the set, because you can't specify the value for the key. Trying to call add will cause an UnsupportedOperationException to be thrown.)