Showing posts with label Queue. Show all posts
Showing posts with label Queue. Show all posts

Sunday, November 24, 2019

Producer Consumer Solution Using Blockingqueue Inward Coffee Thread

Producer Consumer job is 1 of the classic multi-threading problems inwards estimator scientific discipline together with the multi-threading world. It's tricky because it involves inter-thread communication, only it's of import because most of the multi-threading problems fits into this category. There are many ways to solve producer consumer job inwards Java e.g. you lot tin solve this past times using wait() together with notify() method, equally discussed here, or you lot tin job the Semaphore to solve this problem. In this article, you lot volition acquire a 3rd way to solve the producer-consumer job past times using the BlockingQueue inwards Java. It is arguably the simplest way to solve this job inwards whatever programming linguistic communication because blocking queue information construction non alone provides storage only also provides catamenia command together with thread-safety, which makes the code actually simple. Brian Goetz has also explained this cardinal degree together with designing inwards his classic Java Concurrency inwards Practice book, a must read for serious Java developers.



Producer Consumer Pattern using BlockingQueue

Java provides a built-in blocking queue information construction inwards java.util.concurrent package. It was added on JDK amongst multiple concurrent utilities e.g. CountDownLatch, CyclicBarrier, together with Callable together with Future classes.

The java.util.concurrent.BlockingQueue is an interface together with comes amongst 2 ready-made implementations thence ArrayLinkedBlockingQueue together with LinkedBlockingQueue. As the cite suggests, 1 is backed past times an array piece other is backed past times linked list.



In guild to solve the producer-consumer problem, nosotros volition create 2 threads which volition copy producer together with consumer together with instead of shared object nosotros volition job the shared BlockingQueue. Our code volition hold upwards simple, the producer will add together an chemical gene into queue together with consumer volition take the element.

BlockingQueue provides a put() method to shop the chemical gene together with take() method to cry upwards the element. Both are blocking method, which agency put() volition block if the queue has reached its capacity together with at that spot is no house to add together a novel element. Similarly, take() method volition block if blocking queue is empty. So, you lot tin run across that critical requirement of the producer-consumer designing is met correct there, you lot don't necessitate to position whatever thread synchronization code.

run() method, which adds 10 Integer object starting from 0.

After adding each element, the Producer thread is sleeping for 200 milliseconds past times calling Thread.sleep() method. This gives fourth dimension to the Consumer thread to swallow elements from Queue, that's why our code never blocks.

You tin run across that our Producer together with Consumer threads are working inwards sync because of Thread.sleep() nosotros receive got introduced afterward put() call. You tin farther experiment amongst the code past times removing the code to pause the Producer thread or inserting recess on Consumer thread to  create scenarios where Queue is total or empty.


Benefits of using BlockingQueue to solve Producer Consumer
  • Simple code, much to a greater extent than readable
  • less fault prone equally you lot don't receive got to bargain amongst whatever external synchronization

That's all virtually how to solve producer consumer job using BlockingQueue inwards Java. In production code, you lot should e'er job BlockingQueue, using wait() together with notify() is neither slowly non desirable given you lot receive got amend tools available. Even Joshua Bloch's has advised inwards Effective Java to prefer higher concurrency utilities together with libraries instead of writing your ain code. Remember, the code is alone written 1 time only read numerous fourth dimension for maintenance, troubleshooting together with back upwards purpose.

Further Learning
Multithreading together with Parallel Computing inwards Java
answer)
  • The divergence betwixt synchronized block together with methods inwards Java? (answer)
  • The divergence betwixt Callable together with Runnable inwards Java? (answer)
  • Difference betwixt extends Thread vs implements Runnable inwards Java? (answer)
  • When to job the volatile variable inwards Java? (answer)

  • Thursday, October 31, 2019

    How To Role Queue Collection Inward Java? An Illustration Tutorial

    The JDK provides an implementation of several information construction inwards Java collection framework, e.g., ArrayList is a dynamic array, LinkedList represents a linked list, HashMap represents a hash tabular array information structure, together with Queue interface stand upward for queue information structure. Btw, If you lot are non familiar amongst information construction itself, thus you lot tin dismiss likewise see Introduction to Data Structures & Algorithms inwards Java, an fantabulous course of report to start amongst the essential information construction inwards Java. The Queue information construction allows you lot to procedure elements inwards the start inwards start out order, together with that's why it is likewise known equally a FIFO information structure. In fellowship to render start inwards primary out functionality, it allows you lot to insert information at i cease together with delete information from other ends, likewise known equally consuming data. If you lot involve to procedure objects inwards the FIFO order, you lot tin dismiss usage a Queue to shop them.

    Since Queue is an interface, you lot cannot usage it directly, either you lot involve to usage its implementation classes. JDK provides 2 implementations of the Queue interface, a PriorityQueue together with LinkedList.

    H5N1 PriorityQueue allows you lot to eat elements based upon their priority, rattling useful to implement a TODO listing where the highest priority detail should e'er travel at the caput together with consumed first. On the other hand, a LinkedList is a classical linked list, but you lot tin dismiss usage it equally Queue equally well.

    In fellowship to usage Queue, you lot involve to travel familiar amongst essential methods to perform basic operations, e.g. adding elements into a queue, consuming elements from a queue or checking elements without consuming.

    Any Queue implementation provides 2 sets of a method to perform this basic operation, the start laid of methods are derived from java.util.Collection interface because Queue is likewise a Collection together with instant laid of methods is added to copy queue information construction behavior.

    For example, to add together an chemical gene to the Queue you lot tin dismiss usage either add() or offer() method together with to take away an chemical gene you lot tin dismiss usage remove() or poll() methods.

    The alone divergence betwixt 2 sets of the method is that methods from Collection throw Exception when they neglect but other sets of methods, e.g. offer(), poll() and peek() returns null or false when they fail.

    If you lot are non familiar amongst the Java Collection framework thus NoSuchElementException is thrown.


    Methods which Returns exceptional value on Failure

    offer(E e): adds the chemical gene e to the tail of the queue. If the insertion is successful, the method returns true; otherwise, it returns false. Generally, if at that spot are capacity bounds, it is preferred to usage add together method instead.

    poll(): like remove() function, it retrieves together with removes the caput of the queue. The alone divergence from remove() is that poll() functioning returns null when the queue is empty.

    peek(): only similar element() functioning it retrieves together with returns the caput of the queue, without removing it. In this situation, when the queue is empty, it returns null.

    I mostly prefer to usage the methods from Queue interface, i.e. offer, poll, together with peek because they don't neglect amongst Exception together with they amend readability.  If you lot run across add() you lot are non certain whether you lot are dealing amongst a Queue or Collection, but if you lot run across the offer(), you lot know that you lot are dealing amongst a Queue.

    Btw, If you lot haven't read it withal thus read Effective Java third edition for to a greater extent than of such practical tips on Java programming.




    How to usage Queue inwards Java

    Here is a uncomplicated event of using the Queue interface inwards Java. This flat behaves the same equally Queue information structure, e.g. you lot tin dismiss produce FIFO processing.  If you lot sympathise that it would travel rattling tardily to usage this interface together with its dissimilar implementation class, e.g. PriorityQueue, LinkedList, together with others.


    import java.util.LinkedList; import java.util.Queue;  /**  * Java Program to usage Queue  interface  * @author Javin Paul  */ public class QueueDemo{      public static void main(String args[]) {          Queue<String> months = new LinkedList<String>();          // Example 1 - Adding objects into Queue         System.out.println("Queue : " + months);         months.add("JAN");         months.add("FEB");         months.add("MAR");         months.add("APR");         months.add("MAY");         months.add("JUN");         months.add("JUL");         months.add("AUG");         months.add("SEP");         months.add("OCT");         months.add("NOV");         months.add("DEC");         System.out.println("Queue subsequently initialization : " + months);          // Example 2 - Checking if an Object is inwards Queue or not         boolean hasMay = months.contains("MAY");         System.out.println("Does Queue has MAY inwards it? " + hasMay);          // Example iii - Retrieving value from caput of Queue         String caput = months.peek();         System.out.println("Head of the Queue contains : " + head);          // Example four - Removing objects from caput of the Queue         String oldHead = months.poll();         String newHead = months.peek();         System.out.println("old caput : " + oldHead);         System.out.println("new caput : " + newHead);          // Example five - Another agency to take away caput objects from Queue         months.remove();         System.out.println("now caput of Queue is: " + months.peek());      }  }   Output : Queue : [] Queue subsequently initialization : [JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC] Does Queue has MAY inwards it? true Head of the Queue contains : JAN former caput : JAN new caput : FEB at nowadays caput of Queue is: MAR


    It is worth to refer that FIFO (first-in-first-out) is the most mutual agency to fellowship the elements inwards the Queue, but that's non the alone order.

    You convey PriorityQueue on which you lot tin dismiss fellowship chemical gene based upon fellowship defined past times their Comparator or Comparable, it volition guarantee that caput volition e'er travel the lowest element.

    That's all virtually how to usage Queue inwards Java. You convey the luxury to pick out betwixt 2 sets of methods, i which throws an exception together with other which returns cypher together with you lot tin dismiss pick out depending on your requirements.

    You tin dismiss non alone usage the Queue interface to impose FIFO fellowship of processing but likewise usage dissimilar implementations, e.g. PriorityQueue to procedure elements based upon fellowship defined they their Comparator.

    Other Java tutorials together with resources you lot may like

    Thanks for reading this article thus far. If you lot similar this tutorial, thus delight part it amongst your friends together with colleagues. If you lot convey whatever questions or feedback, thus delight drib a note.