Searching...
Monday, 23 June 2014

Thread safe implementation of Queue (ConcurrentLinkedQueue) Example

08:57

An unbounded thread-safe queue based on linked nodes. This queue orders elements FIFO (first-in-first-out). The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue.

Example

package com.vinod.test;

import java.util.concurrent.ConcurrentLinkedQueue;

public class ConcurrentLinkedQueueExample {

    public static void main(String[] args) {
        ConcurrentLinkedQueue<String> orderQueue = new ConcurrentLinkedQueue<String>();
        orderQueue.add("order number 1");
        orderQueue.add("order number 2 premium");
        orderQueue.add("order number 3");
        orderQueue.add("order number 4");
        System.out.println("Order details after insertion");
        for (String orderDetail : orderQueue) {
            System.out.println(orderDetail);
            orderQueue.remove("order number 1");
        }
        System.out.println("priority order "+orderQueue.poll());
    }

}
   

Output

Order details after insertion

order number 1

order number 2 premium

order number 3

order number 4

priority order order number 2 premium

0 comments: