Jasjeet Singh
02/16/2024, 11:07 AMfor (item in queue) {
if (item == 0) {
queue.remove(item)
}
}
Will this cause deadlocks?
To be specific the queue used here is ConcurrentLinkedQueue
from java.util
.hho
02/16/2024, 11:15 AMIterator
for the collection.Jasjeet Singh
02/16/2024, 11:37 AMSam
02/16/2024, 1:49 PMConcurrentModificationException
. Yours will be okay though, because ConcurrentLinkedQueue
is specifically exempt from that rule 👍.Jasjeet Singh
02/16/2024, 3:14 PMConcurrentLinkedQueue
) or is this just your knowlegde/observations?Sam
02/16/2024, 3:47 PMIterators are weakly consistent, returning elements reflecting the state of the queue at some point at or since the creation of the iterator. They do not throwWhereas for an ArrayList:, and may proceed concurrently with other operations. Elements contained in the queue since the creation of the iterator will be returned exactly once.ConcurrentModificationException
The iterators returned by this class'sanditerator
methods are _fail-fast_: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's ownlistIterator
orremove
methods, the iterator will throw aadd
.ConcurrentModificationException
Jasjeet Singh
02/16/2024, 4:07 PMJasjeet Singh
02/16/2024, 4:08 PMWout Werkman
02/16/2024, 5:05 PMremoveIf
, it's a Java Collection method, and ConcurrentLinkedQueue
has an optimized override for this.
fun MutableCollection<Int>.removeZeroes(): Boolean {
return removeIf { it == 0 }
}
Additionally, for more fine grained control, sometimes using a MutableIterator
can be both more convenient as well as faster (remove
on ConcurrentLinkedQueue
is O(n)
, while it's O(1)
on it's iterator). You can look at the default implementation of removeIf
to see an example.Jasjeet Singh
02/16/2024, 5:43 PMremoveIf
but due to compatibility issues, I dropped it 😞
For the MutableIterator
part, this is a really nice optimization that i wanted for a long time. I actually hate making remove (basically find and then remove) on collections when I already have them in a for loop. Now this really advocates against the use of for
loop haha but really thanks for this advice. Iterators are noice concept!Wout Werkman
02/16/2024, 8:15 PMJasjeet Singh
02/17/2024, 4:54 AMqueue.remove(item)
is my average case of itr.remove()
. That too if removeIf{..}
is not compatible.