r/javahelp • u/Floppy012 • Sep 03 '25
Best Thread-Safe way of adding/removing from a Collection
I was wondering how this could be best solved:
I have a game-like scenario where a thread has a loop that runs 50 times/s. Each iteration it iterates over a collection (can be List or Set) that can get relatively large ~5k-10k items. Items shall not be removed after processing so a queue is probably not the right choice.
Add/Remove requests always come from outside that thread and occur frequently.
There are many solutions that come to mind when trying to implement this. Synchronized blocks, Object locking, Synchronized Collections, ConcurrentHashMap, Reentrant Locks, Separate lists for add/remove requests and processing those lists in before/after an iteration. Maybe I'm even missing something.
What would be the most balanced way of achieving thread safety/performance?
View all comments
Show parent comment
1
u/Floppy012 Sep 04 '25
Entries in that list are representations of monsters.
Basically, every iteration each item checks if a state change is required. If so the state change is performed. The amount of processing is relatively minimal per iteration.
Monster spawns -> entry added Monster dies -> entry removed