java - 在单例类中并发调用方法

标签 java concurrency singleton

假设我创建了一个名为 Calculator 的单例类,其方法 add 需要 2 个参数。

public class Calculator {
    private static Calculator instance = new Calculator();

    public static Calculator getInstance() {
        return instance;
    }

    public int add(int num1, int num2) {
        return num1 + num2;
    }
}

情况1: 既然是单例,如果我们并发调用add方法一万次会不会有问题?

情况 2: 如果这个类不是单例,而是一个普通的类,那么如果我做同样的事情,同时调用它会发生什么。

案例3: 现在,如果我的类不是单例,并且如果我的 add 方法是静态方法,那么内存将如何使用?

所以我的疑问是它的行为方式,给定场景中的 Java 内存模型是什么。哪一种有效或推荐?你能帮我理解这一点吗?

最佳答案

Case 1: Now since it is singleton, will there be any issues if we call the method add concurrently say 10,000's of times?

这里不存在并发问题:方法add没有任何副作用(它不会改变对象的状态)。

Case 2: If this class is not singleton, and a normal class then what will happen if I do the same thing, calling it concurrently.

与上一个答案相同。

Case 3: Now if my class is not singleton and if my add method is a static method then how the memory will be used?

与前两个相同的答案:无论该方法是否静态,每次使用两个参数调用它时,它都会对这些参数执行计算,而不改变实例/类的状态。

So my doubt is how it behaves, what is the Java memory model in the given scenarios. Which is efficient or recommended one? Can you please help me in understanding this?

再说一次,这并不重要。不会有并发问题,因为没有状态被修改。这与并发或 JMM 无关。

关于java - 在单例类中并发调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37129528/

相关文章:

java - 非线程安全标准集合的安全发布

java - 如何通过Thread访问Runnable对象?

string - 在Go中合并存储在 channel 上的多个 map (对相同键的值求和)

java - 在 Java (linux) 中获取一段时间内的平均系统 CPU 使用率

java - 支付回调后 Spring security 'Expected CSRF token not found...'

java - 从字符串中获取指定单词 php codeigniter

Java同步: atomically moving money across account pairs?

angular - 单实例 Angular 2+ 通知服务/错误处理程序

java - 安卓Java : Choose dynamically a subtype class

android - 共享库项目 Activity 的单一实例?