使用Java中的方法同步?(Synchronized using for Methods in Java?)

我需要知道在java中使用Synchronized using for methods的用法。请参阅下面的代码一次。

代码:

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. }

以上代码用于method.is是否有可能使用上面的upDateUserStatus()同步获取java.util.ConcurrentModificationException

你能否告诉我上面的方法同步使用有什么用?

提前致谢。

I need to know about the usage of Synchronized using for methods in java.Please see the 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 synchronizedfor method.is there any possibility of getting java.util.ConcurrentModificationException using synchronized above upDateUserStatus()?

Can you please suggest me what is the use of synchronized using for above method?.

Thanks in Advance.

最满意答案

如果upDateUserStatus修改了存储在其userDetails对象中的播放器列表,则upDateAllUsersStatus循环的下一次迭代可能会抛出ConcurrentModificationException因为播放器列表在被迭代时被upDateAllUsersStatus修改(通过upDateAllUsersStatus )。 synchronized关键字没有帮助:它可以防止不同线程中的并发执行,但它不会阻止单个线程在同一个线程迭代时修改列表。

但是,你的代码看起来很奇怪,我怀疑它还有其他问题:你正在迭代存储在userDetails中的玩家列表,但你实际上没有对单个Player对象任何事情。 您只需在同一userDetails对象上多次调用upDateUserStatus 。 您是否打算使用upDateUserStatus来获取Player参数而不是UserDetails ? 如果是这样,那应该是安全的,因为单个Player (可能)不能修改其他玩家的列表。

If upDateUserStatus modifies the list of players stored in its userDetails object, the next iteration of the loop in upDateAllUsersStatus may throw a ConcurrentModificationException because the player list was modified (by upDateUserStatus) while it's being iterated (by upDateAllUsersStatus). The synchronized keyword doesn't help: that protects against concurrent execution in different threads, but it doesn't prevent an individual thread from modifying a list while that same thread is iterating it.

Your code looks strange, though, and I suspect it has other problems: you're iterating the list of players stored in userDetails, but you don't actually do anything with the individual Player objects. You just call upDateUserStatus multiple times on the same userDetails object. Did you intend for upDateUserStatus to take a Player argument instead of a UserDetails? If so, that should be safe, since an individual Player (presumably) can't modify the list of other players.

更多推荐