akarnokd
akarnokd

Reputation: 69997

How to fill a byte array from multiple threads safely?

Is there a way to safely populate a byte array from multiple threads (e.g. first thread fills the first half, the second thread fills the second half using System.arraycopy) without synchronizing on the array itself using Java 6 or 7? The jsr166 related libraries only contain int arrays (AtomicIntegerArray, ParallelIntegerArray).

Upvotes: 1

Views: 2345

Answers (2)

crunchdog
crunchdog

Reputation: 13468

Oh this sounds like a good way to get a headache. :) I think I would go for one array per thread, and later join them.

Upvotes: 0

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

Yes it works. Writing to an array location does not interfere with nearby locations. However, you need to make sure that all threads have finished before reading (a happens-before relationship). The fact that you are using arrays makes no difference.

Upvotes: 6

Related Questions