ByteBuffer (int bufferSize) { if (heapCapacityBytes == 0) { return null; } while (true) { long used = heapBytesUsed.get(); if (used + bufferSize > heapCapacityBytes) { return null; } if (heapBytesUsed.compareAndSet(used, used + bufferSize)) { try { ByteBuffer heapByteBuffer = ByteBuffer.allocate(bufferSize); statistics.pageAllocatedHeap(bufferSize); return heapByteBuffer; } catch (OutOfMemoryError e) { LOG.warnWithDebug("OutOfMemory: can't allocate heap buffer[size: " + bufferSize + "b] -> skip, will try to deal without it", e); heapBytesUsed.addAndGet(-bufferSize); return null; } } } }