Main Question:
I’m seeking some way to give an object within a LinkedList a reference to itself within the list so that it can (efficiently) remove itself from said list (Without sorting through the list looking for itself. I’d like it to just directly cut itself from the list and tie the previous and next items together.).
Less Necessary Details:
I’ve done a reasonable amount of googling and not found anything other than people advising not to use circular references.
I’d like to do this as I’m designing a game, and in the game objects can implement various interfaces which allow them to be in various lists which are looped through in a prioritized manner. A single object might be in a draw loop, a loop which steps it through the frames of its animation, a high priority logic loop, and a low priority logic loop all at the same time. I would like to implement a removeFrom|TypeOfLoop| method in each appropriate interface so that if an object decides that it no longer needs to be in a loop it can directly remove itself. This keeps the objects that do the actual looping pleasantly simple.
Alternatively, If there is no way to do this, I’m thinking of implementing a flagging system where the list checks to see if each item wants to be removed based on a variable within the item. However, I dislike the idea of doing this enough to possibly just make my own LinkedList that is capable of removing by reference.
I did this recently. I was looking for an O(1) add O(1) remove lock-free
Collection. Eventually I wrote my ownRingbecause I wanted a fixed-size container but you may find the technique I used for my first attempt of value.I don’t have the code in front of me but if memory serves:
Take a copy of Doug Lea‘s excellent Concurrent Doubly LinkedList and:
Expose the
Nodeclass. I used aninterfacebut that is up to you.Change the
add,offer… methods to return aNodeinstead ofboolean. It is now no longer a javaCollection, but see my comment later.Expose theadd adeletemethod of theNodeclass orremovemethod that takes aNode.You can now remove elements from the list in O(1) time, and it is Lock Free.
Added
Here’s an implementation of the
remove(Node)method taken from hisIteratorimplementation. Note that you have to keep trying until you succeed.