2
* Cobertura - http://cobertura.sourceforge.net/
4
* Copyright (C) 2010 Piotr Tabor
6
* Note: This file is dual licensed under the GPL and the Apache
7
* Source License (so that it can be used from both the main
8
* Cobertura classes and the ant tasks).
10
* Cobertura is free software; you can redistribute it and/or modify
11
* it under the terms of the GNU General Public License as published
12
* by the Free Software Foundation; either version 2 of the License,
13
* or (at your option) any later version.
15
* Cobertura is distributed in the hope that it will be useful, but
16
* WITHOUT ANY WARRANTY; without even the implied warranty of
17
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18
* General Public License for more details.
20
* You should have received a copy of the GNU General Public License
21
* along with Cobertura; if not, write to the Free Software
22
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
26
package net.sourceforge.cobertura.coveragedata.countermaps;
28
import java.util.Iterator;
29
import java.util.LinkedHashMap;
31
import java.util.concurrent.ConcurrentHashMap;
32
import java.util.concurrent.ConcurrentMap;
33
import java.util.concurrent.atomic.AtomicInteger;
35
import net.sourceforge.cobertura.coveragedata.HasBeenInstrumented;
38
* Thread-safe implementation of map that counts number of keys (like multi-set)
43
public class AtomicCounterMap<T> implements CounterMap<T>,HasBeenInstrumented{
44
private final ConcurrentMap<T, AtomicInteger> counters=new ConcurrentHashMap<T, AtomicInteger>();
46
public final void incrementValue(T key, int inc){
47
AtomicInteger v=counters.get(key);
51
v=counters.putIfAbsent(key, new AtomicInteger(inc));
52
if(v!=null)v.addAndGet(inc);
56
public final void incrementValue(T key){
57
//AtomicInteger v=counters.putIfAbsent(key, new AtomicInteger(1));
58
//return (v!=null)?v.incrementAndGet():1;
59
AtomicInteger v=counters.get(key);
63
v=counters.putIfAbsent(key, new AtomicInteger(1));
64
if(v!=null)v.incrementAndGet();
68
public final int getValue(T key){
69
AtomicInteger v=counters.get(key);
70
return v==null?0:v.get();
74
public synchronized Map<T,Integer> getFinalStateAndCleanIt(){
75
Map<T,Integer> res=new LinkedHashMap<T, Integer>();
76
Iterator<Map.Entry<T, AtomicInteger>> iterator=counters.entrySet().iterator();
77
while (iterator.hasNext()) {
78
Map.Entry<T, AtomicInteger> entry=iterator.next();
80
int old=entry.getValue().get();
90
return counters.size();