java - Thread-Safety in a class -
please can have @ following code , advise whether classa thread-safe or not? if not thread-safe, please advise breaking?
public class classa { private list<player> players; public classa() { this.players = collections.synchronizedlist(new arraylist<player>()); } public player play(player player){ int score = 0; . . . if (players.contains(player)) { player = players.get(players.indexof(player)); player.addscore(score); } else { player.addscore(score); players.add(player); } return player; } }
no, not.
for example, 2 threads fail players.contains test , both add version of player (a better way add player every time set). also, unless player.addscore thread-safe, score adding subtly wrong.
synchronizing on whole play method (and reverting of players normal list) solve these problems.
Comments
Post a Comment