Tuesday, 15 July 2014

java - Volatile array - memory visibility of the elements -



java - Volatile array - memory visibility of the elements -

consider code snippet

class { private map<string, object> taskmap = new hashmap<>(); private volatile object[] tasksarray ; // assume happens on thread1 public void assigntasks() { synchronized(taskmap){ // set new tasks map // reassign values map new array tasksarray ( direct random access ) } } // assume invoked on thread2 public void action(){ int someindex = <init index value within tasksarray.length>; object[] localtasksarray = tasksarray; object onetask = localtasksarray[someindex]; // question : above operation safe respect memory visibility object onetask ? // possible onetask may appear null or in other state expected ? }

}

question : operation object onetask = localtasksarray[someindex]; safe respect memory visibility object onetask ? possible onetask may appear null or in other state expected ?

my thoughts these :

it possible thread2 may see onetask null or in state other expected. because , though taskarray volatile , , read of array ensure proper visibility of array , not ensure visibility of state internal object onetask.

the volatile keyword protects field taskarray reference object[]. whenever read or write field, have consistent ordering. however, doesn't extend array referenced nor objects array references.

most want atomicreferencearray instead.

java arrays thread-safety volatile memory-visibility

No comments:

Post a Comment