Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List in ConcurrentHashMap

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.

like image 793
GPPSoft Avatar asked Oct 21 '22 19:10

GPPSoft


1 Answers

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

like image 139
hveiga Avatar answered Oct 23 '22 10:10

hveiga