Translation Java Concurrent Series--blockingqueue__java

Source: Internet
Author: User

The Blockingqueue interface in the Java.util.concurrent package is a blocking queue capable of thread-safe insertion and removal of object instances. This article will show you how to use Blockingqueue.

This article does not discuss how to use Java to implement a blockingqueue. If you are interested in going to your own implementation, you can refer to the contents of the blocking queue section of the Java Concurrency Tutorial.

Blockingqueue Usage
Blockingqueue is typically used for a thread production object while another thread consumes those objects. The following illustration is an elaboration of this principle:
! [Blockingqueue principle] [Http://tutorials.jenkov.com/images/java-concurrency-utils/blocking-queue.png]

The production line continues to generate new objects and inserts them into the blocking queue until the queue reaches its critical point of storage capacity. In other words, the capacity of the blocking queue is limited. If the blocking queue reaches the critical point of storage, it will block until the production line attempts to insert a new object until the consuming thread extracts an object from the blocked queue.
The consumer thread continues to remove the object from the blocking queue and process it. When a consumer thread tries to fetch an object from an empty queue, it blocks until the production line puts an object into the queue.

Blockingqueue Methods
Blockingqueue has 4 different sets of methods for inserting, deleting, and checking objects in a queue. If the requested method cannot be executed immediately, the result of each set of methods is also different. The following table shows the return results of these methods.

tbody>
  throws Exception special Value blocks times out
Insert Add (o) offer (o) put (o) offer (O, timeout, Timeunit)
Remove Remove (o) poll () take () poll (timeout, timeunit)
examine element () Peek ()

The 4 groups of different behavioral methods are explained as follows:
1. Throw Exception: If an attempt to invoke an operation that cannot be executed immediately, an exception is thrown.
2. Special value: Returns a special value (usually True/false) if an attempt to invoke an operation that cannot be executed immediately.
3. Blocks: If an attempt to invoke an operation that cannot be executed immediately, the method call blocks until it can be executed immediately.
4. Times out: If an attempt to invoke an operation that cannot be executed immediately, the method call blocks until it can be executed immediately, but the wait time does not exceed the given time interval (timeout). Returns a specific value that indicates whether the method was invoked successfully (usually True/false).
Cannot insert null in Blockingqueue. If you attempt to insert a null, Blockingqueue will throw a NullPointerException exception.
All elements within the blcokingqueue can be accessed, not just the head and tail elements. For example, you put an object in the queue waiting to be processed, but your application wants to cancel the task. At this point, you can call the Remove (O) method to delete a specific element in the queue. But this is not a very efficient operation, so try not to use it unless you have to.

Blockingqueue implementations
Blockingqueue is an interface and you need to use its implementation class to use it. The implementation class of the Blockingqueue interface in the Java.util.concurrent package is as follows (Java 6 in the original, the translator is based on Java 8):
Arrayblockingqueue
Delayqueue
Linkedblcokingqueue
Priorityblockingqueue
Synchronousqueue

Java Blockingqueue Example
A blockingqueue example is shown below. The example uses one of the implementation classes of the Blockingqueue interface –arrayblockingqueue.
First, the Blockingqueueexample class starts a producer and a consumer separately in different threads. The producer inserts a string into the shared Blockingqueue, and the consumer extracts the string from the shared blockingqueue.

public class Blockingqueueexample {public

    static void Main (string[] args) throws Exception {

        Blockingqueue queue = new Arrayblockingqueue (1024);

        Producer Producer = new Producer (queue);
        Consumer Consumer = new Consumer (queue);

        New Thread (producer). Start ();
        New Thread (consumer). Start ();

        Thread.Sleep (4000);
    }

The following are the producer classes. Notice how it sleeps for one second each time you put () the call. This allows the consumer to block while waiting for the object to be taken out of the queue.

public class Producer implements runnable{

    protected blockingqueue queue = null;

    Public Producer (Blockingqueue queue) {
        this.queue = queue;
    }

    public void Run () {
        try {
            queue.put ("1");
            Thread.Sleep (1000);
            Queue.put ("2");
            Thread.Sleep (1000);
            Queue.put ("3");
        } catch (Interruptedexception e) {
            e.printstacktrace ();}}}

Here is the consumer class. It simply takes the objects out of the queue and prints them to System.out.

public class Consumer implements runnable{

    protected blockingqueue queue = null;

    Public Consumer (Blockingqueue queue) {
        this.queue = queue;
    }

    public void Run () {
        try {
            System.out.println (Queue.take ());
            System.out.println (Queue.take ());
            System.out.println (Queue.take ());
        } catch (Interruptedexception e) {
            e.printstacktrace ();}}}

Original link

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.