Created
December 27, 2023 09:59
-
-
Save hocyadav/5447026432d5ecfd6ce44ee1a2abcdd4 to your computer and use it in GitHub Desktop.
prodcuer consumer pattern using own blocking queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
simple producer-consumer using java blocking queue : https://gist.github.com/hocyadav/58586e209215cca3ce88c80d7c0d1dc8