Monday, 23 June 2014

Thread safe implementation of Queue (ConcurrentLinkedQueue) Example


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.


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) {
            orderQueue.remove("order number 1");
        System.out.println("priority order "+orderQueue.poll());



Order details after insertion

order number 1

order number 2 premium

order number 3

order number 4

priority order order number 2 premium