-1

I have an enterprise application which was eating so much of CPU. As dug further into thread dump, I see the threads that are eating so much CPU is stuck at TreeMap.put. I see a similar question here due to the same problem.

I understand people mentioned there that TreeMap is not thread safe. But what I don't understand is, not having ThreadSafe might cause inconsistent results. But why it holds the CPU?

Kannan Ramamoorthy
  • 3,980
  • 9
  • 45
  • 63
  • Are you accessing the `TreeMap` from multiple threads? Thread-safety only concerns accessing the same object/state from multiple threads. – dan1st Feb 21 '23 at 17:14
  • Also, how many elements are in the `TreeMap`? How long does a single `TreeMap#put` call take? How often do you call `put()`? – dan1st Feb 21 '23 at 17:16
  • 6
    Unsynchronized multithreaded writes can corrupt a TreeMap to the point of forming infinite loops. [External explanation.](https://ivoanjo.me/blog/2018/07/21/writing-to-a-java-treemap-concurrently-can-lead-to-an-infinite-loop-during-reads/) – teapot418 Feb 21 '23 at 17:17
  • 1
    Just as an fyi: `HashMap` or `LinkedList` may also form infinite loops, e.g. when 2 threads change the `next` or `prev` references to form a cycle. And there are probably a couple of other collections or maps that suffer from the same. General rule of thumb: don't do unsynchronized parallel access to non-thread-safe data structures. – Thomas Feb 21 '23 at 17:22

1 Answers1

0

Multithreaded access to an unsynchronized TreeMap can not only cause inconsistent data to be seen, but can actively lead to infinite loops.

Infinite loops can, of course, take infinite amounts of time. So really, really don't have multithreaded access to a TreeMap. Use a concurrent implementation like ConcurrentSkipListMap, or synchronize properly.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413