All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.postgresql.adba.buffer.DefaultByteBufferPool Maven / Gradle / Ivy

The newest version!
package org.postgresql.adba.buffer;

import java.nio.ByteBuffer;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Default {@link ByteBufferPool}.
 * 
 * @author Daniel Sagenschneider
 */
public class DefaultByteBufferPool implements ByteBufferPool {

  /**
   * Pool of {@link PooledByteBuffer} instances.
   */
  private final Queue pool = new ConcurrentLinkedQueue<>();

  /**
   * Size of buffers.
   */
  private final int bufferSize;

  /**
   * Instantiate.
   */
  public DefaultByteBufferPool() {
    // TODO consider specifying buffer size from properties
    this.bufferSize = 8192; // largest 2 based size fitting jumbo ethernet packet
  }

  /*
   * ================= ByteBufferPool ======================
   */

  @Override
  public PooledByteBuffer getPooledByteBuffer() {

    // Obtain the next pooled buffer
    PooledByteBuffer buffer = pool.poll();
    if (buffer != null) {
      return buffer;
    }

    // No pooled, so create buffer
    // TODO consider blocking thread if too many active buffers to keep memory down
    return new PooledByteBufferImpl();
  }

  private class PooledByteBufferImpl implements PooledByteBuffer {

    private final ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);

    /*
     * =============== PooledByteBuffer ====================
     */

    @Override
    public ByteBuffer getByteBuffer() {
      return this.buffer;
    }

    @Override
    public void release() {
      pool.add(this);
    }
  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy