Java Multithreading increase 12: Blocking queue Application

Source: Internet
Author: User
Tags diff sorts throw exception

First, class-related properties

Interface BlockingQueue<E> Definition:

 Public InterfaceBlockingqueue<e>extendsQueue<e> {    BooleanAdd (e e); BooleanOffer (e e); voidPut (e e)throwsinterruptedexception; BooleanOffer (e E,LongTimeout, timeunit unit)throwsinterruptedexception; E Take ()throwsinterruptedexception; E Poll (LongTimeout, timeunit unit)throwsinterruptedexception; intremainingcapacity (); BooleanRemove (Object o);  Public    Booleancontains (Object o); intDrainto (collection<?SuperE>c); intDrainto (collection<?SuperE> C,intmaxelements);}

Method Summary

Lock lock is required when all methods operate on arrays that store data in a class.

Method Summary
Boolean offer (E e) Inserts the specified element into this queue (if it is feasible immediately and does not violate the capacity limit), returns true on success, or False if no space is currently available.
Boolean offer (e E, long timeout, timeunit unit) Inserts the specified element into this queue, waiting for the available space (if necessary) before reaching the specified wait time. Determine if there is free space, and if there is no free space, wait for the timeout time to be free.
Boolean Add (E E) Inserts the specified element into this queue (if it is feasible immediately and does not violate the capacity limit), returns true on success, and throws IllegalStateException if no space is currently available. is actually called the Offer (e) method, if the offer (e) returns false throws an exception
void put (e e) Inserts the specified element into this queue, waiting for the available space, if necessary. If no idle will wait until it is interrupt.
E Take () Gets and removes the head of this queue, waiting until the element becomes available (if necessary). If no data is blocked.
E Poll () Gets and removes the header of this queue, without blocking if no data is directly returned false.
E Poll (long timeout, timeunit unit) Gets and removes the header of this queue, waiting for the available elements (if necessary) before the specified wait time. If no data is waiting for timeout time, the timeout does not return null. Similar to Boolean offer (e E, long timeout, timeunit unit)
Boolean remove (Object o) Removes a single instance of the specified element, if any, from this queue. The presence and deletion returns TRUE, otherwise false is returned.
E-Peek () Gets but does not delete the header of this queue, if no data directly returns NULL, does not block.
E Element () The e Peek () method is called, and if the Peek return value is not NULL, element returns the value or throws a Nosuchelementexception exception.
Boolean contains (Object o) Returns true if this queue contains the specified element. Similar to the Remove (Object o) operation.
int Drainto (Collection c) Removes all the elements that are available in this queue and adds them to the given collection.
int Drainto (Collection c, int maxelements) Removes a given number of available elements from this queue at most, and adds them to the given collection.
int remainingcapacity () Returns the number of additional elements this queue can accept in an ideal case without blocking (no memory or resource constraints), or integer.max_value if there is no internal limit.

The Blockingqueue method appears in four forms, for operations that cannot be met immediately but may be satisfied at some point in the future, and these four forms are handled differently: the first is to throw an exception, and the second is to return a special value (null or FALSE, depending on the action). The third is to block the current thread indefinitely before the operation succeeds, and the fourth is to block only within a given maximum time limit before giving up. These methods are summarized in the following table:

Throw Exception Special Values Blocking timed out
Insert Add (E) Offer (e) Put (e) Offer (E, time, unit)
Removed from Remove () Poll () Take () Poll (time, unit)
Check Element () Peek () Not available Not available

Second, the blocking queue in Java

The JDK7 provides 7 blocking queues. respectively is

    • Arrayblockingqueue: A bounded blocking queue consisting of an array structure.
    • Linkedblockingqueue: A bounded blocking queue consisting of a list structure.
    • Priorityblockingqueue: A unbounded blocking queue that supports priority ordering.
    • Delayqueue: An unbounded blocking queue implemented with a priority queue.
    • Synchronousqueue: A blocking queue that does not store elements.
    • LinkedTransferQueue: An unbounded blocking queue consisting of a linked list structure.
    • Linkedblockingdeque: A two-way blocking queue consisting of a linked list structure.
Arrayblockingqueue

Arrayblockingqueue is a bounded blocking queue implemented with arrays. This queue sorts the elements according to the principle of first-out (FIFO). By default, the visitor is not guaranteed a fair access queue, the so-called Fair access queue refers to all the producer or consumer threads blocking, when the queue is available, you can access the queue in the order of blocking, that is, the first blocked producer thread, you can first insert elements into the queue, first blocking the consumer thread, You can get the elements from the queue first. In general, the throughput is reduced to ensure fairness. We can create a fair blocking queue using the following code:

New Arrayblockingqueue (+,true);

ArrayBlockingQueueThe source code is very worthy of analysis, because the use of the previous blog in the lock, condition and other knowledge. can also refer to this blog eighth chapter Arrayblockingqueue Source parsing

code example:

ImportJava.util.concurrent.ArrayBlockingQueue;ImportJava.util.concurrent.BlockingQueue; Public classBlockingqueuetest { Public Static voidMain (string[] args) {FinalBlockingqueue queue =NewArrayblockingqueue (3);  for(inti=0;i<2;i++){            NewThread () { Public voidrun () { while(true){                        Try{Thread.Sleep (Long) (Math.random () *1000)); System.out.println (Thread.CurrentThread (). GetName ()+ "ready to put data!"); Queue.put (1); System.out.println (Thread.CurrentThread (). GetName ()+ "Already set data," + "queue currently has" + queue.size () + "data"); } Catch(interruptedexception e) {e.printstacktrace ();        }}}}.start (); }        NewThread () { Public voidrun () { while(true){                    Try {                        //Change the sleep time here to 100 and 1000 to observe the running resultsThread.Sleep (1000); System.out.println (Thread.CurrentThread (). GetName ()+ "Ready to fetch data!");                        Queue.take (); System.out.println (Thread.CurrentThread (). GetName ()+ "The data has been taken away," + "queue currently has" + queue.size () + "data"); } Catch(interruptedexception e) {e.printstacktrace ();                }}}}.start (); }}
Linkedblockingqueue

Linkedblockingqueue is a bounded blocking queue implemented with a linked list. The default and maximum length for this queue is integer.max_value. This queue sorts the elements according to the FIFO principle.

Priorityblockingqueue

The Priorityblockingqueue is a support-priority unbounded queue. By default, elements are arranged in a natural order, or you can specify the collation of an element by using the comparer comparator. The elements are arranged in ascending order.

Delayqueue

The delayqueue is a unbounded blocking queue that supports delay-fetching elements. Queues are implemented using Priorityqueue. The elements in the queue must implement the delayed interface, and you can specify how long to get the current element from the queue when the element is created. Elements can be extracted from the queue only when the delay expires. We can apply delayqueue to the following scenarios:

    • Cache system Design: You can use Delayqueue to save the cache element's validity period, using a thread to loop query Delayqueue, once the element can be obtained from delayqueue, it means that the cache is valid.
    • Timed task scheduling. Use Delayqueue to save the task and execution time that will be performed on the day, and once the task is taken from Delayqueue, the Timerqueue is implemented using Delayqueue, for example.

The delayed in the queue must implement CompareTo to specify the order of the elements. For example, put the longest delay time at the end of the queue. The implementation code is as follows:

 Public intCompareTo (Delayed other) {if(Other = = This)//Compare zero only if same object                return0; if(Otherinstanceofscheduledfuturetask) {Scheduledfuturetask x=(Scheduledfuturetask) other; Longdiff = time-X.time; if(diff < 0)                    return-1; Else if(diff > 0)                    return1; Else if(SequenceNumber <x.sequencenumber)return-1; Else                    return1; }            LongD = (Getdelay (timeunit.nanoseconds)-Other.getdelay (timeunit.nanoseconds)); return(d = = 0)? 0: ((d < 0)? -1:1); }

How to implement the delayed interface
We can refer to the Scheduledfuturetask class in Scheduledthreadpoolexecutor. This class implements the delayed interface. First: When the object is created, use the time record before the object can be used, the code is as follows:

Long Long period) {            Super(R, result);             this. Time = ns;             this. period = period;             this. SequenceNumber = sequencer.getandincrement ();}

You can then use Getdelay to query the current element for how long it will take, and the code is as follows:

 Public Long getdelay (timeunit unit) {       return Unit.convert (Time-now (), timeunit.nanoseconds);}

Through the constructor can see the delay time parameter NS units are nanoseconds, their own design time is best to use nanosecond, because Getdelay can specify any unit, once in nanoseconds as units, and delay time and precision less than nanosecond trouble. When used, note that Getdelay returns a negative number when time is less than the current period.

How to implement the delay queue

The implementation of the delay queue is simple, and when the consumer gets the element from the queue, it blocks the current thread if the element does not reach the delay time.

long delay = first.getdelay (timeunit.nanoseconds); if (Delay <= 0)     return Q.poll (); Else if NULL )    available.await ();
Synchronousqueue

Synchronousqueue is a blocking queue that does not store elements. Each put operation must wait for a take operation, or the element cannot continue to be added. Synchronousqueue can be seen as a passer-by, responsible for passing the data of producer threads directly to the consumer thread. The queue itself does not store any elements, and is well suited for transitive scenarios, such as data that is used in one thread, passed to another thread, and synchronousqueue throughput is higher than linkedblockingqueue and Arrayblockingqueue.

LinkedTransferQueue

LinkedTransferQueue is an unbounded blocking Transferqueue queue composed of linked list structures. Trytransfer and transfer methods are linkedtransferqueue compared to other blocking queues.

Transfer method. If there is currently a consumer waiting to receive elements (consumers use the Take () method or the poll () method with time limit), the transfer method can immediately transfer (transmit) to the consumer the element that the producer has passed in. If no consumer is waiting for an element to be received, the transfer method stores the element in the queue's tail node and waits until the element is consumed by the consumer before returning. The key code for the transfer method is as follows:

Node pred = Tryappend (s, havedata); return Awaitmatch (S, Pred, E, (how = = TIMED), Nanos);

The first line of code is trying to take the S node that holds the current element as the tail node. The second line of code is to let the CPU spin waiting for consumer spending elements. Because spin consumes the CPU, it spins a certain number of times and uses the Thread.yield () method to pause the currently executing thread and execute other threads.

Trytransfer method. is used to test whether the incoming elements of the producer can be passed directly to the consumer. Returns false if no consumer waits for the receiving element. The difference between the transfer method and the Trytransfer method is that the method returns immediately regardless of whether the consumer receives it or not. The transfer method is to wait until the consumer consumes the return.

For the Trytransfer (e E, long timeout, Timeunit unit) method with a time limit, an attempt is made to pass the producer's incoming element directly to the consumer, but if no consumer consumes the element, it waits for the specified time to return, and if the timeout has not consumed the element, Returns False if the element was consumed within the timeout period, which returns true.

Linkedblockingdeque

Linkedblockingdeque is a two-way blocking queue consisting of a linked list structure. The so-called bidirectional queue means that you can insert and remove elements from both ends of the queue. Double-ended queue because there is an operation queue of the entrance, in the multi-threaded simultaneously queued, also reduced half of the competition. Compared to other blocking queues, Linkedblockingdeque is more addfirst,addlast,offerfirst,offerlast,peekfirst,peeklast and so on, the method of ending with first word, means inserting, Gets (peek) or removes the first element of a double-ended queue. The method ending with the last word, which represents the insertion, gets or removes the final element of the double-ended queue. In addition, the Insert method add is equivalent to AddLast, and removing the method removes the Removefirst. But the Take method is equivalent to Takefirst, not knowing whether it is a JDK bug, or using a method with first and last suffixes to be clearer. The capacity of the queue can be initialized when the linkedblockingdeque is initialized to prevent the transition from expanding when it is re-expanding. In addition, the two-way blocking queue can be used in "work-stealing" mode.

Resources:

"Multithreaded Video" Zhang Xiaoxiang

<< chat concurrency (vii) blocking queues in--java >>

Java Multithreading increase 12: Blocking queue application

Related Article

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.