Skip to content

Instantly share code, notes, and snippets.

@hocyadav
Created December 27, 2023 09:59
Show Gist options
  • Save hocyadav/5447026432d5ecfd6ce44ee1a2abcdd4 to your computer and use it in GitHub Desktop.
Save hocyadav/5447026432d5ecfd6ce44ee1a2abcdd4 to your computer and use it in GitHub Desktop.
prodcuer consumer pattern using own blocking queue
import lombok.SneakyThrows;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author Hariom Yadav
* @since 05-Dec-2023
*/
public class MyBlockingQueue {
Queue<Integer> qq = new LinkedList<>();
int maxSize = 5;
@SneakyThrows
public synchronized void put(int val){
if (qq.size() >= maxSize) wait();
qq.add(val);
notifyAll();
}
@SneakyThrows
public synchronized Integer get(){
if (qq.isEmpty()) wait();
Integer polled = qq.poll();
notifyAll();
return polled;
}
}
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author Hariom Yadav
* @since 05-Dec-2023
*/
public class TestMyBlockingQueue {
@SneakyThrows
@Test
public void foo2(){
MyBlockingQueue queue = new MyBlockingQueue();
AtomicInteger atomic = new AtomicInteger(0);
Runnable producer = () -> {
while (true) {
try {
Thread.sleep(1000);
queue.put(atomic.getAndIncrement());
System.out.println("Producer = " + queue.qq);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
};
Runnable consumer = () -> {
while (true) {
try {
Thread.sleep(2000);
System.out.println("Consumer = " + queue.get());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
};
new Thread(producer).start();
new Thread(consumer).start();
// new Thread(consumer).start();// we can add multiple consumer ✅
Thread.sleep(50000);
}
}
@hocyadav
Copy link
Author

simple producer-consumer using java blocking queue : https://gist.github.com/hocyadav/58586e209215cca3ce88c80d7c0d1dc8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment