forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCircularBuffer.java
58 lines (46 loc) · 1.45 KB
/
CircularBuffer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.thealgorithms.datastructures.buffers;
import java.util.concurrent.atomic.AtomicInteger;
public class CircularBuffer<Item> {
private final Item[] buffer;
private final CircularPointer putPointer;
private final CircularPointer getPointer;
private final AtomicInteger size = new AtomicInteger(0);
public CircularBuffer(int size) {
// noinspection unchecked
this.buffer = (Item[]) new Object[size];
this.putPointer = new CircularPointer(0, size);
this.getPointer = new CircularPointer(0, size);
}
public boolean isEmpty() {
return size.get() == 0;
}
public boolean isFull() {
return size.get() == buffer.length;
}
public Item get() {
if (isEmpty()) return null;
Item item = buffer[getPointer.getAndIncrement()];
size.decrementAndGet();
return item;
}
public boolean put(Item item) {
if (isFull()) return false;
buffer[putPointer.getAndIncrement()] = item;
size.incrementAndGet();
return true;
}
private static class CircularPointer {
private int pointer;
private final int max;
CircularPointer(int pointer, int max) {
this.pointer = pointer;
this.max = max;
}
public int getAndIncrement() {
if (pointer == max) pointer = 0;
int tmp = pointer;
pointer++;
return tmp;
}
}
}