Skip to content

Instantly share code, notes, and snippets.

@mariofusco
Created September 13, 2023 07:28
Show Gist options
  • Save mariofusco/c98f06dcfff5d5425df5c698cd2807b9 to your computer and use it in GitHub Desktop.
Save mariofusco/c98f06dcfff5d5425df5c698cd2807b9 to your computer and use it in GitHub Desktop.
private static final BufferRecyclerPool STRIPED_JCTOOLS_INSTANCE = new StripedPool(JCToolsPool::new, 4);
private static final BufferRecyclerPool STRIPED_LOCK_FREE_INSTANCE = new StripedPool(BufferRecyclerPool.LockFreePool::nonShared, 4);
static class StripedPool implements BufferRecyclerPool {
private static final long PROBE = getProbeOffset();
private final int mask;
private final BufferRecyclerPool[] pools;
public StripedPool(Supplier<BufferRecyclerPool> poolFactory, int slots) {
this.mask = slots-1;
this.pools = new BufferRecyclerPool[slots];
for (int i = 0; i < slots; i++) {
this.pools[i] = poolFactory.get();
}
}
private static long getProbeOffset() {
try {
return UnsafeAccess.UNSAFE.objectFieldOffset(Thread.class.getDeclaredField("threadLocalRandomProbe"));
} catch (NoSuchFieldException e) {
throw new UnsupportedOperationException(e);
}
}
private int index() {
return probe() & mask;
}
private int probe() {
int probe;
if ((probe = UnsafeAccess.UNSAFE.getInt(Thread.currentThread(), PROBE)) == 0) {
ThreadLocalRandom.current(); // force initialization
probe = UnsafeAccess.UNSAFE.getInt(Thread.currentThread(), PROBE);
}
return probe;
}
@Override
public BufferRecycler acquireBufferRecycler() {
return pools[index()].acquireBufferRecycler();
}
@Override
public void releaseBufferRecycler(BufferRecycler recycler) {
pools[index()].releaseBufferRecycler(recycler);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment