-2

I am having ArrayIndexOutOfBoundsException error for my getBuffer method,

public class BufferPool {

private LPQueue<Buffer> queue;
private RandomAccessFile disk;
private int blockSize;
private int poolSize;
private Buffer[] pool;

    public BufferPool(File file, int bufferNumber, int blockSize)
        throws IOException {
    this.blockSize = blockSize;
    queue = new LPQueue<Buffer>(bufferNumber);

    disk = new RandomAccessFile(file, "rw");

    poolSize = ((int) disk.length() / blockSize);
    pool = new Buffer[poolSize];
}

    public Buffer getBuffer(int index) {
        if (pool[index] == null) {   // <<----------here!
            pool[index] = newBuffer(index);
        }
        return pool[index];
    }
}

Can you please help me to solve this problem out? This buffer pool is pool of the buffer to store the value of data to sort it later.. This get Buffer Gets a handle to a Buffer that represents the indexth block of the file that is backing this BufferPool. index is the index of the block we want to acquire. it returns a buffer handle to that block.

Jieun Chon
  • 139
  • 1
  • 10

1 Answers1

2

Your index is out of the bounds of the Array. You have poolSize = n and index >=n -> ArrayIndexOutOfBoundsException.

Make if(index >= pool.length) return null; or something like that in the getBuffer Method

If you have an Array of size 3:

poolSize = 3;
Buffer[] myArray = new Buffer[poolSize];

//Your Array looks the following:
myArray[Element1, Element2, Element3]
           |         |         |
Index:     0         1         2  

So if you try to get myArray[3] you get the Exception.

You probably have a loop somewhere in your code that looks the following:

for(int i = 0; i<=poolSize; i++){
    Buffer b = getBuffer(i); //so you ask for getBuffer(3) the last time
}

You have to be careful on what index you ask for. Always get your boundaries right.

Loki
  • 4,065
  • 4
  • 29
  • 51