Agrona's Threadsafe Offheap Buffers
Agrona's Threadsafe Offheap Buffers
Learn more about Agrona's Threadsafe offheap buffers, and how to increase performance.
Join the DZone community and get the full member experience.Join For Free
Sensu is an open source monitoring event pipeline. Try it today.
This blog post continues my ongoing series on the Agrona library by explaining how we offer easy access to offheap memory for threadsafe operations. I should probably caveat before we move on that this is a fairly advanced topic and I don't attempt to explain concepts such as memory barriers - merely outline the features of the API.
The Deficiencies of ByteBuffer
Java provides a byte buffer class to wrap both offheap and onheap memory. Bytebuffers are specifically used in the Java networking stack as a places for data to be read from or written into.
So what's the problem with bytebuffers? Well because they're targeted at their usecase they don't offer support for things like atomic operations. If you want to write an offheap data structure that's concurrently accessed from different processes then byte buffers don't address your needs. An example of the kind of library that you might want to write would be a message queue that one process will read from and another will write to.
DirectBuffer- the top level interface that provides the ability to read values from the buffer.
DirectBufferadding operations for writing to the buffer.
AtomicBuffer- No it's not a nuclear powered
MutableDirectBuffer! This interface adds atomic operations and compare-and-swap semantics.
UnsafeBuffer- a default implementation. The name unsafe isn't supposed to imply that the class shouldn't be used, merely that its backing implementation uses
The decision to split up the buffers, rather than have a single class is motivated by wanting to restrict the access that different system components have to buffers. If a class only needs to read from a buffer, then it shouldn't be allowed to introduce bugs into the system by being allowed to mutate the buffer. Similarly components that are designed to be single threaded shouldn't be allowed to use the Atomic operations.
Wrapping Some Memory
In order to be able to do anything with a buffer, you need to tell it where the buffer is to begin with! This process is called wrapping the underlying memory. All the methods for wrapping memory are called
wrap and its possible to wrap a
DirectBuffer. You can also specify an offset and length with which to wrap the data structures. For example here is how you wrap a
final int offset = 0; final int length = 5; buffer.wrap(new byte[length], offset, length);
There is one more option for wrapping - which is an address to a memory location. In this case the method takes the base address of the memory and its length. This is to support things like memory allocated via
sun.misc.Unsafe or for example a malloc call. Here's an example using
final int length = 10; final long address = unsafe.allocateMemory(length); buffer.wrap(address, length);
Wrapping the memory also sets up the capacity of the buffer, which can be accessed via the
So now you've got your buffer of off-heap memory you can read from and write to it. The convention is that each getter starts with the word
get and is suffixed with the type of the value that you're trying to get out. You need to provide an address to say where in the buffer to read from. There's also an optional byte order parameter. If the byte order isn't specified then the machine's native order will be used. Here's an example of how to increment a long at the beginning of the buffer:
final int address = 0; long value = buffer.getLong(address, ByteOrder.BIG_ENDIAN); value++; buffer.putLong(address, value, ByteOrder.BIG_ENDIAN);
As well as primitive types its possible to get and put bytes from the buffers. In this case the buffer to be read into or from is passed as a parameter. Again a
DirectBuffer is supported. For example, here's how you would read data into a
final int offsetInBuffer = 0; final int offsetInResult = 0; final int length = 5; final byte result = new byte[length]; buffer.getBytes(offsetInBuffer, result, offsetInResult, length, result);
long values can also be read or written with memory ordering semantics. Methods suffixed with
Ordered guarantee that they will eventually be set to the value in question, and that value will eventually be visible from another thread doing a volatile read on the value. In other words
putLongOrdered automatically performs a store-store memory barrier.
put*Volatilefollow the same ordering semantics as reads and writes to variables declared with the volatile keyword would in Java.
More sophisticated memory operations are also possible via the
AtomicBuffer. For example there is a
compareAndSetLong which will atomically set an updated value at a given index, given the existing value there is an expected value. The
getAndAddLong method is a completely atomic way of adding at a given index.
Nothing in life is free, there is a caveat to all this. These guarantees are non-existent if your index isn't word-aligned. Remember, its also possible to tear writes to values over word boundaries on some weak memory architectures, such as ARM and Sparc, seestack overflow for more details on this kind of thing.
Bounds checking is one of those thorny issues and topics of ongoing debate. Avoiding bounds checks can result in faster code, but introduces the potential to cause a segfault and bring down the JVM. Agrona's buffers give you the choice to disable bounds checking through the commandline property
agrona.disable.bounds.checks, but bounds check by default. This means that their use is safe, but if application profiling of tested code determines that bounds checking is a bottleneck then it can be removed.
Agrona's buffers allow us to easily use offheap memory without the restrictions that Java's existing bytebuffers impose upon us. We're continuing to expand the library which can be downloaded from maven central.
Thanks to Mike Barker, Alex Wilson, Benji Weber, Euan Macgregor, Matthew Cranman for their help reviewing this blog post.
Published at DZone with permission of Richard Warburton , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.