1 18 package freecs.util; 19 20 import freecs.Server; 21 22 27 public class ObjectBuffer { 28 private Object elements[]; 29 private volatile int nextAdd; 30 private volatile int nextRemove; 31 private volatile int capacity; 32 private volatile int counter=0; 33 34 public ObjectBuffer (int cap) throws IllegalArgumentException { 35 if (cap < 2) 36 throw new IllegalArgumentException ("Capacity must be higher than 1 to make sense"); 37 this.capacity = cap; 38 this.nextAdd=0; 39 this.nextRemove=0; 40 elements = new Object [capacity]; 41 if (Server.TRACE_CREATE_AND_FINALIZE) 42 Server.log (this, "++++++++++++++++++++++++++++++++++++++++CREATE", Server.MSG_STATE, Server.LVL_VERY_VERBOSE); 43 } 44 45 public int size () { 46 return counter; 47 } 48 49 public int capacity () { 50 return capacity; 51 } 52 53 public boolean isEmpty () { 54 return counter==0; 55 } 56 57 public boolean isFull () { 58 return counter==capacity; 59 } 60 61 public boolean put (Object o) { 62 if (o==null) 63 throw new NullPointerException ("ObjectBuffer unable to store null"); 64 if (this.isFull ()) 65 return false; 66 elements[nextAdd] = o; 67 nextAdd++; 68 if (nextAdd >= capacity) 69 nextAdd = 0; 70 counter++; 71 return true; 72 } 73 74 public boolean contains (Object o) { 75 for (int i = 0, j=nextRemove; i < counter; i++, j++) { 76 if (j >= capacity) j = 0; 77 if (elements[j].equals (o)) return true; 78 } 79 return false; 80 } 81 82 public Object get () { 83 if (this.isEmpty ()) return null; 84 return elements[nextRemove]; 85 } 86 87 public Object pop () { 88 if (this.isEmpty ()) return null; 89 Object retObj = elements[nextRemove]; 90 elements[nextRemove]=null; 91 nextRemove++; 92 if (nextRemove >= capacity) 93 nextRemove = 0; 94 counter--; 95 return (retObj); 96 } 97 98 public void inhale (ObjectBuffer ob) { 99 elements = new Object [ob.capacity()]; 100 while (!ob.isEmpty()) 101 this.put(ob.pop()); 102 } 103 104 public void resizeTo (int size) throws IllegalArgumentException { 105 if (size < this.size()) 106 throw new IllegalArgumentException ("new capacity may not be lower than current size"); 107 if (size == elements.length) 108 return; 109 Object newelements[] = new Object [size]; 110 synchronized (this) { 111 int csize = this.size(); 112 if (isEmpty()) { 113 elements = newelements; 114 return; 115 } 116 if (nextAdd <= nextRemove) { 117 System.arraycopy(elements,nextRemove,newelements,0,this.capacity()-nextRemove); 118 System.arraycopy(elements, 0, newelements, this.capacity()-nextRemove, nextAdd); 119 } else { 120 System.arraycopy(elements,nextRemove,newelements,0,nextAdd+1); 121 } 122 nextAdd = this.size(); 123 nextRemove=0; 124 elements = newelements; 125 } 126 } 127 128 public void finalize() { 129 if (Server.TRACE_CREATE_AND_FINALIZE) 130 Server.log(this, "----------------------------------------FINALIZED", Server.MSG_STATE, Server.LVL_VERY_VERBOSE); 131 } 132 } | Popular Tags |