I have multi threads that want to put a value in a TreeSet<Long>
, in a part of code. The values are almost unique because they are System.nanoTime()
. I clean the TreeSet
s periodically. Problem is that sometimes my threads got blocked in TreeSet.add()
function. I used jconsole to watch thread states, threads are in RUNNABLE
state and the stack trace shows this:
java.util.TreeMap.put(TeeMap.java:567)
java.util.TreeSet.add(TreeSet.java:255)
... //my program stack trace
I'm using jdk 1.7.0_60 for running program. Also I should mention in this situation cpu usage become 100%. My question is why the threads got blocked and how can I fix the situation? I looked at TreeMap code, but I didn't figure out problem, but I think problem relates to while loop in TreeMap.put()
.
As it was mentioned in comments, the problem is that TreeSet
is not thread safe and if we want to modify it (add or remove data) in multi threads, it must be synchronized externally.