Reputation: 2016
I want to keep temporarily blocked users in a HashMap located in a singleton:
public enum BlockedUsersRepository {
REPOSITORY;
private final ConcurrentMap<String, User> blockedUsers = new ConcurrentHashMap<String, User>();
/* Static 'instance' method */
public static BlockedUsersRepository getInstance( ) {
return REPOSITORY;
}}
A user is getting into the map after a number of unsuccessful attempts to enter card number. I do it by launching the following methods from User class:
public void addBlockedUser(User user) {
blockedUsers.put(user.getEmail(),user);
}
public void removeBlockedUser(User user) {
blockedUsers.remove(user.getEmail());
}
The question is: do I undertake ENOUGH measures for thread-safety? How can I model concurrent access to the map in Terminal to make sure it really works or fails? Is it an appropriate approach at all, because I am afraid it's lame because the singletone plays a role of kinda a global variable accessible/modifiable by a number of User instances. I am new to the concurrency in Java and ask you to be lenient. Thank you.
Upvotes: 4
Views: 1443
Reputation: 5558
The enum as singleton is a threadsafe way of creating one. You have final
on the ConcurrentMap meaning no issues at that point.
ConcurrentHashMap can not be broken by concurrent writes.
A concurrent addBlockedUser/removeBlockedUser may lead to the user being blocked or unblocked. But imo both results are ok as you dont have a constraint saying a user has to be blocked for at least x seconds to be unblockable.
Problems that might be present but not directly threading issues.
Upvotes: 2