Options to make Java's ByteBuffer thread safe

前提是你 提交于 2019-11-27 23:44:06

A Buffer class could be made thread-safe ... in the sense that the individual operations were properly synchronized, etcetera. However, the API is not designed with multiple threads in mind, so this this is probably a waste of time.

The basic problem is that the individual operations on a Buffer are too fine-grained to be the unit of synchronization. An application cannot meaningfully synchronize at the level of the get and put operations, or flip, position and so on. Generally speaking, an application needs to perform sequences of these operations atomically in order to synchronize effectively.

The second problem is that if you do synchronize at a fine level, this is likely to add significant overheads on the method calls. Since the point of using the Buffer APIs is to do I/O efficiently, this defeats the purpose.


If you do need to synchronize thread access to a shared buffer, it is better to use external synchronization; e.g. something like this:

    synchronized (someLock) {
        buffer.getByte();
        buffer.getLong();
        ...
    }

Provided all threads that use a given buffer synchronize properly (e.g. using the same lock object), it doesn't matter that the Buffer is not thread-safe. Thread safety is managed externally to the buffer object, and in a more coarse-grained fashion.


As comments point out, you could also use ByteBuffer.slice() or buffer.asReadOnlyBuffer() to give you another buffer with the existing one as backing. However, the javadocs do not guarantee thread-safety in either case. Indeed, the javadocs for Buffer make this blanket statement:

Buffers are not safe for use by multiple concurrent threads. If a buffer is to be used by more than one thread then access to the buffer should be controlled by appropriate synchronization.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!