Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Performance using Concurrency

  1. How can I improve performance of this chunk of code ?
  2. 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();
        }
    }
like image 566
Rachel Avatar asked Mar 16 '26 00:03

Rachel


2 Answers

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.

like image 111
John Vint Avatar answered Mar 18 '26 14:03

John Vint


Dumping all the synchronized keywords and defining dict as a ConcurrentHashMap might be worth trying.

like image 32
BlairHippo Avatar answered Mar 18 '26 12:03

BlairHippo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!