You could use a ConcurrentLinkedQueue as your list, and iterate using the iterator method. Then elements are added to directly to the thread's list, but it uses a wait-free algorithm instead of locking the whole list. You can alternatively use CopyOnWriteArrayList if adding elements is very rare.
and @VildNinja
I have played around with this idea to use an "object stream". I was not aware of ConcurrentLinkedQueue which is a very interesting class in that case.
I've tried it also with a concurrent HashSet by using
Set set = Collections.newSetFromMap( new ConcurrentHashMap() );
to increase performance furthermore but I like the FIFO-Version which can become handy and looks also better in code.
Maybe will change it later at the very end of development to (Concurrent)HashSet to potentially increase performance.
An example abstract class showing the general architecture of one of my unit memory classes implementing the idea with a ConcurrentLinkedQueue.
public class ThreadUnitMemory< A extends AbstractObject<A>> {
private final HashSet<A> allObjects;
private final ConcurrentLinkedQueue<A> clqObjectStreamNew, clqObjectStreamKill;
public LoopDatabase() {
allObjects = new HashSet<A>();
clqObjectStreamNew = new ConcurrentLinkedQueue<A>();
clqObjectStreamKill = new ConcurrentLinkedQueue<A>();
}
public void addObjectToThread( A a ) {
clqObjectStreamNew.offer( a );
}
public void removeObjectFromThread( A ao ) {
clqObjectStreamTrash.offer( a );
}
private A buffer;
public void loop() {
while( !clqObjectStreamNew.isEmpty() ) {
buffer = clqObjectStreamNew.poll();
allObjects.add( buffer );
}
while( !clqObjectStreamTrash.isEmpty() ) {
buffer = clqObjectStreamTrash.poll();
allObjects.remove( buffer );
}
// compute all the logic stuff we are actually here for - iterating over allObjects
}
}
Hi! Hope you will like it here.
Does each thread need its own entity list in memory?
[...]
An indeed interesting architectural solution I would really like to implement but I've decided against but will try that out someday definitly for other projects.
Reasons I decided against:
>> Needs more time to implement. Especially when you are later in development stage, I guess it would be best to implement this from the very beginning.
>> Needs lots of ressources in general which is not justified in my case. The threads are totally seperated from one another beside the little tweak that new objects have to be added to their memory when needed.
>> All threads have their individual memory architecture.
the logic-thread for example only needs a simple set of objects;
the OpenGL-thread is sorting the objects in a scene graph;
the AI-thread is sorting with different hyrachies depending on the ai's and their relation to the object;
and this goes on... again it was designed from the beginning that every thread is and works totally independent.
However, I've wrote this down for a later project.
Thank all of you very much!
- Ica