diff --git a/core/src/main/java/com/turn/ttorrent/common/ByteBufferRentalService.java b/core/src/main/java/com/turn/ttorrent/common/ByteBufferRentalService.java new file mode 100644 index 000000000..f217cc845 --- /dev/null +++ b/core/src/main/java/com/turn/ttorrent/common/ByteBufferRentalService.java @@ -0,0 +1,41 @@ +package com.turn.ttorrent.common; + +import java.nio.ByteBuffer; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + +/** + * A limited, exclusive storage, so that the workers are limited to it's amount. + * + * The ByteBuffers are array backed, so the APIs they get sent to have no need to instantiate one + * + * "rental service": exemplifies well the intent, shitty name :-) + * + */ +public class ByteBufferRentalService { + private BlockingQueue byteBufferBlockingQueue; + + /** + * Initializes a bounded storage + * + * @param amount the amount of byte buffers to create + * @param length the length of the created buffers + */ + public ByteBufferRentalService(int amount, int length) { + byteBufferBlockingQueue = new LinkedBlockingQueue(amount); + + for (int i = 0; i < amount; i++) { + byteBufferBlockingQueue.add( ByteBuffer.allocate(length) ); + } + } + + public ByteBuffer take() throws InterruptedException { + return byteBufferBlockingQueue.take(); + } + + public void put(ByteBuffer buffer) throws InterruptedException { + buffer.clear(); + + byteBufferBlockingQueue.put( buffer ); + } +}