Merge pull request #7166 from eclipse/jetty-10.0.x-6974-ByteBufferPool

Issue #6974 - improvements & fixes to ByteBufferPool implementations (#7017)
This commit is contained in:
Lachlan 2021-12-03 14:46:16 +11:00 committed by GitHub
commit 9b501022d5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 439 additions and 137 deletions

View File

@ -16,6 +16,7 @@ package org.eclipse.jetty.io;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
@ -27,16 +28,24 @@ abstract class AbstractByteBufferPool implements ByteBufferPool
private final int _factor;
private final int _maxQueueLength;
private final long _maxHeapMemory;
private final AtomicLong _heapMemory = new AtomicLong();
private final long _maxDirectMemory;
private final AtomicLong _heapMemory = new AtomicLong();
private final AtomicLong _directMemory = new AtomicLong();
/**
* Creates a new ByteBufferPool with the given configuration.
*
* @param factor the capacity factor
* @param maxQueueLength the maximum ByteBuffer queue length
* @param maxHeapMemory the max heap memory in bytes, -1 for unlimited memory or 0 to use default heuristic.
* @param maxDirectMemory the max direct memory in bytes, -1 for unlimited memory or 0 to use default heuristic.
*/
protected AbstractByteBufferPool(int factor, int maxQueueLength, long maxHeapMemory, long maxDirectMemory)
{
_factor = factor <= 0 ? 1024 : factor;
_maxQueueLength = maxQueueLength;
_maxHeapMemory = maxHeapMemory;
_maxDirectMemory = maxDirectMemory;
_maxHeapMemory = (maxHeapMemory != 0) ? maxHeapMemory : Runtime.getRuntime().maxMemory() / 4;
_maxDirectMemory = (maxDirectMemory != 0) ? maxDirectMemory : Runtime.getRuntime().maxMemory() / 4;
}
protected int getCapacityFactor()
@ -49,11 +58,13 @@ abstract class AbstractByteBufferPool implements ByteBufferPool
return _maxQueueLength;
}
@Deprecated
protected void decrementMemory(ByteBuffer buffer)
{
updateMemory(buffer, false);
}
@Deprecated
protected void incrementMemory(ByteBuffer buffer)
{
updateMemory(buffer, true);
@ -90,12 +101,29 @@ abstract class AbstractByteBufferPool implements ByteBufferPool
return getMemory(false);
}
@ManagedAttribute("The max num of bytes that can be retained from direct ByteBuffers")
public long getMaxDirectMemory()
{
return _maxDirectMemory;
}
@ManagedAttribute("The max num of bytes that can be retained from heap ByteBuffers")
public long getMaxHeapMemory()
{
return _maxHeapMemory;
}
public long getMemory(boolean direct)
{
AtomicLong memory = direct ? _directMemory : _heapMemory;
return memory.get();
}
IntConsumer updateMemory(boolean direct)
{
return (direct) ? _directMemory::addAndGet : _heapMemory::addAndGet;
}
@ManagedOperation(value = "Clears this ByteBufferPool", impact = "ACTION")
public void clear()
{

View File

@ -13,14 +13,19 @@
package org.eclipse.jetty.io;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.IntFunction;
import java.util.stream.Collectors;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.component.Dumpable;
import org.eclipse.jetty.util.component.DumpableCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -31,13 +36,15 @@ import org.slf4j.LoggerFactory;
* 2048, and so on.</p>
*/
@ManagedObject
public class ArrayByteBufferPool extends AbstractByteBufferPool
public class ArrayByteBufferPool extends AbstractByteBufferPool implements Dumpable
{
private static final Logger LOG = LoggerFactory.getLogger(MappedByteBufferPool.class);
private final int _maxCapacity;
private final int _minCapacity;
private final ByteBufferPool.Bucket[] _direct;
private final ByteBufferPool.Bucket[] _indirect;
private boolean _detailedDump = false;
/**
* Creates a new ArrayByteBufferPool with a default configuration.
@ -56,7 +63,7 @@ public class ArrayByteBufferPool extends AbstractByteBufferPool
*/
public ArrayByteBufferPool(int minCapacity, int factor, int maxCapacity)
{
this(minCapacity, factor, maxCapacity, -1, -1, -1);
this(minCapacity, factor, maxCapacity, -1, 0, 0);
}
/**
@ -69,7 +76,7 @@ public class ArrayByteBufferPool extends AbstractByteBufferPool
*/
public ArrayByteBufferPool(int minCapacity, int factor, int maxCapacity, int maxQueueLength)
{
this(minCapacity, factor, maxCapacity, maxQueueLength, -1, -1);
this(minCapacity, factor, maxCapacity, maxQueueLength, 0, 0);
}
/**
@ -79,8 +86,8 @@ public class ArrayByteBufferPool extends AbstractByteBufferPool
* @param factor the capacity factor
* @param maxCapacity the maximum ByteBuffer capacity
* @param maxQueueLength the maximum ByteBuffer queue length
* @param maxHeapMemory the max heap memory in bytes
* @param maxDirectMemory the max direct memory in bytes
* @param maxHeapMemory the max heap memory in bytes, -1 for unlimited memory or 0 to use default heuristic.
* @param maxDirectMemory the max direct memory in bytes, -1 for unlimited memory or 0 to use default heuristic.
*/
public ArrayByteBufferPool(int minCapacity, int factor, int maxCapacity, int maxQueueLength, long maxHeapMemory, long maxDirectMemory)
{
@ -93,24 +100,30 @@ public class ArrayByteBufferPool extends AbstractByteBufferPool
maxCapacity = 64 * 1024;
if ((maxCapacity % factor) != 0 || factor >= maxCapacity)
throw new IllegalArgumentException("The capacity factor must be a divisor of maxCapacity");
_maxCapacity = maxCapacity;
_minCapacity = minCapacity;
int length = maxCapacity / factor;
// Initialize all buckets in constructor and never modify the array again.
int length = bucketFor(maxCapacity) + 1;
_direct = new ByteBufferPool.Bucket[length];
_indirect = new ByteBufferPool.Bucket[length];
for (int i = 0; i < length; i++)
{
_direct[i] = newBucket(i, true);
_indirect[i] = newBucket(i, false);
}
}
@Override
public ByteBuffer acquire(int size, boolean direct)
{
int capacity = size < _minCapacity ? size : (bucketFor(size) + 1) * getCapacityFactor();
ByteBufferPool.Bucket bucket = bucketFor(size, direct, null);
int capacity = size < _minCapacity ? size : capacityFor(bucketFor(size));
ByteBufferPool.Bucket bucket = bucketFor(size, direct);
if (bucket == null)
return newByteBuffer(capacity, direct);
ByteBuffer buffer = bucket.acquire();
if (buffer == null)
return newByteBuffer(capacity, direct);
decrementMemory(buffer);
return buffer;
}
@ -122,26 +135,29 @@ public class ArrayByteBufferPool extends AbstractByteBufferPool
int capacity = buffer.capacity();
// Validate that this buffer is from this pool.
if ((capacity % getCapacityFactor()) != 0)
if (capacity != capacityFor(bucketFor(capacity)))
{
if (LOG.isDebugEnabled())
LOG.debug("ByteBuffer {} does not belong to this pool, discarding it", BufferUtil.toDetailString(buffer));
return;
}
// Don't release into the pool if greater than the maximum ByteBuffer capacity.
if (capacity > _maxCapacity)
return;
boolean direct = buffer.isDirect();
ByteBufferPool.Bucket bucket = bucketFor(capacity, direct, this::newBucket);
ByteBufferPool.Bucket bucket = bucketFor(capacity, direct);
if (bucket != null)
{
bucket.release(buffer);
incrementMemory(buffer);
releaseExcessMemory(direct, this::clearOldestBucket);
releaseExcessMemory(direct, this::releaseMemory);
}
}
private Bucket newBucket(int key)
private Bucket newBucket(int key, boolean direct)
{
return new Bucket(key * getCapacityFactor(), getMaxQueueLength());
return new Bucket(capacityFor(key), getMaxQueueLength(), updateMemory(direct));
}
@Override
@ -150,18 +166,12 @@ public class ArrayByteBufferPool extends AbstractByteBufferPool
super.clear();
for (int i = 0; i < _direct.length; ++i)
{
Bucket bucket = _direct[i];
if (bucket != null)
bucket.clear();
_direct[i] = null;
bucket = _indirect[i];
if (bucket != null)
bucket.clear();
_indirect[i] = null;
_direct[i].clear();
_indirect[i].clear();
}
}
private void clearOldestBucket(boolean direct)
protected void releaseMemory(boolean direct)
{
long oldest = Long.MAX_VALUE;
int index = -1;
@ -169,7 +179,7 @@ public class ArrayByteBufferPool extends AbstractByteBufferPool
for (int i = 0; i < buckets.length; ++i)
{
Bucket bucket = buckets[i];
if (bucket == null)
if (bucket.isEmpty())
continue;
long lastUpdate = bucket.getLastUpdate();
if (lastUpdate < oldest)
@ -181,31 +191,29 @@ public class ArrayByteBufferPool extends AbstractByteBufferPool
if (index >= 0)
{
Bucket bucket = buckets[index];
buckets[index] = null;
// The same bucket may be concurrently
// removed, so we need this null guard.
if (bucket != null)
bucket.clear(this::decrementMemory);
bucket.clear();
}
}
private int bucketFor(int capacity)
protected int bucketFor(int capacity)
{
return (capacity - 1) / getCapacityFactor();
return (int)Math.ceil((double)capacity / getCapacityFactor());
}
private ByteBufferPool.Bucket bucketFor(int capacity, boolean direct, IntFunction<Bucket> newBucket)
protected int capacityFor(int bucket)
{
return bucket * getCapacityFactor();
}
private ByteBufferPool.Bucket bucketFor(int capacity, boolean direct)
{
if (capacity < _minCapacity)
return null;
int b = bucketFor(capacity);
if (b >= _direct.length)
int bucket = bucketFor(capacity);
if (bucket >= _direct.length)
return null;
Bucket[] buckets = bucketsFor(direct);
Bucket bucket = buckets[b];
if (bucket == null && newBucket != null)
buckets[b] = bucket = newBucket.apply(b + 1);
return bucket;
return buckets[bucket];
}
@ManagedAttribute("The number of pooled direct ByteBuffers")
@ -233,4 +241,47 @@ public class ArrayByteBufferPool extends AbstractByteBufferPool
{
return direct ? _direct : _indirect;
}
public boolean isDetailedDump()
{
return _detailedDump;
}
public void setDetailedDump(boolean detailedDump)
{
_detailedDump = detailedDump;
}
@Override
public void dump(Appendable out, String indent) throws IOException
{
List<Object> dump = new ArrayList<>();
dump.add(String.format("HeapMemory: %d/%d", getHeapMemory(), getMaxHeapMemory()));
dump.add(String.format("DirectMemory: %d/%d", getDirectMemory(), getMaxDirectMemory()));
List<Bucket> indirect = Arrays.stream(_indirect).filter(b -> !b.isEmpty()).collect(Collectors.toList());
List<Bucket> direct = Arrays.stream(_direct).filter(b -> !b.isEmpty()).collect(Collectors.toList());
if (isDetailedDump())
{
dump.add(new DumpableCollection("Indirect Buckets", indirect));
dump.add(new DumpableCollection("Direct Buckets", direct));
}
else
{
dump.add("Indirect Buckets size=" + indirect.size());
dump.add("Direct Buckets size=" + direct.size());
}
Dumpable.dumpObjects(out, indent, this, dump);
}
@Override
public String toString()
{
return String.format("%s@%x{minBufferCapacity=%s, maxBufferCapacity=%s, maxQueueLength=%s, factor=%s}",
this.getClass().getSimpleName(), hashCode(),
_minCapacity,
_maxCapacity,
getMaxQueueLength(),
getCapacityFactor());
}
}

View File

@ -16,11 +16,12 @@ package org.eclipse.jetty.io;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
import org.eclipse.jetty.util.BufferUtil;
@ -154,69 +155,68 @@ public interface ByteBufferPool
private final int _maxSize;
private final AtomicInteger _size;
private final AtomicLong _lastUpdate = new AtomicLong(System.nanoTime());
private final IntConsumer _memoryFunction;
@Deprecated
public Bucket(int capacity, int maxSize)
{
this(capacity, maxSize, i -> {});
}
public Bucket(int capacity, int maxSize, IntConsumer memoryFunction)
{
_capacity = capacity;
_maxSize = maxSize;
_size = maxSize > 0 ? new AtomicInteger() : null;
_memoryFunction = Objects.requireNonNull(memoryFunction);
}
public ByteBuffer acquire()
{
ByteBuffer buffer = queuePoll();
if (buffer == null)
return null;
if (_size != null)
_size.decrementAndGet();
ByteBuffer buffer = _queue.poll();
if (buffer != null)
{
if (_size != null)
_size.decrementAndGet();
_memoryFunction.accept(-buffer.capacity());
}
return buffer;
}
public void release(ByteBuffer buffer)
{
_lastUpdate.setOpaque(System.nanoTime());
resetUpdateTime();
BufferUtil.clear(buffer);
if (_size == null)
queueOffer(buffer);
else if (_size.incrementAndGet() <= _maxSize)
queueOffer(buffer);
if (_size == null || _size.incrementAndGet() <= _maxSize)
{
_queue.offer(buffer);
_memoryFunction.accept(buffer.capacity());
}
else
{
_size.decrementAndGet();
}
}
void resetUpdateTime()
{
_lastUpdate.lazySet(System.nanoTime());
}
public void clear()
{
clear(null);
}
void clear(Consumer<ByteBuffer> memoryFn)
{
int size = _size == null ? 0 : _size.get() - 1;
while (size >= 0)
{
ByteBuffer buffer = queuePoll();
ByteBuffer buffer = acquire();
if (buffer == null)
break;
if (memoryFn != null)
memoryFn.accept(buffer);
if (_size != null)
{
_size.decrementAndGet();
--size;
}
}
}
private void queueOffer(ByteBuffer buffer)
{
_queue.offer(buffer);
}
private ByteBuffer queuePoll()
{
return _queue.poll();
}
boolean isEmpty()
{
return _queue.isEmpty();
@ -235,7 +235,7 @@ public interface ByteBufferPool
@Override
public String toString()
{
return String.format("%s@%x{%d/%d@%d}", getClass().getSimpleName(), hashCode(), size(), _maxSize, _capacity);
return String.format("%s@%x{capacity=%d, size=%d, maxSize=%d}", getClass().getSimpleName(), hashCode(), _capacity, size(), _maxSize);
}
}
}

View File

@ -0,0 +1,107 @@
//
// ========================================================================
// Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.io;
/**
* Extension of the {@link ArrayByteBufferPool} whose bucket sizes increase exponentially instead of linearly.
* Each bucket will be double the size of the previous bucket, this decreases the amounts of buckets required
* which can lower total memory usage if buffers are often being acquired of different sizes. However as there are
* fewer buckets this will also increase the contention on each bucket.
*/
public class LogarithmicArrayByteBufferPool extends ArrayByteBufferPool
{
/**
* Creates a new ByteBufferPool with a default configuration.
*/
public LogarithmicArrayByteBufferPool()
{
this(-1, -1, -1);
}
/**
* Creates a new ByteBufferPool with the given configuration.
*
* @param minCapacity the minimum ByteBuffer capacity
* @param maxCapacity the maximum ByteBuffer capacity
*/
public LogarithmicArrayByteBufferPool(int minCapacity, int maxCapacity)
{
this(minCapacity, maxCapacity, -1, -1, -1);
}
/**
* Creates a new ByteBufferPool with the given configuration.
*
* @param minCapacity the minimum ByteBuffer capacity
* @param maxCapacity the maximum ByteBuffer capacity
* @param maxQueueLength the maximum ByteBuffer queue length
*/
public LogarithmicArrayByteBufferPool(int minCapacity, int maxCapacity, int maxQueueLength)
{
this(minCapacity, maxCapacity, maxQueueLength, -1, -1);
}
/**
* Creates a new ByteBufferPool with the given configuration.
*
* @param minCapacity the minimum ByteBuffer capacity
* @param maxCapacity the maximum ByteBuffer capacity
* @param maxQueueLength the maximum ByteBuffer queue length
* @param maxHeapMemory the max heap memory in bytes
* @param maxDirectMemory the max direct memory in bytes
*/
public LogarithmicArrayByteBufferPool(int minCapacity, int maxCapacity, int maxQueueLength, long maxHeapMemory, long maxDirectMemory)
{
super(minCapacity, 1, maxCapacity, maxQueueLength, maxHeapMemory, maxDirectMemory);
}
@Override
protected int bucketFor(int capacity)
{
return 32 - Integer.numberOfLeadingZeros(capacity - 1);
}
@Override
protected int capacityFor(int bucket)
{
return 1 << bucket;
}
@Override
protected void releaseMemory(boolean direct)
{
long oldest = Long.MAX_VALUE;
int index = -1;
Bucket[] buckets = bucketsFor(direct);
for (int i = 0; i < buckets.length; ++i)
{
Bucket bucket = buckets[i];
if (bucket.isEmpty())
continue;
long lastUpdate = bucket.getLastUpdate();
if (lastUpdate < oldest)
{
oldest = lastUpdate;
index = i;
}
}
if (index >= 0)
{
Bucket bucket = buckets[index];
// Acquire a buffer but never return it to the pool.
bucket.acquire();
bucket.resetUpdateTime();
}
}
}

View File

@ -13,7 +13,10 @@
package org.eclipse.jetty.io;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@ -23,6 +26,8 @@ import java.util.function.Function;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.component.Dumpable;
import org.eclipse.jetty.util.component.DumpableCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -33,13 +38,14 @@ import org.slf4j.LoggerFactory;
* queue of ByteBuffers each of capacity 2048, and so on.</p>
*/
@ManagedObject
public class MappedByteBufferPool extends AbstractByteBufferPool
public class MappedByteBufferPool extends AbstractByteBufferPool implements Dumpable
{
private static final Logger LOG = LoggerFactory.getLogger(MappedByteBufferPool.class);
private final ConcurrentMap<Integer, Bucket> _directBuffers = new ConcurrentHashMap<>();
private final ConcurrentMap<Integer, Bucket> _heapBuffers = new ConcurrentHashMap<>();
private final Function<Integer, Bucket> _newBucket;
private boolean _detailedDump = false;
/**
* Creates a new MappedByteBufferPool with a default configuration.
@ -79,7 +85,7 @@ public class MappedByteBufferPool extends AbstractByteBufferPool
*/
public MappedByteBufferPool(int factor, int maxQueueLength, Function<Integer, Bucket> newBucket)
{
this(factor, maxQueueLength, newBucket, -1, -1);
this(factor, maxQueueLength, newBucket, 0, 0);
}
/**
@ -88,25 +94,25 @@ public class MappedByteBufferPool extends AbstractByteBufferPool
* @param factor the capacity factor
* @param maxQueueLength the maximum ByteBuffer queue length
* @param newBucket the function that creates a Bucket
* @param maxHeapMemory the max heap memory in bytes
* @param maxDirectMemory the max direct memory in bytes
* @param maxHeapMemory the max heap memory in bytes, -1 for unlimited memory or 0 to use default heuristic.
* @param maxDirectMemory the max direct memory in bytes, -1 for unlimited memory or 0 to use default heuristic.
*/
public MappedByteBufferPool(int factor, int maxQueueLength, Function<Integer, Bucket> newBucket, long maxHeapMemory, long maxDirectMemory)
{
super(factor, maxQueueLength, maxHeapMemory, maxDirectMemory);
_newBucket = newBucket != null ? newBucket : this::newBucket;
_newBucket = newBucket;
}
private Bucket newBucket(int key)
private Bucket newBucket(int key, boolean direct)
{
return new Bucket(key * getCapacityFactor(), getMaxQueueLength());
return (_newBucket != null) ? _newBucket.apply(key) : new Bucket(capacityFor(key), getMaxQueueLength(), updateMemory(direct));
}
@Override
public ByteBuffer acquire(int size, boolean direct)
{
int b = bucketFor(size);
int capacity = b * getCapacityFactor();
int capacity = capacityFor(b);
ConcurrentMap<Integer, Bucket> buffers = bucketsFor(direct);
Bucket bucket = buffers.get(b);
if (bucket == null)
@ -114,7 +120,6 @@ public class MappedByteBufferPool extends AbstractByteBufferPool
ByteBuffer buffer = bucket.acquire();
if (buffer == null)
return newByteBuffer(capacity, direct);
decrementMemory(buffer);
return buffer;
}
@ -125,21 +130,20 @@ public class MappedByteBufferPool extends AbstractByteBufferPool
return; // nothing to do
int capacity = buffer.capacity();
int b = bucketFor(capacity);
// Validate that this buffer is from this pool.
if ((capacity % getCapacityFactor()) != 0)
if (capacity != capacityFor(b))
{
if (LOG.isDebugEnabled())
LOG.debug("ByteBuffer {} does not belong to this pool, discarding it", BufferUtil.toDetailString(buffer));
return;
}
int b = bucketFor(capacity);
boolean direct = buffer.isDirect();
ConcurrentMap<Integer, Bucket> buckets = bucketsFor(direct);
Bucket bucket = buckets.computeIfAbsent(b, _newBucket);
Bucket bucket = buckets.computeIfAbsent(b, i -> newBucket(i, direct));
bucket.release(buffer);
incrementMemory(buffer);
releaseExcessMemory(direct, this::clearOldestBucket);
releaseExcessMemory(direct, this::releaseMemory);
}
@Override
@ -152,7 +156,7 @@ public class MappedByteBufferPool extends AbstractByteBufferPool
_heapBuffers.clear();
}
private void clearOldestBucket(boolean direct)
protected void releaseMemory(boolean direct)
{
long oldest = Long.MAX_VALUE;
int index = -1;
@ -160,6 +164,9 @@ public class MappedByteBufferPool extends AbstractByteBufferPool
for (Map.Entry<Integer, Bucket> entry : buckets.entrySet())
{
Bucket bucket = entry.getValue();
if (bucket.isEmpty())
continue;
long lastUpdate = bucket.getLastUpdate();
if (lastUpdate < oldest)
{
@ -170,20 +177,20 @@ public class MappedByteBufferPool extends AbstractByteBufferPool
if (index >= 0)
{
Bucket bucket = buckets.remove(index);
// The same bucket may be concurrently
// removed, so we need this null guard.
// Null guard in case this.clear() is called concurrently.
if (bucket != null)
bucket.clear(this::decrementMemory);
bucket.clear();
}
}
private int bucketFor(int size)
protected int bucketFor(int capacity)
{
int factor = getCapacityFactor();
int bucket = size / factor;
if (bucket * factor != size)
++bucket;
return bucket;
return (int)Math.ceil((double)capacity / getCapacityFactor());
}
protected int capacityFor(int bucket)
{
return bucket * getCapacityFactor();
}
@ManagedAttribute("The number of pooled direct ByteBuffers")
@ -226,4 +233,43 @@ public class MappedByteBufferPool extends AbstractByteBufferPool
return slice;
}
}
public boolean isDetailedDump()
{
return _detailedDump;
}
public void setDetailedDump(boolean detailedDump)
{
_detailedDump = detailedDump;
}
@Override
public void dump(Appendable out, String indent) throws IOException
{
List<Object> dump = new ArrayList<>();
dump.add(String.format("HeapMemory: %d/%d", getHeapMemory(), getMaxHeapMemory()));
dump.add(String.format("DirectMemory: %d/%d", getDirectMemory(), getMaxDirectMemory()));
if (isDetailedDump())
{
dump.add(new DumpableCollection("Indirect Buckets", _heapBuffers.values()));
dump.add(new DumpableCollection("Direct Buckets", _directBuffers.values()));
}
else
{
dump.add("Indirect Buckets size=" + _heapBuffers.size());
dump.add("Direct Buckets size=" + _directBuffers.size());
}
Dumpable.dumpObjects(out, indent, this, dump);
}
@Override
public String toString()
{
return String.format("%s@%x{maxQueueLength=%s, factor=%s}",
this.getClass().getSimpleName(), hashCode(),
getMaxQueueLength(),
getCapacityFactor());
}
}

View File

@ -22,12 +22,11 @@ import org.eclipse.jetty.util.StringUtil;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ -64,10 +63,13 @@ public class ArrayByteBufferPoolTest
@Test
public void testMaxRelease()
{
ArrayByteBufferPool bufferPool = new ArrayByteBufferPool(10, 100, 1000);
int minCapacity = 10;
int factor = 1;
int maxCapacity = 1024;
ArrayByteBufferPool bufferPool = new ArrayByteBufferPool(minCapacity, factor, maxCapacity);
ByteBufferPool.Bucket[] buckets = bufferPool.bucketsFor(true);
for (int size = 999; size <= 1001; size++)
for (int size = maxCapacity - 1; size <= maxCapacity + 1; size++)
{
bufferPool.clear();
ByteBuffer buffer = bufferPool.acquire(size, true);
@ -86,7 +88,11 @@ public class ArrayByteBufferPoolTest
.filter(Objects::nonNull)
.mapToInt(Bucket::size)
.sum();
assertEquals(size <= 1000, 1 == pooled);
if (size <= maxCapacity)
assertThat(pooled, is(1));
else
assertThat(pooled, is(0));
}
}
@ -190,7 +196,7 @@ public class ArrayByteBufferPoolTest
public void testMaxMemory()
{
int factor = 1024;
int maxMemory = 11 * 1024;
int maxMemory = 11 * factor;
ArrayByteBufferPool bufferPool = new ArrayByteBufferPool(-1, factor, -1, -1, -1, maxMemory);
Bucket[] buckets = bufferPool.bucketsFor(true);
@ -200,26 +206,38 @@ public class ArrayByteBufferPoolTest
{
int capacity = factor * i;
ByteBuffer buffer = bufferPool.acquire(capacity, true);
assertThat(buffer.capacity(), equalTo(capacity));
bufferPool.release(buffer);
}
// Check state of buckets.
assertThat(bufferPool.getMemory(true), equalTo(10L * factor));
assertThat(buckets[1].size(), equalTo(1));
assertThat(buckets[2].size(), equalTo(1));
assertThat(buckets[3].size(), equalTo(1));
assertThat(buckets[4].size(), equalTo(1));
// Create and release a buffer to exceed the max memory.
ByteBuffer buffer = bufferPool.newByteBuffer(2 * factor, true);
int capacity = 2 * factor;
ByteBuffer buffer = bufferPool.newByteBuffer(capacity, true);
assertThat(buffer.capacity(), equalTo(capacity));
bufferPool.release(buffer);
// Now the oldest buffer should be gone and we have: 1+2x2+3=8
long memory = bufferPool.getMemory(true);
assertThat(memory, lessThan((long)maxMemory));
assertNull(buckets[3]);
assertThat(bufferPool.getMemory(true), equalTo(8L * factor));
assertThat(buckets[1].size(), equalTo(1));
assertThat(buckets[2].size(), equalTo(2));
assertThat(buckets[3].size(), equalTo(1));
// Create and release a large buffer.
// Max memory is exceeded and buckets 3 and 1 are cleared.
// We will have 2x2+7=11.
buffer = bufferPool.newByteBuffer(7 * factor, true);
capacity = 7 * factor;
buffer = bufferPool.newByteBuffer(capacity, true);
bufferPool.release(buffer);
memory = bufferPool.getMemory(true);
assertThat(memory, lessThanOrEqualTo((long)maxMemory));
assertNull(buckets[0]);
assertNull(buckets[2]);
assertThat(bufferPool.getMemory(true), equalTo(11L * factor));
assertThat(buckets[2].size(), equalTo(2));
assertThat(buckets[7].size(), equalTo(1));
}
}

View File

@ -23,11 +23,9 @@ import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ -139,7 +137,7 @@ public class MappedByteBufferPoolTest
public void testMaxMemory()
{
int factor = 1024;
int maxMemory = 11 * 1024;
int maxMemory = 11 * factor;
MappedByteBufferPool bufferPool = new MappedByteBufferPool(factor, -1, null, -1, maxMemory);
ConcurrentMap<Integer, Bucket> buckets = bufferPool.bucketsFor(true);
@ -149,26 +147,39 @@ public class MappedByteBufferPoolTest
{
int capacity = factor * i;
ByteBuffer buffer = bufferPool.acquire(capacity, true);
assertThat(buffer.capacity(), equalTo(capacity));
bufferPool.release(buffer);
}
// Check state of buckets.
assertThat(bufferPool.getMemory(true), equalTo(10L * factor));
assertThat(buckets.get(1).size(), equalTo(1));
assertThat(buckets.get(2).size(), equalTo(1));
assertThat(buckets.get(3).size(), equalTo(1));
assertThat(buckets.get(4).size(), equalTo(1));
// Create and release a buffer to exceed the max memory.
ByteBuffer buffer = bufferPool.newByteBuffer(2 * factor, true);
int capacity = 2 * factor;
ByteBuffer buffer = bufferPool.newByteBuffer(capacity, true);
assertThat(buffer.capacity(), equalTo(capacity));
bufferPool.release(buffer);
// Now the oldest buffer should be gone and we have: 1+2x2+3=8
long memory = bufferPool.getMemory(true);
assertThat(memory, lessThan((long)maxMemory));
assertNull(buckets.get(4));
assertThat(bufferPool.getMemory(true), equalTo(8L * factor));
assertThat(buckets.get(1).size(), equalTo(1));
assertThat(buckets.get(2).size(), equalTo(2));
assertThat(buckets.get(3).size(), equalTo(1));
// Create and release a large buffer.
// Max memory is exceeded and buckets 3 and 1 are cleared.
// We will have 2x2+7=11.
buffer = bufferPool.newByteBuffer(7 * factor, true);
capacity = 7 * factor;
buffer = bufferPool.newByteBuffer(capacity, true);
assertThat(buffer.capacity(), equalTo(capacity));
bufferPool.release(buffer);
memory = bufferPool.getMemory(true);
assertThat(memory, lessThanOrEqualTo((long)maxMemory));
assertNull(buckets.get(1));
assertNull(buckets.get(3));
assertThat(bufferPool.getMemory(true), equalTo(11L * factor));
assertThat(buckets.get(2).size(), equalTo(2));
assertThat(buckets.get(7).size(), equalTo(1));
}
}

View File

@ -0,0 +1,11 @@
<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_10_0.dtd">
<Configure>
<New id="byteBufferPool" class="org.eclipse.jetty.io.LogarithmicArrayByteBufferPool">
<Arg type="int"><Property name="jetty.byteBufferPool.minCapacity" default="0"/></Arg>
<Arg type="int"><Property name="jetty.byteBufferPool.maxCapacity" default="65536"/></Arg>
<Arg type="int"><Property name="jetty.byteBufferPool.maxQueueLength" default="-1"/></Arg>
<Arg type="long"><Property name="jetty.byteBufferPool.maxHeapMemory" default="0"/></Arg>
<Arg type="long"><Property name="jetty.byteBufferPool.maxDirectMemory" default="0"/></Arg>
</New>
</Configure>

View File

@ -6,7 +6,7 @@
<Arg type="int"><Property name="jetty.byteBufferPool.factor" default="1024"/></Arg>
<Arg type="int"><Property name="jetty.byteBufferPool.maxCapacity" default="65536"/></Arg>
<Arg type="int"><Property name="jetty.byteBufferPool.maxQueueLength" default="-1"/></Arg>
<Arg type="long"><Property name="jetty.byteBufferPool.maxHeapMemory" default="-1"/></Arg>
<Arg type="long"><Property name="jetty.byteBufferPool.maxDirectMemory" default="-1"/></Arg>
<Arg type="long"><Property name="jetty.byteBufferPool.maxHeapMemory" default="0"/></Arg>
<Arg type="long"><Property name="jetty.byteBufferPool.maxDirectMemory" default="0"/></Arg>
</New>
</Configure>

View File

@ -0,0 +1,30 @@
# DO NOT EDIT - See: https://www.eclipse.org/jetty/documentation/current/startup-modules.html
[description]
Configures the ByteBufferPool used by ServerConnectors whose bucket sizes increase exponentially instead of linearly.
[tags]
bytebufferpool
[provides]
bytebufferpool
[xml]
etc/jetty-bytebufferpool-logarithmic.xml
[ini-template]
### Server ByteBufferPool Configuration
## Minimum capacity to pool ByteBuffers
#jetty.byteBufferPool.minCapacity=0
## Maximum capacity to pool ByteBuffers
#jetty.byteBufferPool.maxCapacity=65536
## Maximum queue length for each bucket (-1 for unbounded)
#jetty.byteBufferPool.maxQueueLength=-1
## Maximum heap memory retainable by the pool (0 for heuristic, -1 for unlimited)
#jetty.byteBufferPool.maxHeapMemory=0
## Maximum direct memory retainable by the pool (0 for heuristic, -1 for unlimited)
#jetty.byteBufferPool.maxDirectMemory=0

View File

@ -1,8 +1,8 @@
[description]
Configures the ByteBufferPool used by ServerConnectors.
[depends]
logging
[tags]
bytebufferpool
[xml]
etc/jetty-bytebufferpool.xml
@ -24,8 +24,8 @@ etc/jetty-bytebufferpool.xml
## Maximum queue length for each bucket (-1 for unbounded).
#jetty.byteBufferPool.maxQueueLength=-1
## Maximum heap memory retainable by the pool (-1 for unlimited).
#jetty.byteBufferPool.maxHeapMemory=-1
## Maximum heap memory retainable by the pool (0 for heuristic, -1 for unlimited).
#jetty.byteBufferPool.maxHeapMemory=0
## Maximum direct memory retainable by the pool (-1 for unlimited).
#jetty.byteBufferPool.maxDirectMemory=-1
## Maximum direct memory retainable by the pool (0 for heuristic, -1 for unlimited).
#jetty.byteBufferPool.maxDirectMemory=0