gpt4 book ai didi

java - 100% 不可变,但仍然不是线程安全的

转载 作者:行者123 更新时间:2023-12-02 10:42:17 25 4
gpt4 key购买 nike

我读过很多有关线程安全的内容。在我的多线程程序的某些部分,我更喜欢尝试不变性。在得到不正确的结果后,我注意到我的不可变对象(immutable对象)不是线程安全的,尽管它是 100% 不可变的。如果我错了,请纠正我。

public final class ImmutableGaugeV4 {
private final long max, current;

public ImmutableGaugeV4(final long max) {
this(max, 0);
}

private ImmutableGaugeV4(final long max, final long current) {
this.max = max;
this.current = current;
}

public final ImmutableGaugeV4 increase(final long increment) {
final long c = current;
return new ImmutableGaugeV4(max, c + increment);
}

public final long getCurrent() {
return current;
}

public final long getPerc() {
return current * 100 / max;
}

@Override
public final String toString() {
return "ImmutableGaugeV4 [max=" + max + ", current=" + current + "](" + getPerc() + "%)";
}
}

啊啊啊

public class T4 {
public static void main(String[] args) {
new T4().x();
}

ImmutableGaugeV4 g3 = new ImmutableGaugeV4(10000);

private void x() {
for (int i = 0; i < 10; i++) {
new Thread() {
public void run() {
for (int j = 0; j < 1000; j++) {
g3 = g3.increase(1);
System.out.println(g3);
}
}

}.start();
}
}
}

有时我会得到正确的结果,但大多数时候我不会得到正确的结果

ImmutableGaugeV4 [max=10000, current=9994](99%)
ImmutableGaugeV4 [max=10000, current=9995](99%)
ImmutableGaugeV4 [max=10000, current=9996](99%)
ImmutableGaugeV4 [max=10000, current=9997](99%)

这个不可变对象(immutable对象)有什么问题?在不使用内在锁的情况下,要使其线程安全,缺少什么?

最佳答案

都不是

final long c = current;
return new ImmutableGaugeV4(max, c + increment);

也不

g3 = g3.increase(1);

是线程安全的。这些复合操作不是原子的。

我建议阅读 Brian Goetz 撰写的“Java 并发实践”:专门讨论复合操作和“发布和转义”问题的章节。

关于java - 100% 不可变,但仍然不是线程安全的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52853821/

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