- How can I improve performance of
this chunk of code ? - What would be unit test case for the given problem statement ?
Code:
public class SlowDictionary {
private final Map<String,String> dict = new HashMap<String,String>();
public synchronized String translate (String word)
throws IllegalArgumentException {
if (!dict.containsKey(word)) {
throw new IllegalArgumentException(word + " not found.");
}
return dict.get(word);
}
public synchronized void addToDictionary (String word, String translation)
throws IllegalArgumentException {
if (dict.containsKey(word)) {
throw new IllegalArgumentException(word + " already exists.");
}
dict.put(word,translation);
}
public synchronized Set<String> getAllWords () {
return dict.keySet();
}
}
First thing you want to do is get rid of all synchronized key words.
The easiest way of doing that is be declaring dict to be a ConcurrentHashMap:
Doing this you can immidiatly remove the synchronized part of translate so it would look like:
The reason for this is the contract in which the CCHM holds regarding up to date reads.
Finally, add to dictionary can look like:
Also remove synchronized from getAllWords as well.
Edit: After thinking about tom’s comment. Having a double look up in this ‘exception case’ probably isnt worth it. If the case didnt throw an exception then it would be appropriate.