public static ConcurrentHashMap<Integer,Session> USER_SESSIONS...
Everything works fine. But what if the system is allowed to be authorized two sessions with the same user ID? Well, that is roughly two PCs sitting under the same account, but different session. Tried to do so:
ConcurrentHashMap<Integer,List<Session>> USER_SESSIONS....
...............
private void addUser(Session session){
List<Session> userSessions = Server.USER_SESSIONS.get(session.mUserId);
if(userSessions==null){
userSessions = new List<Session>();
userSessions.add(session);
Server.USER_SESSIONS.put(session.getUserId(),userSessions);
}else{
userSessions.add(session);
}
}
private void removeUser(Session session){
List<Session> userSessions = Server.USER_SESSIONS.get(session.mUserId);
if(userSessions!=null){
userSessions.remove(session);
if(userSessions.size()==0)
{
Server.USER_SESSIONS.remove(session.getUserId());
}
}
}
.................
private void workWithUsers(int userId){
for(Session session : Server.USER_SESSIONS.get(userId))
{
<do it!>
}
}
Naturally, all these methods can be called from different threads, and I'm getting errors related to List . And this is natural, because while I have foreach-list session can be removed by removeUser from another thread. What to do? How to make so that-be at work with a list of all the threads List waited until it occupies the thread is finished with it? Yet done so :)
public static ConcurrentHashMap<Integer,ConcurrentHashMap<Session,Session>> USER_SESSIONS
Since ConcurrentHashMap thread safe. But I think it's crooked decision. Many thanks in advance for your help!
P.S: JRE 1.6
Please sorry for my English.
You could use List myList = Collections.synchronizedList(new ArrayList<String>());
if you don't want to use CopyOnWriteArrayList.
The only thing you need to have in mind is that it is mandatory to synchronized the code where you will be iterating over the list. You can see more info here: Collections.synchronizedList and synchronized
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With