BlockingQueue inward Java is added inward Java 1.5 along amongst diverse other concurrent Utility classes similar ConcurrentHashMap, Counting Semaphore, CopyOnWriteArrrayList etc. BlockingQueue is a unique collection type which non alone shop elements only every bit good supports menstruum command past times introducing blocking if either BlockingQueue is total or empty. take() method of BlockingQueue volition block if Queue is empty together with put() method of BlockingQueue volition block if Queue is full. This holding makes BlockingQueue an ideal alternative for implementing Producer consumer blueprint pattern where ane thread insert chemical cistron into BlockingQueue together with other thread consumes it. In this Java tutorial nosotros volition larn nearly What is BlockingQueue inward Java, How to role BlockingQueue, ArrayBlockingQueue together with LinkedBlockingQueue together with about of import properties of it.
Important properties of BlockingQueue inward Java
Before using whatever novel Collection shape e.g. BlockingQueue, I e'er read at that topographic point API documentation to know to a greater extent than nearly it. There are e'er about of import points which is worth remembering together with avoids potential programming errors piece using novel Collection class. Following listing of points nearly BlockingQueue inward Java volition help to larn together with sympathise to a greater extent than nearly it.
1) BlockingQueue inward Java doesn't allow cipher elements, diverse implementation of BlockingQueue similar ArrayBlockingQueue, LinkedBlockingQueue throws NullPointerException when you lot essay to add together cipher on queue.
BlockingQueue<String> bQueue = new ArrayBlockingQueue<String>(10);
//bQueue.put(null); //NullPointerException - BlockingQueue inward Java doesn't allow null
bQueue = new LinkedBlockingQueue<String>();
bQueue.put(null);
Exception inward thread "main" java.lang.NullPointerException
at java.util.concurrent.LinkedBlockingQueue.put(LinkedBlockingQueue.java:288)
//bQueue.put(null); //NullPointerException - BlockingQueue inward Java doesn't allow null
bQueue = new LinkedBlockingQueue<String>();
bQueue.put(null);
Exception inward thread "main" java.lang.NullPointerException
at java.util.concurrent.LinkedBlockingQueue.put(LinkedBlockingQueue.java:288)
2) BlockingQueue tin endure bounded or unbounded. Influenza A virus subtype H5N1 bounded BlockingQueue is ane which is initialized amongst initial capacity together with telephone phone to put() volition endure blocked if BlockingQueue is total together with size is equal to capacity. This bounding nature makes it ideal to role a shared queue betwixt multiple threads similar inward most mutual Producer consumer solutions inward Java. An unbounded Queue is ane which is initialized without capacity, genuinely past times default it initialized amongst Integer.MAX_VALUE. most mutual instance of BlockingQueue uses bounded BlockingQueue every bit shown inward below example.
BlockingQueue<String> bQueue = new ArrayBlockingQueue<String>(2);
bQueue.put("Java");
System.out.println("Item 1 inserted into BlockingQueue");
bQueue.put("JDK");
System.out.println("Item 2 is inserted on BlockingQueue");
bQueue.put("J2SE");
System.out.println("Done");
Output:
Item 1 inserted into BlockingQueue
Item 2 is inserted on BlockingQueue
bQueue.put("Java");
System.out.println("Item 1 inserted into BlockingQueue");
bQueue.put("JDK");
System.out.println("Item 2 is inserted on BlockingQueue");
bQueue.put("J2SE");
System.out.println("Done");
Output:
Item 1 inserted into BlockingQueue
Item 2 is inserted on BlockingQueue
This code volition alone insert Java together with JDK into BlockingQueue together with and thence it volition block piece inserting tertiary chemical cistron J2SE because size of BlockingQueue is 2 here.
3)BlockingQueue implementations similar ArrayBlockingQueue, LinkedBlockingQueue together with PriorityBlockingQueue are thread-safe. All queuing method uses concurrency command together with internal locks to perform functioning atomically. Since BlockingQueue every bit good extend Collection, volume Collection operations similar addAll(), containsAll() are non performed atomically until whatever BlockingQueue implementation specifically supports it. So telephone phone to addAll() may neglect after inserting brace of elements.
4) Common methods of BlockingQueue is are put() together with take() which are blocking methods inward Java together with used to insert together with retrive elements from BlockingQueue inward Java. put() volition block if BlockingQueue is total together with take() volition block if BlockingQueue is empty, telephone phone to take() removes chemical cistron from caput of Queue every bit shown inward next example:
BlockingQueue<String> bQueue = new ArrayBlockingQueue<String>(2);
bQueue.put("Java"); //insert object into BlockingQueue
System.out.println("BlockingQueue after put: " + bQueue);
bQueue.take(); //retrieve object from BlockingQueue inward Java
System.out.println("BlockingQueue after take: " + bQueue);
Output:
BlockingQueue after put: [Java]
BlockingQueue after take: []
bQueue.put("Java"); //insert object into BlockingQueue
System.out.println("BlockingQueue after put: " + bQueue);
bQueue.take(); //retrieve object from BlockingQueue inward Java
System.out.println("BlockingQueue after take: " + bQueue);
Output:
BlockingQueue after put: [Java]
BlockingQueue after take: []
5) BlockingQueue interface extends Collection, Queue together with Iterable interface which provides it all Collection together with Queue related methods similar poll(), together with peak(), dissimilar take(), peek() method returns caput of the queue without removing it, poll() every bit good retrieves together with removes elements from caput only tin expect till specified fourth dimension if Queue is empty.
BlockingQueue<String> linkedBQueue = new LinkedBlockingQueue<String>(2);
linkedBQueue.put("Java"); //puts object into BlockingQueue
System.out.println("size of BlockingQueue earlier peek : " + linkedBQueue.size());
System.out.println("example of peek() inward BlockingQueue: " + linkedBQueue.peek());
System.out.println("size of BlockingQueue after peek : " + linkedBQueue.size());
System.out.println("calling poll() on BlockingQueue: " + linkedBQueue.poll());
System.out.println("size of BlockingQueue after poll : " + linkedBQueue.size());
Output:
size of BlockingQueue earlier peek : 1
instance of peek() inward BlockingQueue: Java
size of BlockingQueue after peek : 1
calling poll() on BlockingQueue: Java
size of BlockingQueue after poll : 0
linkedBQueue.put("Java"); //puts object into BlockingQueue
System.out.println("size of BlockingQueue earlier peek : " + linkedBQueue.size());
System.out.println("example of peek() inward BlockingQueue: " + linkedBQueue.peek());
System.out.println("size of BlockingQueue after peek : " + linkedBQueue.size());
System.out.println("calling poll() on BlockingQueue: " + linkedBQueue.poll());
System.out.println("size of BlockingQueue after poll : " + linkedBQueue.size());
Output:
size of BlockingQueue earlier peek : 1
instance of peek() inward BlockingQueue: Java
size of BlockingQueue after peek : 1
calling poll() on BlockingQueue: Java
size of BlockingQueue after poll : 0
6)Other of import methods from BlockingQueue inward Java is remainingCapacity() together with offer(), quondam returns release remaining infinite inward BlockingQueue, which tin endure filled without blocking piece after insert object into queue if possible together with render truthful if success together with faux if neglect dissimilar add() method which throws IllegalStateException if it fails to insert object into BlockingQueue. Use offer() over add() wherever possible.
Usage of BlockingQueue inward Java
There tin endure many creative usage of BlockingQueue inward Java given its menstruum command ability. Two of the most mutual ways I come across programmer uses BlockingQueue is to implement Producer Consumer blueprint pattern together with implementing Bounded buffer inward Java. It surprisingly made coding together with inter thread communication over a shared object rattling easy.
ArrayBlockingQueue together with LinkedBlockingQueue inward Java
ArrayBlockingQueue together with LinkedBlockingQueue are mutual implementation of BlockingQueue<E> interface. ArrayBlockingQueue is backed past times array and Queue impose orders every bit FIFO. caput of the queue is the oldest chemical cistron inward price of fourth dimension together with tail of the queue is youngest element. ArrayBlockingQueue is every bit good fixed size bounded buffer on the other manus LinkedBlockingQueue is an optionally bounded queue built on overstep of Linked nodes. In price of throughput LinkedBlockingQueue provides higher throughput than ArrayBlockingQueue inward Java.
That’s all on What is BlockingQueue inward Java together with How to role it. We receive got seen ii convenient implementation of BlockingQueue i.e. ArrayBlockingQueue together with LinkedBlockingQueue which comes along amongst Java API. If you lot are implementing Producer Consumer blueprint pattern inward Java, consider using BlockingQueue, it non alone brand coding slowly only every bit good performs meliorate together with furnish meliorate robustness together with stability than writing your ain BlockingQueue or using naked wait together with notify method.
Further Learning
Java In-Depth: Become a Complete Java Engineer
How to kind ArrayList inward contrary gild inward Java