Reputation: 4245
I allocated a very large byte array for threads to read and write bytes in the array. Write operation is to assign the new byte directly to the value in the array like byte[i] = byte2;
I can ensured that there will be no conflict for those operation (same section in the byte array will not write by 2 different threads. when a section in reading, no write operation will perform by other threads). My concern is will the modification to array been instantly available to other threads. I know there might be memory fence, which other threads may still read the old values in the array.
If the problem exists, how to avoid? will volatile byte[] store;
works in this circumstance?
Upvotes: 3
Views: 1189
Reputation: 533880
will the modification to array been instantly available to other threads.
not without a write fence for the writer and a read fence for the reader.
I know there might be memory fence, which other threads may still read the old values in the array.
You will need to use one of those for the reader and writer (not one per byte, one per operation)
will volatile byte[] store; works in this circumstance?
It won't do what you want, though it will slow down your application. When you do
store[i] = b;
This added a read fence as you are reading the store
reference to the byte[].
The best solution is to use Unsafe to have complete control over these read write operations. See the code for AtomicIntegerArray.
However, without going down that road you can do a dummy operation like this which is not as efficient/elegant, but a lot simpler to implement.
private final AtomicBoolean fence = new AtomicBoolean();
public void readFence() {
fence.get();
}
public void writeFence() {
fence.set(true);
}
For this to work, you must do a writeFence()
after all writes, and a readFence()
before all reads.
If you are going down the more low level route you might find using off heap memory an advantage. Off heap memory can store very large (TBs) amounts of data without impacting the GC.
Upvotes: 4
Reputation: 4917
You can use SynchronizedList
for this
Example
byte[] c = new byte[];
List list = Collections.synchronizedList(Arrays.asList(c));
It will be thread-safely
Upvotes: -2