gpt4 book ai didi

java - 下面类的线程安全是否会被破坏?我确信不可能,但只是想双重确定,因为它不容易测试

转载 作者:行者123 更新时间:2023-12-02 09:15:31 24 4
gpt4 key购买 nike

public class ThreadSafe implements ITaskCompletionListener {

private final Set<String> taskIds = new HashSet<String>();
private final Set<String> successfulIds = new HashSet<String>();
private final Set<String> cancelledIds = new HashSet<String>();
private final Set<String> errorIds = new HashSet<String>();

public ThreadSafe() {

}

// invoked concurrently
@Override
public void onCancel(String pTaskId) {
remove(pTaskId);
cancelledIds.add(pTaskId);
}

// invoked concurrently
@Override
public void onError(String pTaskId) {
remove(pTaskId);
errorIds.add(pTaskId);
}

// invoked concurrently
@Override
public void onSuccess(String pTaskId) {
remove(pTaskId);
successfulIds.add(pTaskId);
}

private void remove(String pTaskId) {
taskIds.remove(pTaskId);
}

}

最佳答案

来自HashSet文档:

Note that this implementation is not synchronized. If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally

所以不,你的代码不是线程安全的。并发访问任何方法都可能会产生奇怪的结果。

关于java - 下面类的线程安全是否会被破坏?我确信不可能,但只是想双重确定,因为它不容易测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6270544/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com