Synchronized using for Methods in Java? -
i need know usage of synchronized using methods in java.please see below code once.
code :
public void updateallusersstatus(userdetails userdetails) { for(player p : userdetails.getplayerslist()) { if(p != null) { string userid = p.getuserid(); updateuserstatus(userid ); } } } public synchronized void updateuserstatus(string name) { //here update status of user in db. }
the above code used synchronized
for method.is there possibility of getting java.util.concurrentmodificationexception using synchronized above updateuserstatus()?
can please suggest me utilize of synchronized using above method?.
thanks in advance.
if updateuserstatus
modifies list of players stored in userdetails
object, next iteration of loop in updateallusersstatus
may throw concurrentmodificationexception
because player list modified (by updateuserstatus
) while it's beingness iterated (by updateallusersstatus
). synchronized
keyword doesn't help: protects against concurrent execution in different threads, doesn't prevent individual thread modifying list while same thread iterating it.
your code looks strange, though, , suspect has other problems: you're iterating list of players stored in userdetails
, don't do individual player
objects. phone call updateuserstatus
multiple times on same userdetails
object. did intend updateuserstatus
take player
argument instead of userdetails
? if so, should safe, since individual player
(presumably) can't modify list of other players.
java
No comments:
Post a Comment