user1979776
user1979776

Reputation: 171

Best way to write hash map with sparse writes and many reads

I need to write a hash map in Java which will be used across threads mostly for reads. Consider a situation in which clients write to the hash map only once(only 10 or 15 entries max), but the key and value comes from the client. This means that I do not know the key/value pairs in advance.After once writing them, they read many times simultaneously.

More like the below code snippet in an efficient way:

public String getPS(String query) {
    //put into map if not present
    if(psMap.get(query) == null){
        synchronized (this) {
            if(psMap.get(query) == null){
                //test1 is just a sample  value
                psMap.put(query,"test1");
            }
        }
    }
    return psMap.get(query);

}

Upvotes: 1

Views: 70

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533472

ConcurrentHashMap has concurrent access and the ability to remember a computed value. Note: this will be called only once per key.

public String getPS(String query) {
    //put into map a computed value if not present
    return psMap.computeIfAbsent(query, $ -> "test1");
}

Upvotes: 0

DrunkenPope
DrunkenPope

Reputation: 576

The implementation of ConcurrentHashMap assumes that the most common operation is retrieving a value, so it is already optimized for the get operations. It even has the putIfAbsent method, so you don't have to implement it yourself.

Upvotes: 4

Related Questions