ArrayList concurrency through socket connections

I have a problem. I suppose this has something to do with concurrency or thread synchronization, although I can't put my finger on just what is happening.

Here is my description of the data flow for our FriendRequestList object.

On the client side, we send a friendโ€™s request to another user (employee). Therefore, we send a request and add our own username to our User.incFriendReq -list. Instance is an ArrayList for reference only.

So, now we send a request to the server to get our own friend request list ( FriendRequestList.java ).

So now the problem. If I use this code below, the user will not see the friendโ€™s request before he stops his connection (logout), which closes the connection. When he logs in, he will only see the request in his list.

Server Side Code:

... Worker.java ...

 private Object getFriendRequests() { User me = Data.getUser(myUserName); if ( me == null ) { return new NoSuchUserException(); // Don't worry about it ;) } return new FriendRequestList(me.getFriendReq()); } 

... User.java ...

 private List<String> incFriendReq; public List<String> getFriendReq() { return incFriendReq; } 

Client side

... Communication.java ...

 public FriendRequestList getRequests() { sendObject(new GetRequests()); return inputHandler.containsRequests(); } 

... MessageListener.java ...

 public void run() { ... FriendRequestList requests = communication.getRequests(); update(requestList, requests); // Here we have the problem. requests.size is never different from 0 } 

However, if I update Worker.java to do this instead:

 private Object getFriendRequests() { User me = Data.getUser(myUserName); if ( me == null ) { return new NoSuchUserException(); } return new FriendList(me.getFriends().stream().collect(Collectors.toList())); } 

At that moment, when another user asks for my friendship, I see a request in my list. What gives? It sounds to me just like the underlying data structure is not being updated, race conditions or something else. But the fix is โ€‹โ€‹how I retrieve server-side data using a stream.

Please explain to someone how it will be done in Java 7 before threads solve my interesting problem for me.

On note

I want to add that users are placed inside LinkedBlockingDeque and retrieve a share for workers from the Data object.

+5
source share
1 answer

It seems to me that returning the incFriendReq list directly to getFriendReq is one of the sources of your problem. When you use java 8 and pass this list to a new list, you just make a copy, so there is no useful addition. If so, your server code should also work using new ArrayList<>(me.getFriends()) .

I would make sure that all calls to the list are correctly synchronized and that you know where and when this list is mutated.

0
source

All Articles