【发布时间】:2014-06-23 19:52:48
【问题描述】:
考虑一下代码 sn -p
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 内部状态的可见性。
【问题讨论】:
-
我想你可能想要AtomicReferenceArray
-
你的想法很准确。
标签: java arrays thread-safety volatile memory-visibility