3
votes

I have to develop an application that is similar to the producer-consumer problem in java.

However I do not know a lot about java, and I have a couple of questions.

Both the producer and consumer that are different threads and they both need to access the same buffer. If they are both different classes (that either extends thread class or implement the runnable interface) how do I code them to use the exact same buffer (this supposed buffer is an array of a certain object)?

I also would like to read some suggestions about how the overall architecture and how should I implement them. I need to code them so that two threads don't consume the same buffer position at the same time, that two producer threads don't insert at the exact same value at the same time, producer can't insert a new item in an already filled buffer, and that no consumer should consume when the buffer is empty.

In this example there must be several consumers and several producers working at the same time.

I looked for some examples in java but they are all different of what I need.

2

2 Answers

4
votes

You can pass in a same instance of array or list to both consumer and producer by passing it through their constructor.

Array a = new Array();
Consumer c = new Consumer(a);
Producer p = new Producer(a);

For the second question, you would like to learn about (google it!) for synchronization in Java. You can again pass in the same private Object lock1 = new Object(); to both consumer and producer and they can use it as a shared lock.

http://download.oracle.com/javase/tutorial/essential/concurrency/locksync.html

Whenever a consumer or a producer access the shared array, they would need to acquire lock first. Other conditional requirements such as 'not inserting elements when the array is full' or 'not consuming elements when the array is empty' can be implemented inside the synchronized block.

public void add(Object someObject){
    synchronized (lock1) {
        if(a.size()>limit) {
            System.out.println("Array is full");
        } else {
           a.add(someObject)
        }
    }
}
3
votes

Indeed in the java core library(version 1.5 or above),there are already data structures to meet your needs.Under the java.util.concurrent package,BlockedQueue,LinkedBlockedQueue..etc are all for concurrent using.