{"id":6664,"date":"2018-10-16T23:46:20","date_gmt":"2018-10-16T18:16:20","guid":{"rendered":"https:\/\/java2blog.com\/?p=6664"},"modified":"2021-01-26T23:45:05","modified_gmt":"2021-01-26T18:15:05","slug":"custom-blockingqueue-implementation-java","status":"publish","type":"post","link":"https:\/\/java2blog.com\/custom-blockingqueue-implementation-java\/","title":{"rendered":"Custom BlockingQueue implementation in java"},"content":{"rendered":"<p>In this post, we will see how to create your own custom <a href=\"https:\/\/java2blog.com\/blockingqueue-in-java\/\" rel=\"noopener noreferrer\" target=\"_blank\">BlockingQueue<\/a>.<\/p>\n<p>This is one of the most asked <a href=\"https:\/\/java2blog.com\/java-interview-questions\/\" target=\"_blank\" rel=\"noopener noreferrer\">java interview questions<\/a>. You need to implement your own <a href=\"https:\/\/java2blog.com\/blockingqueue-in-java\/\" target=\"_blank\" rel=\"noopener noreferrer\">BlockingQueue<\/a>. This question helps interviewer to get your understanding of <a href=\"https:\/\/java2blog.com\/java-multithreading-interview-questions-and-answers\/\">multithreading concepts<\/a>.<\/p>\n<p>Here is simple implementation of BlockingQueue.<\/p>\n<ul>\n<li>We will use array to store elements in <a href=\"https:\/\/java2blog.com\/blockingqueue-in-java\/\" rel=\"noopener noreferrer\" target=\"_blank\">BlockingQueue<\/a> internally. Size of this array defines maximum number of\u00a0 elements that can reside in BlockingQueue at a time.<\/li>\n<li>We will use <code>lock<\/code> and <code>conditions<\/code> objects to create custom BlockingQueue.<\/li>\n<li>While putting the element in the queue, if the queue is full, then the producer will <code>wait<\/code> for queue to empty.<\/li>\n<li>While consuming element from the queue, if the queue is empty then the <code>consumer<\/code> will wait for the <code>queue<\/code> to get filled.<\/li>\n<\/ul>\n<p>Create a class named <code>CustomBlockingQueue.java<\/code><\/p>\n<pre class=\"java\" name=\"code\" title=\"CustomBlockingQueue.java\">package org.arpit.java2blog;\nimport java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReentrantLock;\n\npublic class CustomBlockingQueue {\n\n    final Lock lock = new ReentrantLock();\n\n    \/\/ Conditions\n    final Condition produceCond  = lock.newCondition(); \n    final Condition consumeCond = lock.newCondition(); \n\n    \/\/ Array to store element for CustomBlockingQueue\n    final Object[] array = new Object[6];\n    int putIndex, takeIndex;\n    int count;\n\n    public void put(Object x) throws InterruptedException {\n\n        lock.lock();\n        try {\n            while (count == array.length){\n                \/\/ Queue is full, producers need to wait\n                produceCond.await();\n            }\n\n            array[putIndex] = x;\n            System.out.println(\"Producing - \" + x);\n            putIndex++;\n            if (putIndex == array.length){\n                putIndex = 0;\n            }\n            \/\/ Increment the count for the array\n            ++count;\n            consumeCond.signal();\n        } finally {\n            lock.unlock();\n        }\n    }\n\n    public Object take() throws InterruptedException {\n        lock.lock();\n        try {\n            while (count == 0){\n                \/\/ Queue is empty, consumers need to wait\n                consumeCond.await();\n            }\n            Object x = array[takeIndex];\n            System.out.println(\"Consuming - \" + x);\n            takeIndex++;\n            if (takeIndex == array.length){\n                takeIndex = 0;\n            }\n            \/\/ reduce the count for the array\n            --count;\n            \/\/ send signal producer\n            produceCond.signal();\n            return x;\n        } finally {\n            lock.unlock();\n        }\n    }\n}\n<\/pre>\n<p>Create another main class which will use above CustomBLockingQueue.<\/p>\n<pre class=\"java\" name=\"code\" title=\"CustomBlockingQueueMain.java\">package org.arpit.java2blog;\n\npublic class CustomBlockingQueueMain {\n\n    public static void main(String[] args) {\n        CustomBlockingQueue customBlockingQueue = new CustomBlockingQueue();\n        \/\/ Creating producer and consumer threads\n        Thread producer = new Thread(new Producer(customBlockingQueue));\n        Thread consumer = new Thread(new Consumer(customBlockingQueue)); \n\n        producer.start();\n        consumer.start();\n    }\n}\n\nclass Producer implements Runnable {\n\n    private CustomBlockingQueue customBlockingQueue;\n\n    public Producer(CustomBlockingQueue customBlockingQueue){\n        this.customBlockingQueue = customBlockingQueue;\n    }\n    @Override\n    public void run() {\n        for (int i = 1; i &lt;= 10; i++) {\n            try {\n                customBlockingQueue.put(i);                            \n            } catch (InterruptedException e) {\n                e.printStackTrace();\n            }\n        }\n    }\n\n}\n\nclass Consumer implements Runnable {\n    private CustomBlockingQueue customBlockingQueue;\n\n    public Consumer(CustomBlockingQueue customBlockingQueue){\n        this.customBlockingQueue = customBlockingQueue;\n    }\n    @Override\n    public void run() {\n        for (int i = 1; i &lt;= 10; i++) {\n            try {\n                customBlockingQueue.take();               \n            } catch (InterruptedException e) {\n                e.printStackTrace();\n            }\n        }\n    }\n\n}\n<\/pre>\n<p>We have created two <a href=\"https:\/\/java2blog.com\/java-runnable-example\/\" target=\"_blank\" rel=\"noopener noreferrer\">Runnable<\/a> classes, one for producer and another for consumer and created two threads using these runnables.<\/p>\n<div style=\"padding: 12px; background-color: #f0f8ff; line-height: 1.4;\">Producing &#8211; 1<br \/>\nProducing &#8211; 2<br \/>\nProducing &#8211; 3<br \/>\nProducing &#8211; 4<br \/>\nProducing &#8211; 5<br \/>\nProducing &#8211; 6<br \/>\nConsuming &#8211; 1<br \/>\nConsuming &#8211; 2<br \/>\nConsuming &#8211; 3<br \/>\nConsuming &#8211; 4<br \/>\nConsuming &#8211; 5<br \/>\nConsuming &#8211; 6<br \/>\nProducing &#8211; 7<br \/>\nProducing &#8211; 8<br \/>\nProducing &#8211; 9<br \/>\nProducing &#8211; 10<br \/>\nConsuming &#8211; 7<br \/>\nConsuming &#8211; 8<br \/>\nConsuming &#8211; 9<br \/>\nConsuming &#8211; 10<\/div>\n<p>Output may vary for you but there can be only 6 elements at a time in the CustomBlockingQueue.<br \/>\nThat&#8217;s all about Custom BlockingQueue implementation in java<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this post, we will see how to create your own custom BlockingQueue. This is one of the most asked java interview questions. You need to implement your own BlockingQueue. This question helps interviewer to get your understanding of multithreading concepts. Here is simple implementation of BlockingQueue. We will use array to store elements in [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":12644,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_mi_skip_tracking":false},"categories":[9,211],"tags":[],"_links":{"self":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/6664"}],"collection":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/comments?post=6664"}],"version-history":[{"count":0,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/6664\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media\/12644"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=6664"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=6664"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=6664"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}