1 package org.apache.turbine.util.pool; 2 3 18 19 28 public class BoundedBuffer 29 { 30 31 public static final int DEFAULT_CAPACITY = 1024; 32 33 protected final Object [] buffer; 35 protected int takePtr = 0; protected int putPtr = 0; 37 38 protected int usedSlots = 0; protected int emptySlots; 41 47 public BoundedBuffer(int capacity) 48 throws IllegalArgumentException 49 { 50 if (capacity <= 0) 51 { 52 throw new IllegalArgumentException ( 53 "Bounded Buffer must have capacity > 0!"); 54 } 55 56 buffer = new Object [capacity]; 57 emptySlots = capacity; 58 } 59 60 63 public BoundedBuffer() 64 { 65 this(DEFAULT_CAPACITY); 66 } 67 68 75 public synchronized int size() 76 { 77 return usedSlots; 78 } 79 80 85 public int capacity() 86 { 87 return buffer.length; 88 } 89 90 95 public synchronized Object peek() 96 { 97 return (usedSlots > 0) 98 ? buffer[takePtr] : null; 99 } 100 101 107 public synchronized boolean offer(Object x) 108 { 109 if (x == null) 110 { 111 throw new IllegalArgumentException ("Bounded Buffer cannot store a null object"); 112 } 113 114 if (emptySlots > 0) 115 { 116 --emptySlots; 117 buffer[putPtr] = x; 118 if (++putPtr >= buffer.length) 119 { 120 putPtr = 0; 121 } 122 usedSlots++; 123 return true; 124 } 125 else 126 { 127 return false; 128 } 129 } 130 131 136 public synchronized Object poll() 137 { 138 if (usedSlots > 0) 139 { 140 --usedSlots; 141 Object old = buffer[takePtr]; 142 buffer[takePtr] = null; 143 if (++takePtr >= buffer.length) 144 { 145 takePtr = 0; 146 } 147 emptySlots++; 148 return old; 149 } 150 else 151 { 152 return null; 153 } 154 } 155 } 156 | Popular Tags |