What options do I have to make a ByteBuffer thread safe? It is known that it is not thread safe as it safes position, limit and some(/all?) methods depend on this internal state.
For my purposes it will be sufficient if multiple read-threads are safe, but for other future visitors I would like to know what technics/tricks/traps I need to know to make it completely thread safe.
What I have in mind:
- Synchronizing or using ReadWrite locks for all methods. Probably the slowest approach (?)
- Subclassing ByteBuffer and avoid persisting thread-bound state like position etc. And throwing exceptions accordingly for all methods which need to use internal state. This would be the fastes. But are there any traps? (except that I'll have to read the directly mapped memory into heap memory ...)
What other tricks could I use? How would I e.g. implement a "clone bytes on read" with DirectBuffer - is it possible at all? Would probably slicing the full ByteBuffer (ByteBuffer.slice) be involved in one solution?
Update: What is meant in this question with "duplicate (while synchronized) to get a new instance pointing to the same mapped bytes"