Ekos IV
Ekos IV

Reputation: 367

Building a synchronous map, blocking on individual keys

I want to build a repository class, as follows:

public class ResultRepository {

  private Map<String, Result> sqlRepository = Collections.synchronizedMap(new HashMap<>());

  public synchronized Result getResult(String key) {
    Result result = map.get(key);
    if (result == null) {
      result = doAnExpensiveOperation(key));
      map.put(key, result);
    }
    return result;
  }

  ...

}

This will work, currently, but will be slow if multiple calls are made to the getResult method if the expensive operation is required.

What I want, however, is this:

Is there a pattern I can apply to get this behaviour? I could theoretically have a Set of the pending result keys but this seems a bit janky. Maybe the repository could hold Future<Result> objects?

Upvotes: 0

Views: 151

Answers (1)

drekbour
drekbour

Reputation: 3091

I think all of this comes with ConcurrentHashMap

    private Map<String, Result> sqlRepository = new ConcurrentHashMap<>();

    public Result getResult(String key) {
        return sqlRepository.computeIfAbsent(key, this::doAnExpensiveOperation);
    }

Upvotes: 3

Related Questions