Original Question is here but this time slightly different scenario.
I have a static hashMap, shared with multiple threads. I am not iterating the map and don't care about the size of the map. I only use the get
, put
, remove
in the map. Each thread may call someClass.track(true)
or someClass.track(false)
. I want to track when a thread enters a method (increment #) and exit a method (decrements #) for each thread.
Is it sufficient to use just a HashMap? Or I have to use a ConcurrentHashMap to guarantee getting a correct value from the track
method?
The method looks like this
private static Map<Long, Integer> TRACKER = new HashMap<Long,Integer>();
public static Integer track(boolean b) {
long tid = Thread.currentThread().getId();
if (b) {
if (TRACKER.containsKey(tid)) {
TRACKER.put(tid, TRACKER.get(tid) + 1);
} else {
TRACKER.put(tid, 1);
}
} else {
Integer n = TRACKER.get(tid);
if (n != null) {
n = n -1;
if (n == 0) {
TRACKER.remove(tid);
} else {
TRACKER.put(tid, n);
}
}
}
return TRACKER.get(tid);
}