Skip to content

Instantly share code, notes, and snippets.

@normanmaurer
Created March 2, 2014 20:39
Show Gist options
  • Select an option

  • Save normanmaurer/9313463 to your computer and use it in GitHub Desktop.

Select an option

Save normanmaurer/9313463 to your computer and use it in GitHub Desktop.
final static class SubPagePoolChunkCache<T> extends PoolChunkCache<T> {
SubPagePoolChunkCache(int size) {
super(size);
}
@Override
protected void initBuf(
PoolChunk<T> chunk, long handle, PooledByteBuf<T> buf, int reqCapacity, int normCapacity) {
chunk.initBufWithSubpage(buf, handle, reqCapacity, normCapacity);
}
}
final static class NormalPoolChunkCache<T> extends PoolChunkCache<T> {
NormalPoolChunkCache(int size) {
super(size);
}
@Override
protected void initBuf(
PoolChunk<T> chunk, long handle, PooledByteBuf<T> buf, int reqCapacity, int normCapacity) {
chunk.initBuf(buf, handle, reqCapacity, normCapacity);
}
}
abstract static class PoolChunkCache<T> {
private final Entry<T>[] entries;
int head;
int tail;
@SuppressWarnings("unchecked")
PoolChunkCache(int size) {
if ((size & -size) != size) {
// check if power of two as this is needed for bitwise operations
throw new IllegalArgumentException("size must be power of two");
}
entries = new Entry[size];
for (int i = 0; i < entries.length; i++) {
entries[i] = new Entry<T>();
}
}
protected abstract void initBuf(PoolChunk<T> chunk, long handle,
PooledByteBuf<T> buf, int reqCapacity, int normCapacity);
/**
* Add to cache if not already full.
*/
public boolean add(PoolChunk<T> chunk, long handle) {
Entry<T> entry = entries[tail];
if (entry.chunk != null) {
// cache is full
return false;
}
entry.chunk = chunk;
entry.handle = handle;
tail = nextIdx(tail);
return true;
}
/**
* Allocate something out of the cache if possible
*/
public boolean allocate(PooledByteBuf<T> buf, int reqCapacity, int normCapacity) {
Entry<T> entry = entries[head];
System.out.println("TINY " + entry.chunk);
if (entry.chunk == null) {
return false;
}
initBuf(entry.chunk, entry.handle, buf, reqCapacity, normCapacity);
entry.chunk = null;
entry.handle = -1;
head = nextIdx(head);
return true;
}
private int nextIdx(int index) {
// use bitwise operation as this is faster as using modulo.
return (index + 1) & entries.length -1;
}
static final class Entry<T> {
PoolChunk<T> chunk;
long handle;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment