MicroEyes
MicroEyes

Reputation: 3742

Does function returning only value as object from ConcurrentHashMap<K,V> need to be synchronized?

I have a below class:

Class GameDataHandler {
    private final ConcurrentHashMap<Long, GameData> m_lstUpcomingGameData = new ConcurrentHashMap<>();

    public GameDataHandler () {
       s_instance = this;
    }


    public static IGameData GetGameDataById(long a_gameId) {
        return s_instance.m_lstUpcomingGameData.get(a_gameId);
    }    
}

In my case, GetGameDataById() function is being called by multiple threads. Do I need to put synchronized on my method?

I know that the ConcurrentHashMap is thread-safe, but I am not sure about GetGameDataById() function itself.

Upvotes: 0

Views: 29

Answers (1)

xingbin
xingbin

Reputation: 28289

No, you do not need that. Make it synchronized leads to only one thread can execute the method at the same time, that does not make sense.

But you might need remove the static modifier of method GetGameDataById since the Map is non-static.

Upvotes: 1

Related Questions