Simple application of Synchronousqueue

Source: Internet
Author: User

Synchronousqueue is a blocking queue in which each put must wait for a take and vice versa. The synchronization queue does not have any internal capacity, and even one queue has no capacity.
Peek cannot be performed on the synchronization queue because the element exists only when attempting to get the element;
Unless another thread attempts to remove an element, the element cannot be added (using any method), nor can it iterate the queue because there are no elements available for the iteration. The header of the queue is the first queued thread element that is attempted to be added to the queue, and if there are no queued threads, the element is not added and the header is null.
For other Collection methods (for example, contains), Synchronousqueue as an empty collection. This queue does not allow null elements.
It is ideal for transitive designs in which objects running in a thread will have some information,
An event or task is passed to an object that is running in another thread, and it must be synchronized with the object.
For the producer and consumer threads that are waiting, this class supports an optional fair ordering policy. This sort is not guaranteed by default.
However, queues constructed with fair set to true ensure that threads are accessed in a FIFO order. Fairness usually lowers throughput, but it can reduce variability and avoid service loss.
Note 1: It is a blocking queue in which each put must wait for a take, and vice versa. The synchronization queue does not have any internal capacity, and even one queue has no capacity.
Note 2: It is thread-safe and is blocked.
Note 3: null elements are not allowed.
Note 4: The Fair sort policy refers to the call between put threads, or take between threads. A fair ranking strategy can be used to examine the fairness strategy in Arrayblockingqueue.
Note the following methods of 5:synchronousqueue:
* Iterator () always returns empty because there is nothing inside.
* PEEK () always returns NULL.
* PUT () put an element into the queue and wait until another thread comes in and takes the element away.
* Offer () returns immediately after placing an element in the queue, and if it happens that the element was taken away by another thread, the Offer method returns true to be successful;
* Offer (Timeunit.seconds) put an element in the queue but wait for the specified time to return, just as the logical and offer () method is returned.
* Take () Remove and remove the element from the queue (thought to be in the queue ...). ), he will wait until he can get nothing.
* Poll () Remove and remove the element in the queue (thought to be in the queue ...). ), the method will fetch only when it happens that another thread is in the queue to offer data or put data. Otherwise, NULL is returned immediately.
* Poll (Timeunit.seconds) waits for the specified time and then takes out and removes the element in the queue, in fact, waiting for other thread to go in and out.
* IsEmpty () is always true.
* Remainingcapacity () is always 0.
* Remove () and RemoveAll () are always false.

This is an interesting blocking queue in which each insert operation must wait for the removal of another thread, and any removal operation waits for another thread's insert operation. So there is actually no element inside this queue, or capacity is 0, strictly speaking is not a container. The peek operation cannot be called because the queue has no capacity, because elements are only available when the element is removed.

What's the use of a concurrent queue with no capacity? Or what is the meaning of existence?

The implementation of Synchronousqueue is very complex, of course, if you really want to analyze or can get some experience, but the previous analysis of excessive structure, found increasingly trapped in data structures and algorithms inside. My intention is to use concurrency to make the best use of available resources by studying the principles of concurrency. So in the following chapters as far as possible in the study of data structures and algorithms, but in order to understand the principle of the inside, it will be necessary to avoid some of this knowledge, hope that the back can be enough.

Back to the topic. There is no capacity inside the synchronousqueue, but because an insert operation always corresponds to a removal operation, the reverse is also required. Then an element will not synchronousqueue inside for a long time, and once the insert thread and the thread are removed, the element is quickly transferred from the insertion thread to the removal thread. This means that this is more like a channel (pipeline), where resources are quickly passed from one direction to another.

In particular, although the element does not "stay" within Synchronousqueue, it does not mean that the synchronousqueue does not have a queue inside. In fact, synchronousqueue the maintainer thread queue, that is, the insert thread or the removal thread will be wired when it does not exist simultaneously. Since there is a queue, there is also fairness and unfairness, and fairness guarantees that the inserted thread being waited on or the removal thread will pass the resource in FIFO order.

Obviously this is a fast way to pass elements, which means that in this case the element is always in the quickest way from the inserted (producer) to the removed (consumer), which in the multitasking queue is the quickest way to process the task. This feature is also mentioned more in the related chapters of the online pool.

Synchronousqueue<e> is defined as follows

Synchronousqueue<e>extends abstractqueue<e>implements Blockingqueue<e>, Serializable

As can be seen from the above, it implements Blockingqueue<e>, so it is blocking the queue, from the name, it is synchronized.

It simulates a function similar to the one-hand delivery of money in life, like that of a delivery model that is not suitable for use with Synchronousqueue after cash on delivery or first payment.
The first thing to know is that Synchronousqueue does not have the ability to accommodate elements, i.e. its isempty () method always returns True, but it feels like it can only hold one element.

In addition, when creating Synchronousqueue, you can pass a Boolean parameter to specify whether it is a thread that accesses it in a FIFO order, and true to honor the FIFO.


The following uses the Synchronousqueue simulation to produce only one product producer-consumer model

Import Java.util.random;import Java.util.concurrent.synchronousqueue;import Java.util.concurrent.timeunit;public Class Test19 {public static void main (string[] args) {synchronousqueue<integer> queue = new Synchronousqueue<int Eger> (); new Customer (queue). Start (); New Product (queue). Start (); Static class Product extends Thread{synchronousqueue<integer> queue;public product (Synchronousqueue<integer > Queue) {this.queue = queue;} @Overridepublic void Run () {while (true) {int rand = new Random (). Nextint (1000); System.out.println ("produced a product:" +rand); System.out.println ("Wait three seconds to ship out ..."); try {TimeUnit.SECONDS.sleep (3);} catch (Interruptedexception e) {e.printstacktrace ();} Queue.offer (rand);}}} Static class Customer extends Thread{synchronousqueue<integer> queue;public customer (synchronousqueue< Integer> queue) {this.queue = queue;} @Overridepublic void Run () {while (true) {try {System.out.println ("consumes a product:" +queue.take ());} catch (Interruptedexception e) {e.printstacktrace ();} SysTem.out.println ("------------------------------------------");}} /** * Operation Result: * Production of a product: 464 wait three seconds after delivery out ... Consumption of a product: 773------------------------------------------produced a product: 547 wait three seconds after delivery out ... Consumption of a product: 464------------------------------------------produced a product: 87 wait three seconds after delivery out ... Consumption of a product: 547------------------------------------------*/}

  

Simple application of Synchronousqueue

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.