01: package com.jofti.store;
02:
03: import com.jofti.exception.JoftiException;
04:
05: import edu.emory.mathcs.backport.java.util.concurrent.LinkedBlockingQueue;
06:
07: /**
08: * Responsible for allocating new Buffers that are used to copy data to and from files.
09: *
10: * @author xenephon
11: */
12: public class BufferManager {
13:
14: /**
15: *
16: */
17: LinkedBlockingQueue freeQueue = null;
18:
19: //block size for buffer
20: private int blockSize = 0;
21:
22: //maximum number of buffers to cache
23: private int maxBuffers = 100;
24:
25: // initial number of buffers to create
26: private int bufferNumber = 10;
27:
28: // count for new buffers created
29: private long newBuffers = 0;
30:
31: private long accesses = 0;
32:
33: private long releases = 0;
34:
35: public BufferManager() {
36: }
37:
38: public void init(int blockSize, int maxBuffers, int bufferNumber)
39: throws JoftiException {
40: // allocate all the free buffers to the freeQueue
41: this .blockSize = blockSize;
42: this .maxBuffers = maxBuffers;
43: this .bufferNumber = bufferNumber;
44:
45: // set up the buffer pool
46: freeQueue = new LinkedBlockingQueue(maxBuffers);
47:
48: for (int i = 0; i < bufferNumber; i++) {
49: BlockBuffer buf = new BlockBuffer();
50: buf.init(blockSize);
51: freeQueue.add(buf);
52: }
53:
54: }
55:
56: /**
57: * Obtains a BlockBuffer from the buffer pool.
58: *
59: * @param holder
60: * @return
61: * @throws JoftiException
62: */
63: public BlockBuffer acquireBuffer(FilePositionHolder holder)
64: throws JoftiException {
65:
66: ++accesses;
67:
68: BlockBuffer buf = (BlockBuffer) freeQueue.poll();
69:
70: // we must be out of buffers so we can create one
71: if (buf == null) {
72: // create a new buffer
73: buf = new BlockBuffer();
74: buf.init(blockSize);
75: ++newBuffers;
76:
77: }
78: buf.setPositionHolder(holder);
79:
80: return buf;
81: }
82:
83: /**
84: * releases a buffer into the freeQueue
85: * @param buffer LogBuffer to be released
86: */
87: public void releaseBuffer(BlockBuffer buffer) {
88:
89: ++releases;
90: buffer.reset();
91:
92: // if the offer does not work then we do not care
93: freeQueue.offer(buffer);
94:
95: }
96:
97: }
|