For DelayQueue understanding

The company today to see the code found inside using a DelayQueue, after learning record:

The concept: DelayQueue is delayed to obtain a support element of unbounded blocking queue. All the elements are there "may be extended" element, the element column header is the first "mature" elements, if there is no queue element expires, is not getting elements from the column head, even if there is an element does not work. That if only to be able to take elements from the queue in the delay period.

I understand: the need for delay queue delay processing scenarios: for example, delay the session is closed, if a need to close the session after one minute, you can use the delay queue, another example: timeout canceled orders

Examples of scenarios: Orders timeout

public  class DelayQueue <E the extends Delayed> the extends AbstractQueue <E> 
We see the need to inherit Delayed generic queue interface. Create an entity class that implements this interface

Create entity classes: OrderInfo

. 1  Package wyp.delayqueue;
 2  
. 3  Import lombok.Data;
 . 4  
. 5  Import the java.io.Serializable;
 . 6  Import java.text.ParseException;
 . 7  Import the java.text.SimpleDateFormat;
 . 8  Import java.util.concurrent.Delayed;
 . 9  Import java.util.concurrent.TimeUnit;
 10  
. 11  / ** 
12 is  * @author : Wang Miles
 13 is  * @date: 2019/7/2 3:39 the PM
 14  * a DelayQueue <T>
 15  * generic queue delay must implement delayed Interface
 16   * /
. 17  @Data
 18 is  public  class OrderInfo the implements the Serializable, the DelayedPause {
 . 19      Private  static  Final  Long serialVersionUID = 1L ;
 20 is      Private String orderNo; // order number 
21 is      Private String Status; // order status 
22 is      Private String exptime; // order expiration 
23      Private String createTime; // order creation time 
24-  
25      / ** 
26       * for delaying the internal queue Compare Sort By: current order expiration time compared with the time expired queue object
 27      * Sorting method:
 28       * I understand: sequence element is removed from the expired queue delay, whereby sorting is a method of controlling
 29       * / 
30      @Override
 31 is      public  int the compareTo (the DelayedPause O) {
 32          the SimpleDateFormat Formatter = new new the SimpleDateFormat ( "YYYY HH-dd -MM: mm: SS " );
 33 is          Long nowThreadtime = 0 ;
 34 is          Long queueThreadtime = 0 ;
 35          the try {
 36              nowThreadtime = formatter.parse ( the this .expTime) .getTime ();
 37 [              queueThreadtime = formatter.parse ( ((OrderInfo) o) .expTime)
 .getTime ();38 is          } the catch (a ParseException E) {
 39              e.printStackTrace ();
 40          }
 41 is          return Long.valueOf (nowThreadtime) .compareTo (Long.valueOf (queueThreadtime));
 42 is      }
 43 is  
44 is  
45      / ** 
46 is       * Time Unit: second
 47       * = expiration time delay closing time - the current time
 48       * DOC document with your official, I understood as follows:
 49       * when the return value is negative when this method indicates time delay method can be removed from the queue
 50       * then At this time, the consumer can accept a series of process
 51 is       * / 
52 is      @Override
 53 is      public  Long getDelay (TimeUnit Unit) {
 54 is         SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
55         long time = 0;
56         try {
57             time = formatter.parse(this.expTime).getTime();
58         } catch (ParseException e) {
59             e.printStackTrace();
60         }
61         return time - System.currentTimeMillis();
62     }
63 
64 
65 }

Creating delay queue listener class

Package wyp.delayqueue; 

Import java.util.Objects;
 Import java.util.concurrent.DelayQueue; 

/ ** 
 * @author : Miles Wang 
 * @date: 2019/7/2 3:42 the PM 
 * 
 * time delay queue DelayQueue timeout order to achieve close 
 * daemon thread continued to perform inspection work 
 * double check mode to achieve singleton pattern 
 * later I changed to single-threaded thread pool, all is not important whether simple interest mode 
 * / 
public  class OrderOverTimeClose { 

    Private  volatile  static OrderOverTimeClose = oderOverTimeClose null ; 

    Private OrderOverTimeClose () { 

    } 

    / ** 
     * daemon thread 
     * / 
    PrivateMainThread the Thread; 

    / ** 
     * Create an empty queue latency 
     * / 
    Private   a DelayQueue <OrderInfo> Queue = new new a DelayQueue <OrderInfo> (); 

    / ** 
     * Singleton, double checks the lock mode, only in a concurrent environment object is initialized a 
     * / 
    public  static OrderOverTimeClose the getInstance () {
         IF (oderOverTimeClose == null ) {
             the synchronized (OrderOverTimeClose. class ) { 
                oderOverTimeClose =   new new OrderOverTimeClose (); 
            } 
        } 
        return oderOverTimeClose; 
    } 

    / ** 
     * start method
     * / 
    Public  void the init () { 
        mainThread =   new new the Thread (() -> Execute ()); 
        mainThread.setDaemon ( to true ); 
        mainThread.setName ( "daemon thread ->" ); 
        mainThread.start (); 
    } 

    Private  void Execute () {
         the while ( to true ) {
             the try {
                 IF (queue.size ()> 0 ) {
                     // Get order from the queue timeout 
                    OrderInfo the orderInfo = queue.take ();
                     //Check order status, has been successful, the order will be successfully removed from the queue. 
                    IF (Objects.equals (orderInfo.getStatus (), "success" )) { 
                        System.out.println ( "thread:". + Thread.currentThread () getName () + ", order number:" 
                                + orderInfo.getOrderNo ( ) + ", order status:" 
                                + orderInfo.getStatus () + "order creation time:" 
                                + orderInfo.getCreateTime ()
                                 + ", order timeout:" + orderInfo.getExpTime () + " , the current time:" + OrderPay.getTime (System.currentTimeMillis ())); 
                        Thread.sleep ( 2000 );"Thread:" + Thread.currentThread () getName ( ) + ", order number:." 
                                + OrderInfo.getOrderNo () + ", change orders status: Timeout Off" 
                                + "order creation time:" 
                                + orderInfo.getCreateTime ()
                                 + "Order timeout:" + orderInfo.getExpTime () + " , the current time:" + OrderPay.getTime (System.currentTimeMillis ())); 
                        the Thread.sleep ( 2000 ); 
                    } 
                } 
            } the catch (InterruptedException E ) { 
                e.printStackTrace ();
            } 
        } 
    } 

    / ** 
     * line is inserted into the timeout queue 
     * /
    public  void orderPutQueue (OrderInfo orderInfo, createTime String, 
                              String OverTime) { 
        System.out.println ( "Order Number:" + orderInfo.getOrderNo () + " , order creation time:" 
                + createTime + ", the order expiration time:" + OverTime);
       //   queue.add (the orderInfo); 
          queue.put (the orderInfo); 
    } 
}

Test is to insert elements into the queue delay

package wyp.delayqueue;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @author : miles wang
 * @date : 2019/7/2  3:46 PM
 */
public class OrderPay {
    static String[] str = new String[]{"成功","支付中","订单初始化"};

    public static String getTime(long time){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(time);
        String currentTime = formatter.format(date);
        return currentTime;
    }

    public static void main(String[] args) throws InterruptedException {
        OrderOverTimeClose.getInstance().init();
        for (int i = 0; i < 20; i++) {
            // 创建初始订单
            long createTime = System.currentTimeMillis();
            String currentTime = getTime(createTime);
            String overTime = getTime(createTime + 10000);// 十秒后超时
            String orderNo = String.valueOf(new Random().nextLong());
            OrderInfo order = new OrderInfo();
            order.setOrderNo(orderNo);
            order.setExpTime(overTime);
            int random_index = (int) (Math.random()*str.length);
            order.setStatus(str[random_index]);// 随机分配
            order.setCreateTime(currentTime);
            OrderOverTimeClose.getInstance().orderPutQueue(order, currentTime, overTime);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

These are just individual learning to understand and test records, not necessarily right.

Guess you like

Origin www.cnblogs.com/wangpipi/p/11122416.html