astronauthere
astronauthere

Reputation: 123

Thread-Safety in a class

Please can you have a look at the following code and advise whether ClassA is thread-safe or not? If it is not thread-safe, could you please advise where it is 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;

}

}

Upvotes: 1

Views: 99

Answers (1)

phihag
phihag

Reputation: 287755

No, it is not.

For example, two threads could fail the players.contains test and both add their version of a player (a better way would just add the player every time to a set). Also, unless Player.addScore is thread-safe, score adding could be subtly wrong.

Synchronizing over the whole play method (and reverting of players to a normal list) would solve these problems.

Upvotes: 3

Related Questions