이 코드에서 동시성 오류를 찾을 수 있습니까? 이 코드는 한 스레드에서 완벽하게 작동하지만 두 스레드를 동시에 시작하고 addScore 메서드를 호출하면 트리 맵에 중복 요소가 추가됩니다.동시에 액세스 할 때 트리 맵의 중복 키
class User implements Runnable
{
private ScoreServiceImpl scoreService=ScoreServiceImpl.getInstance();
CountDownLatch latch;
public User(CountDownLatch latch)
{
this.latch = latch;
}
@Override
public void run() {
for(int i=0;i<5;i++) {
scoreService.addScore(3,Integer.parseInt(Thread.currentThread().getName()),ThreadLocalRandom.current().nextInt(50000));
}
System.out.println(scoreService.getHighScoreList(3));
}
}
그리고 만들 수있는 주요 방법 : 이것은 사용자 제작 요청을 시뮬레이션하기 위해 사용하고 코드가
public final class UserHighScore implements Comparable<UserHighScore>{
private final int userId;
private final int value;
public UserHighScore(int userId, int value) {
this.userId = userId;
this.value = value;
}
public int getUserId() {
return userId;
}
public int getValue() {
return value;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof UserHighScore)) {
return false;
}
UserHighScore userHighScore = (UserHighScore) obj;
return userHighScore.userId==userId;
}
@Override
public int compareTo(UserHighScore uh) {
if(uh.getUserId()==this.getUserId()) return 0;
if(uh.getValue()>this.getValue()) return 1;
return -1;
}
}
다음과 같이
comparedTO의 오버라이드를 가진 POJO이다 스레드는 다음과 같습니다 :
public static void main(String[] args) throws InterruptedException {
SpringApplication.run(RestclientApplication.class, args);
CountDownLatch latch = new CountDownLatch(1);
User user1=new User(latch);
User user2=new User(latch);
Thread t1=new Thread(user1);
Thread t2=new Thread(user2);
t1.setName("1");
t2.setName("2");
t1.start();
t2.start();
//latch.countDown();
}
중복 된 내용이지도에 어떻게 표시되는지 어떻게 알 수 있습니까? –
왜냐하면 내가 디버깅 할 때 동일한 userId에 대해 하나 이상의 키가있는지도를보고 목록을 인쇄 할 때 나는 그것을 볼 수 있습니다. – fgonzalez
나를 위해 userId 이상의 엔트리가 있어서는 안됩니다 (점수는 중요하지 않음).) 그러나 하나의 스레드에서만 잘 작동하지만 두 개에서는 작동하지 않습니다. – fgonzalez