Bha*_*kar 4 java arrays volatile thread-safety memory-visibility
考虑代码片段
class A {
private Map<String, Object> taskMap = new HashMap<>();
private volatile Object[] tasksArray ;
// assume this happens on thread1
public void assignTasks() {
synchronized(taskMap){
// put new tasks into map
// reassign values from map as a new array to tasksArray ( for direct random access )
}
}
// assume this is invoked on Thread2
public void action(){
int someindex = <init index to some value within tasksArray.length>;
Object[] localTasksArray = tasksArray;
Object oneTask = localTasksArray[someindex];
// Question : is the above operation safe with respect to memory visibility for Object oneTask ?
// is it possible that oneTask may appear null or in some other state than expected ?
}
Run Code Online (Sandbox Code Playgroud)
}
Object oneTask = localTasksArray[someindex];问题:就对象 oneTask 的内存可见性而言,该操作是否安全?oneTask 是否有可能显示为空或处于预期之外的其他状态?
我的想法是:
thread2 可能会被视为oneTasknull 或处于预期之外的某种状态。这是因为,即使taskArrayisvolatile和该数组的读取将确保数组本身的正确可见性,但这并不能确保对象内部状态的可见性oneTask。
该关键字仅保护对 Object[] 的引用的volatile字段。taskArray每当您读取或写入该字段时,它都会具有一致的顺序。但是,这不会扩展到引用的数组或数组引用的对象。
您很可能需要 AtomicReferenceArray。