DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • What Are Protocol Buffers?
  • How to do Memory Management for DataWeave
  • How Milvus Implements Dynamic Data Update and Query
  • Principles to Handle Thousands of Connections in Java Using Netty

Trending

  • Build a Serverless App Fast With Zipper: Write TypeScript, Offload Everything Else
  • How To Validate Archives and Identify Invalid Documents in Java
  • How To Verify Database Connection From a Spring Boot Application
  • Analyzing Stock Tick Data in SingleStoreDB Using LangChain and OpenAI's Whisper
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Agrona's Threadsafe Offheap Buffers

Agrona's Threadsafe Offheap Buffers

Learn more about Agrona's Threadsafe offheap buffers, and how to increase performance.

Richard Warburton user avatar by
Richard Warburton
·
Apr. 24, 15 · Analysis
Like (0)
Save
Tweet
Share
7.67K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Agrona's Buffers

Agrona provides several buffer classes and interfaces in order to overcome these deficiencies. These buffers are used by both theAeron and SBE libraries.

  1. DirectBuffer - the top level interface that provides the ability to read values from the buffer.
  2. MutableDirectBuffer - extends DirectBuffer adding operations for writing to the buffer.
  3. AtomicBuffer - No it's not a nuclear powered MutableDirectBuffer! This interface adds atomic operations and compare-and-swap semantics.
  4. 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 sun.misc.Unsafe.

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 byte[],ByteBuffer or DirectBuffer. You can also specify an offset and length with which to wrap the data structures. For example here is how you wrap a byte[].

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 Unsafe.

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 capacity() method.

Accessors

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 byte[], ByteBuffer or DirectBuffer is supported. For example, here's how you would read data into abyte[].

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);

Concurrent Operations

int and 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. get*Volatile and 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

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.

Conclusions

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.

Buffer (application) Memory (storage engine)

Published at DZone with permission of Richard Warburton, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • What Are Protocol Buffers?
  • How to do Memory Management for DataWeave
  • How Milvus Implements Dynamic Data Update and Query
  • Principles to Handle Thousands of Connections in Java Using Netty

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: