Is there a Java data structure that is thread-safe for parallel threads writing to different parts of an array of fixed size? -
this i'm trying implement:
a (singleton) array of fixed size (say 1000 elements)
a pool of threads writing smaller (<=100) element blocks array in parallel
we guaranteed total writes threads in pool write <1000 elements, never have grow array.
the order of writes doesn't matter have contiguous, e.g thread1 populates array indexes 0-49, thread 3 indexes 50-149, thread 2 indexes 149-200
is there thread-safe data structure achieve this?
clearly, need synchronize "index manager" allocates in array indexes given thread needs write. there java data structure array can used this, without worrying thread safety?
you should able use atomicreferencearray. can safely update indexes or atomically update compareandset (though appears wont need that).
editing address akhil_mittal's question.
let's switch train of thought updating array updating individual fields. if update field in class write occur without word tearing, won't case write bits 1 thread , bits thread. same true array indexes.
however, if update field in class multiple threads, write 1 thread may not visible thread. because write may buffered on processor cache , flushed other processors. same true array write particular index. visible not guarantee happens-before ordering.
do still need concern thread safety
you need worry thread-safety same way need worry thread-safety non-volatile field. turns out dvk may not need worry writes being visible.
the point of answer explain array writes not thread-safe , using atomicreferencearray can protect delayed writes.
Comments
Post a Comment