[SOLVED] Noob question about synchronization

Hi guys

Sorry if this question is super noobish :slightly_smiling_face:

I have a HostedConnectionService :

public class MyHostedService extends AbstractHostedConnectionService {
...
}

and a game system :

public class MySystem extends AbstractGameSystem { // AbstractGameSystem is from SiO2
...
   public MyObject getMyObject(EntityId eId) {
          return myContainer.getObject(eId);
   }
...
}

inside the MySystem class, I have an EntityContainer

private class MyContainer extends EntityContainer<MyObject> {
...
}

I want to call the getMyObject() method on MySystem from within MyHostedService, the thing is MyHostedService is running inside networking thread and it is possible while calling getMyObject() a new entity be added to MyContainer. Note that EntityContainer is keeping objects in a regular HashMap so I need to do some synchronization.

Will adding a synchronized keyword to getMyObject() method do the job? Or I should use a regular EntitySet with a ConcurrentHashMap instead of using an EntityContainer?

You need to use synchronized also on the method that add/remove from the hashmap.
Note: synchronized has some downsides, it is generally a good idea to avoid it if possible, ConcurrentHashMap is preferable.

1 Like

…that seems odd.

Maybe something is backwards?

1 Like

yes, like you said you need synchronized keyword and it need to be placed on all methods that use it. Like Riccardo said there are already Collections that have synchronization like inside it.

This collections usually have “Concurrent” words in it, but not always. LinkedBlockingQueue was good too if i remember. Anyway if its about HashMap ConcurrentHashMap is fine.

im not sure about SiO2 System class, but as a side note i can say that you can always create Callbacks to manage all in one loop like app.enqueue() that should work from different threads.

1 Like

Still, I say there is probably a design problem. I can’t think of a valid case where it would be necessary to lookup a system-specific object from the network handler.

It’s a sign that something is backwards or that some process is bypassing the ES in some funky way. Both will come back to haunt you later.

1 Like

Guys thanks so much for your helps.

@pspeed yep, I agree that seems odd, also as I remember I have not seen a similar case in any of your examples either.
Thanks so much for the heads up. I am going to rethink my design. I will ask it in a new thread with more details in case I was not able to come up with a decent solution. Thank you again :slightly_smiling_face:

2 Likes