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:
private final ConcurrentMap<String,String> dict = new ConcurrentHashMap<String,String>();
Doing this you can immidiatly remove the synchronized part of translate so it would look like:
public String translate (String word) throws IllegalArgumentException { ..
The reason for this is the contract in which the CCHM holds regarding up to date reads.
Finally, add to dictionary can look like:
public void addToDictionary (String word, String translation) throws IllegalArgumentException {
if (dict.putIfAbsent(word,translation)!=null) {
throw new IllegalArgumentException(word + " already exists.");
}
}
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.
Dumping all the synchronized keywords and defining dict as a ConcurrentHashMap might be worth trying.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With