High CPU due to multiple Java threads accessing TreeMap simultaneously
Environment
- Java
Issue
- High cpu.
- Thread(s) consuming cpu have TreeMap at the top of the stack trace. For example:
"ajp-0.0.0.0-8209-2" daemon prio=10 tid=0x08668800 nid=0x38e runnable [0x4c382000] java.lang.Thread.State: RUNNABLE at java.util.TreeMap.put(TreeMap.java:552) ... "ajp-0.0.0.0-8209-3" daemon prio=10 tid=0x08343000 nid=0x3cf runnable [0x4c23e000] java.lang.Thread.State: RUNNABLE at java.util.TreeMap.getEntry(TreeMap.java:335) at java.util.TreeMap.get(TreeMap.java:255) ... "ajp-0.0.0.0-8209-4" daemon prio=10 tid=0x08409400 nid=0x408 runnable [0x4bee9000] java.lang.Thread.State: RUNNABLE at java.util.TreeMap.getEntry(TreeMap.java:335) at java.util.TreeMap.get(TreeMap.java:255) ... "ajp-0.0.0.0-8209-5" daemon prio=10 tid=0x089d9c00 nid=0x448 runnable [0x4c28f000] java.lang.Thread.State: RUNNABLE at java.util.TreeMap.put(TreeMap.java:552) ...
Resolution
-
Synchronize access on some object that naturally encapsulates the map. This can easily be done at creation by wrapping the map through the Collections.synchronizedSortedMap method:
SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
Root Cause
- TreeMap is not a thread safe object. If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. See http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html.
This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.