I have a ConcurrentSkipListMap
. I need to remove elements which are lower then key
.
Here is how I can perform it:
private ConcurrentNavigableMap<Double, MyObject> myObjectsMap = new ConcurrentSkipListMap<>();
//...
myObjectsMap = myObjectsMap.tailMap(10.25, false);
Looks OK, but I am confused about these facts:
1.
The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa.
Does it mean that old values won't be removed by the garbage collector?
I.e. we removed the old map and now we have a new map. But this new map is backed by the old map. So, what happens with the old map? Will it be removed or will it be sitting on a memory forever?
2.
The returned map will throw an IllegalArgumentException on an attempt to insert a key outside its range.
So, now I can't put new keys which are less than 10.25 and more than the last maximum value?
I'am confused. How then correctly I need to remove elements from the ConcurrentSkipListMap?
Does it mean that old values won't be removed by the garbage collector? I.e. we removed the old map and now we have a new map. But this new map is backed by the old map. So, what happens with the old map? Will it be removed or will it be sitting on a memory forever?
Yes, in point of fact. The old map is still around, and it'll stay around.
If you want to remove keys < 10.25, then do
map.headMap(10.25, false).clear();
...which will create that sub-map, remove all its elements -- removing them from the original map, too -- and then discard that submap view, letting it get garbage collected and leaving you with the original map object containing only keys >= 10.25.
Mind you, while this is guaranteed to remove keys that were < 10.25 when the operation started, there are no guarantees that new keys haven't been concurrently inserted, or that new keys might get inserted later. There's nothing you can do about that, really. If you want to be very sure you're only operating over values >= 10.25, then go ahead and use map.tailMap(10.25, true)
, but other values less than 10.25 might still be getting inserted, and they'll still be in memory.