Code example for ConcurrentMap

Methods: get, putIfAbsent

0
    // store timing info per aggregation key 
    private final ConcurrentMap<String, MetricDataItemSafeImpl> map = 
            new ConcurrentHashMap<String, MetricDataItemSafeImpl>(); 
 
    public void recordData(String name, long timeInNanoseconds) { 
        MetricDataItemSafeImpl summaryDataItem = map.get(name); 
        if (summaryDataItem == null) { 
            // it's possible that two threads both instantiate a new OperationSummaryDataItem 
            // but only one of the SummaryDataItems will get set via putIfAbsent which is why we 
            // retrieve the value afterwards 
            map.putIfAbsent(name, new MetricDataItemSafeImpl(name)); 
            summaryDataItem = map.get(name); 
        } 
        summaryDataItem.recordData(timeInNanoseconds); 
    } 
 
    public Iterable<MetricDataItemSafeImpl> getItems() { 
        return map.values(); 
    } 
}