考虑代码片段
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 ?
}
}
问题:Object oneTask = localTasksArray[someindex];
对于 Object oneTask 的内存可见性,操作是否安全?oneTask 是否可能显示为 null 或处于预期之外的其他状态?
我的想法是:
thread2 可能会oneTask
被视为 null 或处于预期之外的某种状态。这是因为,即使taskArray
是volatile
,并且对该数组的读取将确保数组本身的正确可见性,但这并不能确保对象内部状态的可见性oneTask
。