KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jofti > store > BufferManager


1
2 package com.jofti.store;
3
4 import com.jofti.exception.JoftiException;
5
6 import edu.emory.mathcs.backport.java.util.concurrent.LinkedBlockingQueue;
7
8 /**
9  * Responsible for allocating new Buffers that are used to copy data to and from files.
10  *
11  * @author xenephon
12  */

13 public class BufferManager {
14
15
16     /**
17      *
18      */

19     LinkedBlockingQueue freeQueue = null;
20
21     //block size for buffer
22
private int blockSize = 0;
23
24     //maximum number of buffers to cache
25
private int maxBuffers = 100;
26
27     // initial number of buffers to create
28
private int bufferNumber = 10;
29     
30     // count for new buffers created
31
private long newBuffers =0;
32
33     private long accesses=0;
34
35     private long releases=0;
36     
37     public BufferManager() {
38     }
39
40     public void init(int blockSize, int maxBuffers, int bufferNumber)
41             throws JoftiException
42     {
43         // allocate all the free buffers to the freeQueue
44
this.blockSize = blockSize;
45         this.maxBuffers = maxBuffers;
46         this.bufferNumber = bufferNumber;
47
48         // set up the buffer pool
49
freeQueue = new LinkedBlockingQueue(maxBuffers);
50
51         for (int i = 0; i < bufferNumber; i++) {
52             BlockBuffer buf = new BlockBuffer();
53             buf.init(blockSize);
54             freeQueue.add(buf);
55         }
56
57     }
58
59
60     /**
61      * Obtains a BlockBuffer from the buffer pool.
62      *
63      * @param holder
64      * @return
65      * @throws JoftiException
66      */

67     public BlockBuffer acquireBuffer(FilePositionHolder holder)
68             throws JoftiException {
69
70         ++accesses;
71         
72         BlockBuffer buf = (BlockBuffer) freeQueue.poll();
73         
74         // we must be out of buffers so we can create one
75
if (buf == null) {
76             // create a new buffer
77
buf = new BlockBuffer();
78             buf.init(blockSize);
79             ++newBuffers;
80
81         }
82         buf.setPositionHolder(holder);
83
84         return buf;
85     }
86
87     /**
88      * releases a buffer into the freeQueue
89      * @param buffer LogBuffer to be released
90      */

91     public void releaseBuffer(BlockBuffer buffer) {
92         
93         ++releases;
94         buffer.reset();
95
96         // if the offer does not work then we do not care
97
freeQueue.offer(buffer);
98
99     }
100     
101     
102     
103     
104 }
Popular Tags