Slab: 保证JVM的堆内存对齐

Slab: guaranteed heap alignment on the JVM

随着时间的推移,CPU时钟频率已经相当快,但内存速度未能赶上。为了充分利用CPU,考虑内存数据结构对齐是很重要的,这样能够让CPU缓存(On-CPU Cache)赶上来,换句话说,需要良好的引用局部性。

不幸的是,Java平台的抽象内存分配方式使得它很难保证你的内存分配的性能。在大多数情况下,这是一个幸运:因为饿你不需要担心你自己去管理内存!但是有时你需要实现一个算法,以保证Java在这方面的不足。

开源Slab提供简单的解决方案。



// Define your DataType
public interface GameEvent extends Cursor {
public int getId();
public void setId(int value);
public long getStrength();
public void setStrength(long value);
}

// Create an allocator for your DataType
Allocator eventAllocator = Allocator.of(GameEvent.class);

// Allocate 100 off heap GameEvent instances - sequentially in memory
GameEvent event = eventAllocator.allocate(100);

// Move to the index of the instance that you want to read from or write to
event.move(1);

// set and get values like a normal POJO
event.setId(6);
assertEquals(6, event.getId());

啥是 内存数据结构对齐 ?