public final class StableValue {
private final int value;
private final String label;
public StableValue(int value, String label) {
this.value = value;
this.label = label; // 假设传入的 label 不会被外部修改
}
// 只提供读取方法,无任何修改操作
public int getValue() {
return value;
}
public String getLabel() {
return label;
}
}
上述代码中,StableValue 类被声明为 final,所有字段为 final 类型,且未暴露任何修改内部状态的接口,因此可在多线程环境中安全共享。
稳定值与线程安全的关系
特性
是否支持线程安全
说明
不可变性
是
状态无法更改,避免写冲突
共享访问
是
无需同步机制即可安全读取
内存可见性
是
final 字段保证初始化完成后对所有线程可见
graph TD
A[创建稳定值] --> B[发布到多个线程]
B --> C{线程读取值}
C --> D[无需加锁]
C --> E[无竞态条件]
public class StableExample {
private final int stableValue;
private volatile boolean flag = true;
public StableExample(int value) {
this.stableValue = value; // final赋值,线程安全
}
}
public class ImmutableExample {
private final int value;
private final String name;
public ImmutableExample(int value, String name) {
this.value = value;
this.name = name; // 构造期间完成初始化
}
public int getValue() { return value; }
public String getName() { return name; }
}
使用 `final` 字段可天然保证安全发布,因为 JVM 会禁止对 final 字段的写操作与构造函数外的读操作进行重排序。
public class StableValueHolder {
private final int stableValue;
public StableValueHolder(int value) {
this.stableValue = value; // 安全发布:final 保证可见性
}
public int getValue() {
return stableValue;
}
}
- 对象创建后其状态不可修改
- 所有字段使用 final 修饰
- 类声明为 final 防止子类破坏不变性
- 避免返回可变对象的引用
示例:Java 中的不可变类
public final class ImmutablePoint {
private final int x;
private final int y;
public ImmutablePoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
}
上述代码中,x 和 y 被声明为 final,确保初始化后不可更改。构造函数完成赋值后,对象状态永久固定,多个线程可同时读取而无需加锁。
// 计算滑动窗口内元数据访问频率均值
func CalculateStableScore(accessLog []int64, windowSec int) float64 {
now := time.Now().Unix()
threshold := now - int64(windowSec)
var count float64
for _, t := range accessLog {
if t > threshold {
count++
}
}
return count / float64(windowSec)
}