|
22 | 22 | */
|
23 | 23 | package com.iluwatar.throttling;
|
24 | 24 |
|
| 25 | +import org.slf4j.Logger; |
| 26 | +import org.slf4j.LoggerFactory; |
| 27 | + |
25 | 28 | import java.util.Map;
|
26 | 29 | import java.util.Map.Entry;
|
27 | 30 | import java.util.concurrent.ConcurrentHashMap;
|
| 31 | +import java.util.concurrent.atomic.AtomicLong; |
28 | 32 |
|
29 | 33 | /**
|
30 | 34 | * A class to keep track of the counter of different Tenants
|
31 | 35 | * @author drastogi
|
32 | 36 | *
|
33 | 37 | */
|
34 | 38 | public final class CallsCount {
|
35 |
| - private static Map<String, Integer> tenantCallsCount = new ConcurrentHashMap<>(); |
| 39 | + |
| 40 | + private static final Logger LOGGER = LoggerFactory.getLogger(CallsCount.class); |
| 41 | + private static Map<String, AtomicLong> tenantCallsCount = new ConcurrentHashMap<>(); |
36 | 42 |
|
37 | 43 | /**
|
38 | 44 | * Add a new tenant to the map.
|
39 | 45 | * @param tenantName name of the tenant.
|
40 | 46 | */
|
41 | 47 | public static void addTenant(String tenantName) {
|
42 |
| - if (!tenantCallsCount.containsKey(tenantName)) { |
43 |
| - tenantCallsCount.put(tenantName, 0); |
44 |
| - } |
| 48 | + tenantCallsCount.putIfAbsent(tenantName, new AtomicLong(0)); |
45 | 49 | }
|
46 | 50 |
|
47 | 51 | /**
|
48 | 52 | * Increment the count of the specified tenant.
|
49 | 53 | * @param tenantName name of the tenant.
|
50 | 54 | */
|
51 | 55 | public static void incrementCount(String tenantName) {
|
52 |
| - tenantCallsCount.put(tenantName, tenantCallsCount.get(tenantName) + 1); |
| 56 | + tenantCallsCount.get(tenantName).incrementAndGet(); |
53 | 57 | }
|
54 | 58 |
|
55 | 59 | /**
|
56 | 60 | *
|
57 | 61 | * @param tenantName name of the tenant.
|
58 | 62 | * @return the count of the tenant.
|
59 | 63 | */
|
60 |
| - public static int getCount(String tenantName) { |
61 |
| - return tenantCallsCount.get(tenantName); |
| 64 | + public static long getCount(String tenantName) { |
| 65 | + return tenantCallsCount.get(tenantName).get(); |
62 | 66 | }
|
63 | 67 |
|
64 | 68 | /**
|
65 | 69 | * Resets the count of all the tenants in the map.
|
66 | 70 | */
|
67 | 71 | public static void reset() {
|
68 |
| - for (Entry<String, Integer> e : tenantCallsCount.entrySet()) { |
69 |
| - tenantCallsCount.put(e.getKey(), 0); |
| 72 | + LOGGER.debug("Resetting the map."); |
| 73 | + for (Entry<String, AtomicLong> e : tenantCallsCount.entrySet()) { |
| 74 | + tenantCallsCount.put(e.getKey(), new AtomicLong(0)); |
70 | 75 | }
|
71 | 76 | }
|
72 | 77 | }
|
0 commit comments