Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to implement Concurrent Queue Linked in Java

This tutorial will describe on how Concurrent Queue linked is implemented in java. Also it covers the basics of the usage of Blocking Queue class.

ConcurrentLinkedQueue class is a boundless thread-safe queue based on linked nodes where the elements of this queue are ordered in FIFO (first-in-first-out). In this queue the element that has been the longest time on the queue is the head element, and the element that has been the shortest time on the queue is the tail element of the queue.

  • Insertion of an element in this queue is happened at tail and the element is retrieved from the head position. ConcurrentLinkedQueue do not allows the 'null' elements.
  • When there are multiple threads accessing a common collection, selection of this queue will be good. All the optional methods of Collection and Iterator interfaces are implemented by this class and its iterator.

Listing1: Syntax of ConcurrentLinkedQueue

public class ConcurrentLinkedQueue<E>

Parameter description

E : It is the element's type that's held by this queue.

Constructor of ConcurrentLinkedQueue :

  • ConcurrentLinkedQueue() : Initially an empty ConcurrentLinkedQueue is made by this constructor.
  • ConcurrentLinkedQueue(Collection<? extends E> c) : This constructor makes a ConcurrentLinkedQueue that contains the elements of a particular collection at the time of creation, these elements are arranged in queue as their traversing order of the collection's iterator.

Example :

Here we are making a simple example which will illustrate you that how can ConcurrentLinkedQueue class be implemented.

import java.util.concurrent.ConcurrentLinkedQueue;
public class ConcurrentLinkedQueueDemo {
  public static void main(String args[]){
    ConcurrentLinkedQueue clq = new ConcurrentLinkedQueue();
    clq.add("A");
    clq.add("B");
    clq.add("C");
    clq.add("D");
    System.out.println("Element of queue = "+clq);
    //peek() method
    Object obj = clq.peek();
    System.out.println("Head element of queue = "+obj);
    //isEmpty() method 
    boolean bol =clq.isEmpty();
    System.out.println("Queue is empty : "+bol);
    //contains() method 
    boolean bol1 =clq.contains("D");
    System.out.println("Is element 'D' existed into queue ? "+bol1);
    //poll() method
    Object obj1 = clq.poll();
    System.out.println("Removed head element = "+obj1);
    //size() method
    int i = clq.size();
    System.out.println("Size of queue = "+i);
  }
}

Output :

Element of queue = [A, B, C, D]
Head element of queue = A
Queue is empty : false
Is element 'D' existed into queue ? true
Removed head element = A
Size of queue = 3

How to use BlockingQueue class?

A new class in Java 5 can be used to communicate data to lot many Consumer classes from a Producer class.

The java.util.concurrent.BlockingQueue is designed to work in a multi-threaded world.

A Producer opens a file and puts the data into BlockingQueue.

Listing2: Entering the data into Blocking Queue

import java.io.*;
import java.util.concurrent.*;
 
public class PrepareProduction implements Runnable{
  private final BlockingQueue<String> queue;
 
  PrepareProduction(BlockingQueue<String> q) { queue = q; }
 
  public void run() {
    String thisLine;
    System.out.println("Start PrepareProduction");
    try {
       FileInputStream fin =  new FileInputStream("d:/input_data.dat");
       BufferedReader input = new BufferedReader
           (new InputStreamReader(fin));
       while ((thisLine = input.readLine()) != null) {
           queue.put(thisLine);
       }
       fin.close();
       input.close();
       // special marker for the consumer threads
       // to mark the EOF
       queue.put("*");
       queue.put("*");
       queue.put("*");
       queue.put("*");
       queue.put("*");
       queue.put("*");
       queue.put("*");
       queue.put("*");
       queue.put("*");
    }
    catch (Exception e) {
       e.printStackTrace();
    }
  }
}

A Consumer extract a value from the Queue and execute an operation and in case there is no data in the Queue, the BlockingQueue will wait. The end-of-data is marked by the presence of a special marker (the "*" in this example).

Listing3: Extracting value from Queue

import java.util.concurrent.BlockingQueue;
 
public class DoProduction implements Runnable {
  private final BlockingQueue<String> queue;
 
  DoProduction(BlockingQueue<String> q) { queue = q; }
 
  public void run() {
    try {
       System.out.println
          ("Start " + Thread.currentThread().getName());
       
       String value = queue.take();
       while (!value.equals("*")) {
         //System.out.println
         //  (Thread.currentThread().getName()+": " + value );
         /*
              do something with value
         */     
         value = queue.take();
       }
    }
    catch (Exception e) {
       System.out.println
           (Thread.currentThread().getName() + " " + e.getMessage());
    }
  }
}

A look at the test class

Listing4: Code with a test class

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
 
public class Test {
  public static void main(String[] args) throws Exception {
        
    BlockingQueue<String> q =
        new LinkedBlockingQueue<String>();

    Thread p1 = new Thread(new PrepareProduction(q));
    Thread c1 = new Thread(new DoProduction(q));
    Thread c2 = new Thread(new DoProduction(q));
    Thread c3 = new Thread(new DoProduction(q));
    Thread c4 = new Thread(new DoProduction(q));
    Thread c5 = new Thread(new DoProduction(q));
    Thread c6 = new Thread(new DoProduction(q));
    Thread c7 = new Thread(new DoProduction(q));
    Thread c8 = new Thread(new DoProduction(q));
    Thread c9 = new Thread(new DoProduction(q));
       
    p1.start();
    c1.start();
    c2.start();
    c3.start();
    c4.start();
    c5.start();
    c6.start();
    c7.start();
    c8.start();
    c9.start();
 
    p1.join();
    c1.join();
    c2.join();
    c3.join();
    c4.join();
    c5.join();
    c6.join();
    c7.join();
    c8.join();
    c9.join();
       
    System.out.println("Done.");
  }
}

Conclusion

We covered today on the implementation of Concurrent Queue Linked in Java with the basics on how to use Blocking Queue class.



Software Developer from India. I hold Master in Computer Applications Degree and is well versed with programming languages such as Java, .Net, C and C++ and possess good working knowledge on Mobile Platforms as well.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login