I wanted to make a more simple verison of a pool in my app, using two hashmap - one with alive objects, and one with dead.
I have a function that spawns alive objects and places them in an hashmap, and if they die it removes it from the hashmap. This causes a lot of calls to garbage collector and a big ram usage that only grows. Instead I thought of solution, creating two hashmap like that:
ConcurrentHashMap<Point, Mob> spawned = new ConcurrentHashMap<Point, Mob>();
ConcurrentHashMap<Point, Mob> died = new ConcurrentHashMap<Point, Mob>();
And placing a dead object inside the died hashmap like that for example:
MobSpawnedEntries1 = spawned.entrySet().iterator();
while (MobSpawnedEntries1.hasNext()) {
Map.Entry<Point, Mob> entry = MobSpawnedEntries1.next();
if(entry.getValue().isDead()){
died.put(entry.getKey(), entry.getValue());
MobSpawnedEntries1.remove();
}
}
After that in the spawn function, i checked if the "died" hashmap is empty, if its not I just respawned the object and placed it in the spawned hashmap, and also removed it from the died hashmap.
if (diedEntries.hasNext()) {
Map.Entry<Point, Mob> entry = diedEntries.next();
Point p=entry.getKey();
Mob b=entry.getValue();
b.Reset();
p.x=...;
p.y=...;
spawned.put(p,b);
diedEntries.remove();
}
The problem:
This caused odd bugs such as all entities becoming the same, and changing to the newest spawned entity, when one entitiy dies they all die as well, and stuff like that - like there was connection between all the entities. I thought it was the key so I just created a new Point for each entity instead of placing the old key, but the bug still accured. Why? What is a better solution for this (if there is a need of use in pool ill be happy if someone could show me how - I have never used pool or have any idea how to use it).
0 comments:
Post a Comment