byte array read and write in multithreads Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of byte array read and write in multithreads without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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?

Answer

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.

We are here to answer your question about byte array read and write in multithreads - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji