Skip to content

Instantly share code, notes, and snippets.

@Salil999
Created May 5, 2023 19:13
Show Gist options
  • Save Salil999/fc8bb1478407ec39cd501da9a78c74e8 to your computer and use it in GitHub Desktop.
Save Salil999/fc8bb1478407ec39cd501da9a78c74e8 to your computer and use it in GitHub Desktop.
Synchronized Queue
package com.xgen.svc.mms.svc.ping.observers;
import java.util.concurrent.Semaphore;
public class MyQueue {
private Node front;
private Node rear;
private int numElements;
private final int maxSize;
private final Semaphore mutex = new Semaphore(1);
private static class Node {
private final Integer element;
private Node next;
public Node(Integer pElement) {
this.element = pElement;
}
}
public MyQueue(final int pLimit) {
numElements = 0;
maxSize = pLimit;
}
public void add(final int element) {
try {
mutex.acquire(); // will block until thread is available
final Node toBeAdded = new Node(element);
if (numElements == maxSize) {
return;
}
if (rear == null) {
rear = toBeAdded;
front = toBeAdded;
} else {
rear.next = toBeAdded; // point rear to the next node
rear = toBeAdded; // update rear to be the new node - effectively adding it to the end
}
numElements++;
} catch (InterruptedException e) {
System.out.println(e);
} finally {
mutex.release();
}
}
public Integer get() {
try {
mutex.acquire();
if (front == null) {
return null;
} else {
final Node frontOfQueue = front;
front = front.next; // updates the front of the queue
if (front == null) {
rear = null; // sets rear to null if queue is empty
}
numElements--;
return frontOfQueue.element;
}
} catch (InterruptedException e) {
System.out.println(e);
} finally {
mutex.release();
}
return null;
}
public int getSize() {
try {
mutex.acquire();
return numElements;
} catch (InterruptedException e) {
System.out.println(e);
} finally {
mutex.release();
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment