user1074896
user1074896

Reputation: 1025

How to write Producer-Consumer solution using Message passing?

I found the next code:

public static void main(String args[]) {
        Producer producer = new Producer();
        producer.start();
        new Consumer(producer).start();
    }
}
class Producer extends Thread {
    static final int MAXQUEUE = 5;
    private Vector<String> messages = new Vector<String>();

    public void run() {
        try {
            while (true) {
                putMessage();
                sleep(1000);
            }
        } catch (InterruptedException e) {
        }
    }

    private synchronized void putMessage() throws InterruptedException {

        while (messages.size() == MAXQUEUE)
            wait();
        messages.addElement(new java.util.Date().toString());
        notify();
    }

    public synchronized String getMessage() throws InterruptedException {
        notify();
        while (messages.size() == 0)
            wait();
        String message = (String) messages.firstElement();
        messages.removeElement(message);
        return message;
    }
}

class Consumer extends Thread {
    Producer producer;

    Consumer(Producer p) {
        producer = p;
    }

    public void run() {
        try {
            while (true) {
                String message = producer.getMessage();
                System.out.println("Got message: " + message);
                sleep(2000);
            }
        } catch (InterruptedException e) {
        }
    }

So as I understand Message passing - is only not use shared resources and use like in above sample reference from one object to another to communicate. Am i right?

Upvotes: 0

Views: 4320

Answers (2)

Andrejs
Andrejs

Reputation: 27697

If you are following the Publish/Subscribe pattern then you need a message queue of some sort. The Producer puts messages on the queue and Consumer reads messages of the queue.

The point of messaging is that your producers/consumers don't have to reference each other directly but only communicate via a queue.

Upvotes: 1

Andrejs
Andrejs

Reputation: 27697

Why write it yourself? You can use existing Java Message Service (JMS) solutions like ActiveMQ. It can run in-process and pass messages between your objects.

Upvotes: 0

Related Questions