gpt4 book ai didi

java - 我是否需要使用同步 getter 来使类线程安全?

转载 作者:太空宇宙 更新时间:2023-11-04 09:39:29 24 4
gpt4 key购买 nike

我有代码:

class Counter {
private int v;

public synchronized int inc() {
v = v + 1;
return v;
}

public int get() {
return v;
}
}

我最少需要什么(为了性能)&&(请不要使用并发包以及 java.lang 之外的其他包我现在只想学习 java 基础知识)

  1. make private volatile int v;
  2. make public int synchronized get() {...
  3. 没什么(一切都正常)

使上面的代码线程安全?

问题 Should getters and setters be synchronized?由于含糊不清,没有给出答案:

  1. It is a common mistake to assume that synchronization needs to be used only when writing to shared variables; this is simply not true.

    For each mutable state variable that may be accessed by more than one thread, all accesses to that variable must be performed with the same lock held. In this case, we say that the variable is guarded by that lock.

  2. Normally, you don't have to be so careful with primitives

所以我没有从那里找出原始 int 的答案

最佳答案

如果您希望该类线程安全(我认为这包括避免脏读),您应该选择第一个选项(make private volatile int v)。

第二个选项(public int synchronized get())也可以工作,但同步更重(->性能下降)。

第三个选项(什么都没有(一切正常))可能会在其他线程中产生脏读。

更多信息:Java volatile keyword

关于java - 我是否需要使用同步 getter 来使类线程安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56138521/

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