Java Multithreaded series 10--blockingqueue class

Source: Internet
Author: User

Reference: http://ifeve.com/java-synchronousqueue/
Http://www.cnblogs.com/jackyuj/archive/2010/11/24/1886553.html
http://ifeve.com/java-blocking-queue/

Blockingqueue a few API realizations

Method Description
Add (e E) Add an element that exceeds the queue size limit after throwing an exception
Offer (e e) Add an element that exceeds the queue size limit after throwing an exception, compared to add official is recommended to use the Offer method
Put (e e) add element, if space is insufficient, enter waiting state until there is space
Offer (e E, long timeout, timeunit unit) Add elements and wait for a certain amount of time to succeed or give up if there is not enough space
Take () Gets the header element of the queue and enters the waiting state if no element is desirable
Poll (long timeout, timeunit unit) Gets the header element of the queue and waits for a certain amount of time until it succeeds or discards if no desirable elements are available
Remove (Object o) Delete Element

Blockingqueue derives a few common classes Arrayblockingqueue/linkedblockingdeque/delayqueue/priorityblockingqueue/synchronousqueue , the class diagram looks like this:

Some of their features:

    • Arrayblockingqueue: The element is saved as an array, the capacity of the queue must be specified when initializing capacity, and when the element is added, the block is reached
    • Linkedblockingdeque: Save elements in a doubly-linked list, the capacity of the queue can be specified when initialized, capacity defaults to Integer.max_value if not specified, and when the element is added, it is blocked when the upper limit is reached
    • Delayqueue: Save the meta-table with Priorityqueue, can only get the element that has expired time, otherwise get null, no capacity limit, theoretically can add the element infinitely
    • Priorityblockingqueue: Save elements in an array, the entire team as a balanced binary tree, add elements after the success of the elements in the queue reordering, no capacity limit, theoretically unlimited elements can be added
    • Synchronousqueue: No cache queue, a producer thread inserts a put must wait for the consumer to take the removal action, and vice versa

Arrayblockingqueue use case can refer to the Java Multithreading Series three-the method of implementing thread synchronization, this article tests the use of Delayqueue, the code is as follows:

Importjava.util.Arrays;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;ImportJava.util.concurrent.ArrayBlockingQueue;ImportJava.util.concurrent.BlockingQueue;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.DelayQueue;Importjava.util.concurrent.Delayed;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future;ImportJava.util.concurrent.TimeUnit;/*** @Description use Delayqueue to clear timeout requests <br/> * 1. The main thread removed from the work queue after the task processing is complete, remove the task from the timeout queue <br/> * 2. Timeout check after thread finds timeout request, remove task from work queue*/ Public classDelayqueuetest { Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {intSize = 36; Delayqueue<MyRequest> queue =NewDelayqueue<> ();//queue used to record whether time-outsBlockingqueue<myrequest> WorkQueue =Newarrayblockingqueue<> (size);//The requested team tableMap<integer, myrequest> cache =NewHashmap<> ();//table of requests and IDs         for(inti = 0; i < size; i++) {//InitializeMyrequest Impl =NewMyrequest (i, System.nanotime (), 120);            Queue.put (IMPL);            Workqueue.put (IMPL);        Cache.put (i, impl); }        /*** Set up a timeout check task*/Executors.newsinglethreadexecutor (). Submit (NewRunnable () {@Override Public voidrun () { while(Queue.size () > 0) {                    Try{myrequest Impl=Queue.take (); Workqueue.remove (impl);//remove the request from the queue if the request times outSystem.out.println (String.Format ("%s is timeout", Impl)); } Catch(interruptedexception e) {e.printstacktrace ();        }                }            }        }); /*** Build 2 thread consumption requests*/Executorservice Executorservice= Executors.newfixedthreadpool (2);  while(Workqueue.size () > 0) {List<MyRequest> tasks = Arrays.aslist (Newmyrequest[] {workqueue.take (), Workqueue.take ()}); List<Future<Integer>> futures =Executorservice.invokeall (tasks);  for(future<integer>future:futures) {Queue.remove (Cache.get (Future.get ()));//If the request succeeds, you do not need to check for timeouts}} executorservice.awaittermination (Integer.max_value, timeunit.days);    Executorservice.shutdown (); }}classMyrequestImplementsDelayed, callable<integer> {    Private intthreadId; Private LongStartTime; Private LongExpiredTime;  PublicMyrequest (intThreadId,LongStartTime,LongTimeout) {         This. ThreadId =threadId;  This. StartTime =StartTime;  This. ExpiredTime = TimeUnit.SECONDS.toNanos (timeout) +System.nanotime (); } @Override PublicInteger Call () {Try{thread.sleep (TimeUnit.SECONDS.toMillis (10)); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (String.Format ("%s is OK", This)); returnthreadId; } @Override Public intcompareTo (Delayed arg0) {intRtn; if(arg0 = =NULL|| ! (arg0instanceofmyrequest)) {RTN= 1; } Else{myrequest Impl=(myrequest) arg0; RTN= startTime > Impl.getstarttime ()? 1: (StartTime = = Impl.getstarttime ()? 0:-1); }        returnRtn; } @Override Public Longgetdelay (timeunit unit) {returnExpiredTime-System.nanotime (); }     Public LongGetStartTime () {returnStartTime; } @Override PublicString toString () {returnString.Format ("Myrequest [threadid=%s, starttime=%s, expiredtime=%s]", ThreadId, StartTime, ExpiredTime); }}

Java Multithreaded series 10--blockingqueue class

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.