gpt4 book ai didi

java - 我需要使 Singleton 类中的每个方法同步吗?

转载 作者:行者123 更新时间:2023-12-01 16:45:31 25 4
gpt4 key购买 nike

在下面的多线程编程示例中,Replacer类可以同时被多个线程访问,因此我将类设置为单例,并将getInstance()方法设置为同步。假设该方法也将被多个线程调用,我是否还需要使 replaceNum() 方法同步?

public class Replacer {

private static Replacer replacer = null;
private List<Integer> nums;

private Replacer() {
nums = new ArrayList<>();
}

public static synchronized Replacer getInstance() {
if (replacer == null) {
replacer = new Replacer();
}

return replacer;
}

// Do I need to make below method synchronized?
public void replaceNum(List<Integer> newNums) {
if (nums.size() > 0) {
nums.remove(nums.size() - 1);
}

nums.addAll(newNums);
}
}

最佳答案

该规则对于单例来说并不特殊。纯粹是:

  • 该方法是否需要支持多线程调用,以及
  • 如果多个线程在错误的时间调用它,它是否会执行任何会失败的操作

您的 replaceNum 的答案是“是的,它需要同步”(并且在方法级别是有意义的,因为基本上其中的所有内容都需要同步),因为它使用 ArrayList 的方法,不是线程安全的。如the Javadoc says :

Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.)

因此该方法需要同步对该 ArrayList 的访问。

给出这样的笼统声明,您必须假设没有一个方法是线程安全的,除非它明确指出它是线程安全的。 (类似地,除非类明确表示它是线程安全的,否则您必须假设它不是线程安全的。)

关于java - 我需要使 Singleton 类中的每个方法同步吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52281164/

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