Java Multithreaded Series 6-blocking queues

Source: Internet
Author: User
Tags sorts

This article will use the example of a classic producer consumer to further consolidate the Java multithreading Communication, and introduce the use of blocking queues to simplify the program

Here is an example of a classic producer consumer:

Assuming that the buffer is used to store integers, the buffer size is restricted. The buffer provides the write (int) method to add an integer to the buffer, and the decency Read () method reads from the buffer and deletes an integer. For synchronous operation, a lock with two conditions is used, notempty (buffer non-empty) and notfull (buffer is not full). When an int is added to the task phase buffer, if the buffer is full, the task waits for the Notfull state, and the task waits for the Notempty state if the buffer is empty when the task deletes an int from the buffer.

Importjava.util.LinkedList;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.locks.Condition;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock; Public classConsumerproducer {Private StaticBuffer buffer =NewBuffer ();  Public Static voidMain (string[] args) {//Create a thread poolExecutorservice executor = Executors.newfixedthreadpool (2); Executor.execute (NewProducertask ()); Executor.execute (NewConsumertask ());    Executor.shutdown (); }     Private Static classProducertaskImplementsRunnable {@Override Public voidrun () {Try {                inti = 1;  while(true) {System.out.println ("Producer writes" +i); Buffer.write (i++); Thread.Sleep ((int) (Math.random () * 10000)); }            } Catch(interruptedexception e) {e.printstacktrace (); }        }    }     Private Static classConsumertaskImplementsRunnable { Public voidrun () {Try {                 while(true) {System.out.println ("\t\t\tconsumer reads" +Buffer.read ()); Thread.Sleep ((int) (Math.random () * 10000)); }            } Catch(interruptedexception e) {e.printstacktrace (); }        }    }     Private Static classBuffer {Private Static Final intcapacity = 1;//Buffer sizelinkedlist<integer> queue =NewLinkedlist<integer>(); //Create a lock        Private StaticLock lock =NewReentrantlock (); //Create two conditions        Private StaticCondition Notempty =lock.newcondition (); Private StaticCondition Notfull =lock.newcondition ();  Public voidWriteintvalue) {Lock.lock ();//Request Lock            Try {                 while(queue.size () = =capacity) {System.out.println ("Wait for Notfull condition");                Notfull.await ();                } queue.offer (value); Notempty.signal (); //notempty Condition Signal             } Catch(Exception e) {e.printstacktrace (); } finally{lock.unlock ();//Release Lock}} @SuppressWarnings ("Finally")         Public intRead () {intValue = 0;            Lock.lock (); Try {                 while(Queue.isempty ()) {System.out.println ("\t\t\twait for Notempty condition");                Notempty.await (); } Value=Queue.remove ();             Notfull.signal (); } Catch(Exception e) {e.printstacktrace (); } finally{lock.unlock (); returnvalue; }        }    }}

Blocking queue

Blocking queues cause threads to block when attempting to add elements in a full queue or to delete elements from an empty queue. Blockqueue interface extends Java.util.queue, and provides synchronous put and take methods to queue headers to add elements, and to delete elements from the end of a queue

Java supports three specific block queues, Arrayblockingqueue, Linkedblockingqueue, and Priorityblockingqueue, all in the Java.util.concurrent package.

Arrayblockingqueue

A bounded blocking queue supported by the array. This queue sorts elements by FIFO (first-in, in-out) principle. The head of the queue is the element that has the longest time in the queue. The tail of the queue is the element that has the shortest time in the queue. The new element is inserted at the end of the queue, and the queue fetch operation starts from the head of the queue to get the element.

This is a typical "bounded buffer", in which the fixed-size array keeps the elements inserted by the producer and the user extracts the elements. Once such a buffer is created, it is no longer possible to increase its capacity. Attempting to put an element into the full queue causes the operation to be blocked, and attempting to extract elements from the empty queue will cause similar blocking.

This class supports an optional fairness policy for ordering the waiting producer and consumer threads. By default, this sort is not guaranteed. However, a queue constructed by setting fairness (fairness) to true allows threads to be accessed in FIFO order. Fairness typically reduces throughput, but it also reduces variability and avoids "imbalances".

Linkedblockingqueue

An arbitrarily scoped blocking queue based on the linked node. This queue sorts elements by FIFO (first-in, in-out). The head of the queue is the longest element in the queue. The tail of the queue is the element with the shortest time in the queue. The new element is inserted at the end of the queue, and the queue fetch operation obtains the element at the head of the queue. The throughput of a linked queue is typically higher than an array-based queue, but in most concurrent applications, its predictable performance is low.

The optional capacity range constructs method parameters as a way to prevent the queue from over-scaling. If no capacity is specified, it is equal to Integer.MAX_VALUE . The link node is created dynamically each time it is inserted, unless the node is inserted to make the queue out of capacity.

Priorityblockingqueue

A unbounded blocking queue that uses PriorityQueue the same order rules as the class and provides a blocking fetch operation. Although this queue is logically unbounded, attempting to perform an add operation will also fail when the resource is exhausted (causing outofmemoryerror). This class does not allow the use of null elements. Priority queues that rely on natural order also do not allow the insertion of objects that cannot be compared (this can cause classcastexceptionto be thrown).

The following simplified code is used with Arrayblockingqueue:

ImportJava.util.concurrent.ArrayBlockingQueue;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classConsumerproducerusingblockingqueue {Private Staticarrayblockingqueue<integer> buffer =NewArrayblockingqueue<integer> (2);  Public Static voidMain (string[] args) {//Create a thread poolExecutorservice executor = Executors.newfixedthreadpool (2); Executor.execute (NewProducertask ()); Executor.execute (NewConsumertask ());    Executor.shutdown (); }    Private Static classProducertaskImplementsRunnable {@Override Public voidrun () {Try {                inti = 1;  while(true) {System.out.println ("Producer writes" +i); Buffer.put (i++); Thread.Sleep ((int) (Math.random () * 10000)); }            } Catch(interruptedexception e) {e.printstacktrace (); }        }    }     Private Static classConsumertaskImplementsRunnable { Public voidrun () {Try {                 while(true) {System.out.println ("\t\t\tconsumer reads" +Buffer.take ()); Thread.Sleep ((int) (Math.random () * 10000)); }            } Catch(interruptedexception e) {e.printstacktrace (); }        }    } }

As you can see, the code is reduced by half, mainly because synchronization has been implemented in the Arrayblockingqueue, so no manual coding is required

Java Multithreaded Series 6-blocking queues

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.