FIX: garbage collector on CircularBuffer
[capturemjpeg.git] / src / it / lilik / capturemjpeg / utils / CircularBuffer.java
blob602f282f9c0457d18952a3ad84a44c4b83c2c703
1 /**
2 *
3 */
4 package it.lilik.capturemjpeg.utils;
6 import java.io.ByteArrayInputStream;
8 /**
9 * A circular buffer of <code>ByteArrayInputStream</code>
11 * @author Alessio Caiazza
12 * @author Cosimo Cecchi
15 public class CircularBuffer {
17 /** data storage */
18 private ByteArrayInputStream buffer[];
19 /** last item in <code>CircularBuffer</code> */
20 private int lastIdx;
21 /** first valid item in <code>CircularBuffer</code> */
22 private int firstIdx;
23 /** size of <code>CircularBuffer</code> */
24 private int size;
26 private boolean empty;
28 /** default size */
29 static final int DEFAULT_SIZE = 5;
31 /**
32 * @param size
34 public CircularBuffer(int size) {
35 this.size = size;
36 this.firstIdx = 0;
37 this.lastIdx = 0;
38 this.empty = true;
39 this.buffer = new ByteArrayInputStream[size];
42 /**
45 public CircularBuffer() {
46 this(CircularBuffer.DEFAULT_SIZE);
49 /**
50 * @return the lastIdx
52 public synchronized int getLastIdx() {
53 return lastIdx;
56 /**
57 * @return the firstIdx
59 public synchronized int getFirstIdx() {
60 return firstIdx;
63 /**
64 * Add a an element to the <code>CircularBuffer</code>
66 * @param data the new element
68 public synchronized void push(ByteArrayInputStream data) {
69 buffer[this.lastIdx] = data;
70 if( this.lastIdx == this.firstIdx && !this.empty) {
71 //we have overwritten an element
72 this.firstIdx++;
73 this.firstIdx %= this.size;
75 if (this.empty)
76 this.empty = false;
77 this.lastIdx++;
78 this.lastIdx %= this.size;
81 /**
82 * It counts elements in buffer
83 * @return the number of valid elements
85 public synchronized int getLength() {
86 if (this.empty)
87 return 0;
88 int len = this.lastIdx - this.firstIdx;
89 if (len < 0)
90 len = this.size + len;
91 return len == 0 ? this.size-1 : len;
95 /**
96 * Get the first available element.
98 * @return the first element
99 * @throws IndexOutOfVoundsExceptions
101 public synchronized ByteArrayInputStream pop() {
102 if (isEmpty()) {
103 //TODO:change Exception type
104 throw new IndexOutOfBoundsException("Empty buffer");
106 ByteArrayInputStream res = buffer[this.firstIdx];
107 buffer[this.firstIdx] = null;
108 this.firstIdx++;
109 this.firstIdx %= this.size;
110 if (this.firstIdx == this.lastIdx)
111 this.empty = true;
112 return res;
117 * @return the status of the buffer
119 public synchronized boolean isEmpty() {
120 return this.empty;
123 public int getSize() {
124 return this.size;