在以下假设场景中,出于更好地理解语言的愿望,int[] 引用是否需要 volatile?
public final class SO {
private int[] ar = new int[10]; // is volatile needed here?
private int idx = 0;
public synchronized int get( int i ) {
return ar[i];
}
public synchronized void append( final int val ) {
if ( idx == ar.length ) {
// array is too small, let's grow it
final int[] prev = ar;
ar = new int[ar.length+ar.length*20/100]
System.arrayCopy(prev, 0, ar, 0, prev.length);
}
ar[idx++] = val;
}
}
检索 int 的唯一方法是通过 synchronized 方法和修改 int[] 的唯一方法(包括创建new int[]) 也是通过同步方法完成的。
我不需要添加任何额外的同步吗?
最佳答案
不,不需要 volatile
因为它只能在同步方法中访问,所以它已经是线程安全的。您的代码中不需要进一步的线程安全。
关于java - 这里需要 volatile 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8928868/