Thursday, July 17, 2014

Java Concurrency : Usage of BlockingQueue class

BlockingQueue allows you to put objects into it and take out objects one at a time. So you don't need to worry about concurrent threads' synchronization for queue access. If there are no elements, the accessing thread simply blocks and resumes when elements are added for the thread to access.

Example Code:

import java.util.concurrent.*;
import java.io.*;
import java.util.*;

class Sender implements Runnable {

    private Random rand = new Random(47);
    private BlockingQueue bq = new LinkedBlockingQueue<>();

    public BlockingQueue getBlockingQueue() {
        return bq;
    }

    public void run() {
        try {
            while (true) {
                for (char c = 'A'; c <= 'z'; c++) {
                    bq.add(c);
                    TimeUnit.MILLISECONDS.sleep(rand.nextInt(500));
                }
            }
        } catch (InterruptedException e) {
            System.out.println(e + " Sender sleep Interrupted");
        }
    }
}

class Receiver implements Runnable {

    private PipedReader in;
    private BlockingQueue bq;

    public Receiver(Sender sender) throws IOException {
        bq = sender.getBlockingQueue();
    }

    public void run() {
        try {
            while (true) {
                System.out.print("Read: " + (Character) (bq.take()) + " ");
            }
        } catch (InterruptedException ex) {
            System.out.println("Reader Interrupted!");
        }
    }
}

public class BlockingQueueTest {

    public static void main(String[] args) throws Exception {
        Sender sender = new Sender();
        Receiver receiver = new Receiver(sender);
        ExecutorService exec = Executors.newCachedThreadPool();
        exec.execute(sender);
        exec.execute(receiver);
        TimeUnit.SECONDS.sleep(5);
        exec.shutdownNow();
    }
}

Output:

Read: A Read: B Read: C Read: D Read: E Read: F Read: G Read: H Read: I Read: J Read: K Read: L Read: M Read: N Read: O Read: P Read: Q Read: R Read: S Read: T Read: U Reader Interrupted!
java.lang.InterruptedException: sleep interrupted Sender sleep Interrupted

No comments:

Post a Comment