ARTICLE AD BOX
I have built an application in Java Spring 2.7.2, and I want consistent unit tests for it, covering its common scenarios. But one of my tests is hanging because the different threads disagree on what's inside a particular Map, "fetchQueueMap."
@Service class KafkaProfileService { Map<String, List<String>> fetchQueueMap = new HashMap<>(); ReentrantLock fetchLock = new ReentrantLock(); /** Etc **/ class MappingFetchThread implements Runnable { public void run() { final int DELAY = 5000; Thread.currentThread().setName("mapping-fetch-thread"); Long targetTime = System.currentTimeMillis() + DELAY; while(true) { if(System.currentTimeMillis() < targetTime) { try { Thread.sleep(5000); } catch(InterruptedException ie) { Thread.currentThread().interrupt(); } } else { fetchQueuedRoutingValues(); targetTime = System.currentTimeMillis() + DELAY; } } } } private void fetchQueuedRoutingValues() { HashMap<String, List<String>> toBeFetched = new HashMap<>(); fetchLock.lock(); try { for(String profileName : fetchQueueMap.keySet()) { /*etc, fetch logic is not in question here */ } } finally { fetchLock.unlock(); } } private void addToFetchQueue(String profileName, List<String> routingValues) { fetchLock.lock(); try { if(fetchQueueMap.get(profileName) == null) { fetchQueueMap.put(profileName, new ArrayList<>()); } fetchQueueMap.get(profileName).addAll(routingValues); } finally { fetchLock.unlock(); } } }So when addToFetchQueue is called in one thread, I can see that it is being added correctly. But when the mappingFetcher reads fetchQueueMap, it is not present, the map is empty. The real infuriating part of this is, this is only happening in my unit testing with JUnit. When I actually run the application, there is no issue, and the locking mechanisms I use are enough to keep consistency. What is happening, and why?
