Home » Software Development » Off Heap concurrent counter

About Ashkrit Sharma

Ashkrit Sharma
Pragmatic software developer who loves practice that makes software development fun and likes to develop high performance & low latency system.

Off Heap concurrent counter

Concurrent counter are part of almost every system, it is used to collect data, thread synchronization etc. Java has good support of heap based counter.

There could be use case when you need counter that can be shared between processor.

How to build inter process counters


This is first option that comes to mind, database sequence is counter that can be used by multiple process. All concurrency is handled by database. It is good option for starter but we know types of overhead(Network,Locks etc) you get with database. Only Larry Elision will be happy about it, not you!

Some Server

You could develop some server/middleware that provides such type of service. This option will still have network latency,marshal/unmarshal overhead.

Memory Mapped file

You could use memory mapped file to do this. I got idea from looking at thread-safe-interprocess-shared-memory-in-java presentation from PeterLawrey.

Challenges involved in multi process counter.

Data visibility

Changes done by one process should be visible to all the process. This problem can be solved by using memory mapped file. Operating System gives guarantee about it and java memory model supports it to make is possible.

Thread safety

Counters is all about multiple writers , so thread safety becomes big problem. Compare-and-swap is one option to handles multiple writers. Is it possible to use CAS for off heap operation ? yes it is possible to do that , welcome to Unsafe. By using using Memorymapped & Unsafe it is possible to use CAS for Off heap operation.

In this blog i will share my experiment of Memory mapped using CAS.


How to get memory address

MappedByteBuffer is using DirectByteBuffer, which is off heap memory. So it is possible to get virtual address of memory and use unsafe to perform CAS operation. Lets look at the code.

FileChannel fc = new RandomAccessFile(fileName, "rw").getChannel();
// Map 8 bytes for long value.
mem = fc.map(FileChannel.MapMode.READ_WRITE, 0, 8);
startAddress = ((DirectBuffer) mem).address();

Above code create memory mapped file of 8 bytes and get the virtual address. This address can be be used to read/write content of memory mapped file.

How to Write/read in thread safe manner

public boolean increment() {
		long orignalValue = readVolatile(startAddress);
		long value = convert(orignalValue);
		return UnsafeUtils.unsafe.compareAndSwapLong(null, 
				startAddress,orignalValue, convert(value + 1));

	public long get() {
		long orignalValue = readVolatile(startAddress);
		return convert(orignalValue);

	// Only unaligned is implemented
	private static long readVolatile(long position) {
		if (UnsafeUtils.unaligned()) {
			return UnsafeUtils.unsafe.getLongVolatile(null, position);
		throw new UnsupportedOperationException();

	private static long convert(long a) {
		if (UnsafeUtils.unaligned()) {
			return (UnsafeUtils.nativeByteOrder ? a : Long.reverseBytes(a));
		throw new UnsupportedOperationException();

Important function to look are readVolatile and increment readVolatile reads directly from memory and increment is using unsafe to perform CAS on the address obtained from MemoryByteBuffer.


Some performance numbers from my system. Each thread increments counter 1 Million times.


Performance of counter is decent , as number of threads are increased CAS failures starts to happen and performance starts to degrade. Performance of these counter can be improved by having multiple segment to reduce write contention. I will write about it in next blog.


  • Memory mapped file is very powerful, it can be used to developed lot of things like off heap collections, IPC, Off heap thread coordination etc.
  • Memory mapped file opens gates for GC less programming.

All the code used in this blog is available on github.

Reference: Off Heap concurrent counter from our JCG partner Ashkrit Sharma at the Are you ready blog.
(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
Email address:

Leave a Reply

Be the First to Comment!

Notify of