Atomic read then write of part of a ByteBuffer in

2020-07-17 06:27发布

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.

7条回答
Bombasti
2楼-- · 2020-07-17 07:31

I think putting the critical section of code under a lock control should be the clean solution. However do not use synchronization directly if your use-case has high number of reads compared to writes. I would suggest that you make use of ReentrantReadWriteLock as part of your solution. In function where you modify ByteBuffer you take writeLock().lock() and then your code. And while reading make use of readLock().lock(). You can read more on read-write lock on mentioned link. Basically it will allow concurrent reads but not concurrent writes and while write is happening read threads wait

查看更多
登录 后发表回答