Hi! So I was hacking a bit the Java Artemis ECS framework (ECS = Entity component system) and noticed something: There are two parts of it that require unique integer indices per class, not per object instance.
It needs an unique index for each class that extends Component (ComponentType serves this purpose) and for each class that extends EntitySystem (the SystemIndexManager static inside EntitySystem serves this purpose).
Both solutions more or less rely on a HashMap storing the relationship between a class and its index.
(EntitySystem class source and ComponentType source for reference)
Both are unsafe in multi threading usage, meaning that if you either add components of the same type to two separate entities in different threads or create EntitySystem objects in different threads, you get non-deterministic results.
First instinct was to replace the static ints for AtomicIntegers, yet that doesn't makes it thread safe since there is a whole method and a HashMap in the middle.
So I am asking how would I implement an unique index per class. It doesn't has to be unique in itself but unique indices for EntitySystems and unique indices for ComponentTypes separately. It has to be sequential since those are used for direct array access on various places (so I can't have an EntitySystem with an index of 3 million for example).
I could use synchronized methods and ConcurrentHashMap, following the same ideas of Artemis, but its possible that there is a lock-free way to do this? Or at least least intrusive than synchronizing related methods? As I mentioned, I'm using Java so there are quite a bit of threading stuff to use.