Skip to content

Instantly share code, notes, and snippets.

@siasur
Last active March 14, 2018 02:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siasur/9136814ebe1b3e087d0674c6c45c6379 to your computer and use it in GitHub Desktop.
Save siasur/9136814ebe1b3e087d0674c6c45c6379 to your computer and use it in GitHub Desktop.
public class MessageQueue<T> {
private static final int MAX_SIZE = 255;
private T[] messages;
private int lastReadIndex;
private int lastInsertIndex;
private int adjustIndex(int index) {
if (index >= MAX_SIZE) {
return 0;
}
return index;
}
/**
* Constructor of the {@link MessageQueue}
*
* @author Mischa
*/
@SuppressWarnings("unchecked") // Java doesn't like to create an Array of a generic type...
public MessageQueue() {
messages = (T[]) new Object[MAX_SIZE];
}
/**
* Pushes a new entry into the queue.
* This function will block when the queue is full.
*
* @param msg The entry to push on the stack
* @throws InterruptedException
*/
public synchronized void push(T msg) throws InterruptedException {
int newIndex = adjustIndex(lastInsertIndex + 1);
// Check if we can push the message
while (messages[newIndex] != null) {
wait();
}
// Push the message
messages[newIndex] = msg;
lastInsertIndex = newIndex;
notifyAll();
}
/**
* Pulls one entry from the queue.
* The entry will be returned and removed from the queue.
*
* @return The entry from the queue
*/
public synchronized T pull() {
int newIndex = adjustIndex(lastReadIndex + 1);
T shouldReturn = messages[newIndex];
messages[newIndex] = null;
lastReadIndex = newIndex;
notifyAll();
return shouldReturn;
}
/**
* Checks if there is an entry in the queue.
*
* @return <code>true</code>, when there is an entry in the queue
*/
public synchronized Boolean hasMessage() {
if (lastInsertIndex > -1) {
int newIndex = adjustIndex(lastReadIndex + 1);
if (messages[newIndex] != null) {
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment