Question about Guava MultiMap & concurrency

Hi guys

This is not a JME-related question!

I am using MultiMap implementation from google guava. In Javadoc of

Multimaps.newSetMultimap( Map<K, Collection<V>> map, final Supplier<? extends Set<V>> factory) 

it says

In my case, only one thread will write to the map and other threads will only read from it. Do I still need to use synchronizedMultimap in this case?

This is how I create the Map:

Multimaps.newSetMultimap(new ConcurrentHashMap<>(), ConcurrentHashMap::newKeySet);

Thanks in advance!

If it is internally using Java’s HashMap in any way then updates from one thread can cause reads from another to enter an endless loop.

But if both of your Multimap-internal data structures are concurrent hashmaps then I think you are ok.

What is the use-case? Perhaps there is a better way? Is the map updated constantly or only periodically?

1 Like

For mob grid. Map updates every 1 second or so but reading happens every frame and contains the list of mob entities in a grid cell (cell size is 3x3). MobGridSystem looks for mobs and periodically updated the mob location on the grid. Then for example in the steering system, I am going to look for nearby entities. Also when placing an object on the ground I will check if there is no mob over there. Reading can happen from the networking thread or AI thread.

I can’t remember… are you a Zay-ES user or not?

There are reasons to do things the way you are and using the concurrent* classes should mean that you are ok.

But note that in my own code, I include the grid cell ID right in the position component such that it is always set at the same time as the position and I can query for it through the ES, build entity sets around filters, etc…

That may not work in your case but I thought I would mention it. There is no separate update process in that case.

1 Like

Yes, I am a Zay-ES user.

Good idea. I think I may put it in a separate component (GridPosition for example) rather than the BodyPosition component (as it is handled especially via transition buffer and is not like a regular component) so I won’t send unnecessary updates to the client.

Thanks so much for the help.

Yes, in my case I have a separate position from BodyPosition… since BodyPosition’s idea of position depends on precisely when you ask. I use it only for network synching.

…I have an additional position for recording where things are persistently and that’s the one with the grid.

…but yeah, on the server, if you want a grid-based index then you will have to do something more immediate. (In my case, my physics engine is already managing that grid and I can just ask it.)

1 Like