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.
Short answer: you can’t, without resorting to JNI.
Longer answer: There are no atomic updates in the ByteBuffer API. Moreover, the interaction of a ByteBuffer with memory is not rigorously defined. And in the Sun implementation, the methods used to access raw memory do not attempt to flush the cache, so you may see stale results on a multicore processor.
Also, be aware that
Buffer(and its subclasses such as ByteBuffer) is explicitly documented as not thread-safe. If you have multiple threads accessing the same buffer, you’re (1) relying on implementation behavior for absolute access, or (2) writing broken code for relative access.