java and threads: very strange behaviour
Posted
by Derk
on Stack Overflow
See other posts from Stack Overflow
or by Derk
Published on 2010-04-21T10:59:34Z
Indexed on
2010/04/21
11:53 UTC
Read the original article
Hit count: 314
java
|thread-safety
private synchronized Map<Team, StandingRow> calculateStanding() {
System.out.println("Calculate standing for group " + getName());
Map<Team, StandingRow> standing = new LinkedHashMap<Team, StandingRow>();
for (Team team : teams) {
standing.put(team, new StandingRow(team));
}
StandingRow homeTeamRow, awayTeamRow;
for (Match match : matches.values()) {
homeTeamRow = standing.get(match.getHomeTeam());
awayTeamRow = standing.get(match.getAwayTeam());
System.out.println("Contains key for " + match.getHomeTeam() + ": " + standing.containsKey(match.getHomeTeam()));
System.out.println("Contains key for " + match.getAwayTeam() + ": " + standing.containsKey(match.getAwayTeam()));
}
}
This is my code. matches contains 6 elements, but the problem is that after two matches no keys are anymore found in the standing map.
The output is for example
Contains key for Zuid-Afrika: true
Contains key for Mexico: true
Contains key for Uruguay: true
Contains key for Frankrijk: true
Contains key for Zuid-Afrika: false
Contains key for Uruguay: false
Contains key for Frankrijk: false
Contains key for Mexico: false
Contains key for Mexico: false
Contains key for Uruguay: false
Contains key for Frankrijk: false
Contains key for Zuid-Afrika: false
This is in a threaded environment, but the method is synchronized so I thought that this would not give a problem? I have also a simple unit test for this method and that works well.
© Stack Overflow or respective owner