Optimize release of multiple allocations.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=126799524
This commit is contained in:
olly 2016-07-07 06:25:07 -07:00 committed by Oliver Woodman
parent 1a3de408ac
commit e02ca775f3
3 changed files with 27 additions and 10 deletions

View File

@ -550,9 +550,8 @@ public final class DefaultTrackOutput implements TrackOutput {
private void clearSampleData() {
infoQueue.clearSampleData();
while (!dataQueue.isEmpty()) {
allocator.release(dataQueue.remove());
}
allocator.release(dataQueue.toArray(new Allocation[dataQueue.size()]));
dataQueue.clear();
allocator.trim();
totalBytesDropped = 0;
totalBytesWritten = 0;

View File

@ -37,6 +37,13 @@ public interface Allocator {
*/
void release(Allocation allocation);
/**
* Return an array of {@link Allocation}s.
*
* @param allocations The array of {@link Allocation}s being returned.
*/
void release(Allocation[] allocations);
/**
* Hints to the {@link Allocator} that it should make a best effort to release any memory that it
* has allocated beyond the target buffer size.

View File

@ -29,6 +29,7 @@ public final class DefaultAllocator implements Allocator {
private final int individualAllocationSize;
private final byte[] initialAllocationBlock;
private final Allocation[] singleAllocationReleaseHolder;
private int targetBufferSize;
private int allocatedCount;
@ -67,6 +68,7 @@ public final class DefaultAllocator implements Allocator {
} else {
initialAllocationBlock = null;
}
singleAllocationReleaseHolder = new Allocation[1];
}
public synchronized void setTargetBufferSize(int targetBufferSize) {
@ -92,14 +94,23 @@ public final class DefaultAllocator implements Allocator {
@Override
public synchronized void release(Allocation allocation) {
// Weak sanity check that the allocation probably originated from this pool.
Assertions.checkArgument(allocation.data == initialAllocationBlock
|| allocation.data.length == individualAllocationSize);
allocatedCount--;
if (availableCount == availableAllocations.length) {
availableAllocations = Arrays.copyOf(availableAllocations, availableAllocations.length * 2);
singleAllocationReleaseHolder[0] = allocation;
release(singleAllocationReleaseHolder);
}
@Override
public synchronized void release(Allocation[] allocations) {
if (availableCount + allocations.length >= availableAllocations.length) {
availableAllocations = Arrays.copyOf(availableAllocations,
Math.max(availableAllocations.length * 2, availableCount + allocations.length));
}
availableAllocations[availableCount++] = allocation;
for (Allocation allocation : allocations) {
// Weak sanity check that the allocation probably originated from this pool.
Assertions.checkArgument(allocation.data == initialAllocationBlock
|| allocation.data.length == individualAllocationSize);
availableAllocations[availableCount++] = allocation;
}
allocatedCount -= allocations.length;
// Wake up threads waiting for the allocated size to drop.
notifyAll();
}