How to handle lists of multiple entities being born, drawn and killed simultaneously without conflicts?

ساخت وبلاگ

Vote count: 0

I'll try to keep it short, these is the situation:

  • Creature Class : x y coordinates, moves around randomly and shoots Projectiles

  • Projectile Class : x y coordinates, moves in a straight line and dies when impacting Creatures

  • Arena Class : JPanel which iterates over the lists of creatures and projectiles and calls their draw() method.

If you dont't wish to read any further this is my main question: What is the best way to handle Projectiles being created and inserted in the projectile list of the JPanel? Is having such a list is even a good idea in the first place?

Should I create a mutex semaphore which acquires a permit whenever the JPanel is iterating over the projectile list and releases the permit once it's done? I'm running into trouble when the creatures decide to insert a new bullet while iterating over the list. If this is the case, what is the best way of letting the creature class access this semaphore?

Also I would like to add that I usually use this tactic to avoid concurrent modifications in similar situations:

  1. List of items ready to be added
  2. List of "active" items
  3. List of items ready to be removed

And then:

if (!toBeAdded.isEmpty()) { activeItems.addAll(toBeAdded); activetoBeAdded.clear();
}
if(!toBeRemoved.isEmpty()) { activeItems.removeAll(toBeRemoved); toBeRemoved.clear();
} 

But this of course doesn't work in this particular situation because I am just "moving" the problem from the active list to the toBeAdded one, I still get a concurrent modification if my creatures try and add bullets to the toBeAdded list while it's being used.

asked 34 secs ago

back soft...
ما را در سایت back soft دنبال می کنید

برچسب : نویسنده : استخدام کار backsoft بازدید : 212 تاريخ : يکشنبه 20 فروردين 1396 ساعت: 4:16