Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atomic read then write of part of a ByteBuffer in Java

I've got a ByteBuffer in java, and want to read, then conditionally modify that byte, e.g. with a method like:

public void updateByte(int index) {
    byte b = this.buffer.getByte(index);

    if (b == someByteValue) {
        this.buffer.setByte(index, someNewByte);
    }
}

How can I ensure that the reading then modifying of a byte happens atomically?

I don't want to synchronize the entire ByteBuffer or updateByte method, since I want multiple threads to be able to read/write different bytes of the buffer at the same time (i.e. updateByte can be called simultaneously by many threads as long as index is different).

The ByteBuffer I'm using isn't backed by a byte[], so bb.hasArray() == false in the above example.

like image 541
Dave Challis Avatar asked Dec 13 '22 05:12

Dave Challis


1 Answers

How about providing a set of explicit lock objects for portions of the ByteBuffer (portions could be very small, e.g. one word, or quite large, e.g. four quarter-buffers)?

When a thread wants to check and modify a byte, it must first acquire the lock for the appropriate portion, perform its work, then release the lock.

This would allow access to different portions of the data by multiple threads, without requiring global synchronization.

like image 137
DNA Avatar answered Dec 23 '22 20:12

DNA