Site hosted by Angelfire.com: Build your free website today!
 

Synchronization (Consumer/Producer)

The MessageBuffer class, a shareable Java object.

The general solution is to give methods mutually exclusive access to shared objects. Multual exclusion can be modeled as atomic actions.

import java.util.Random;

/**
 * @author jack
 */
public class MessageBuffer {
    private int[] buffer;
    private int size;
    private int head;
    private int tail;
    private int count;
    private int writers = 0;
    private Random random = new Random();

    MessageBuffer(int size) {
        this.size = size;
        buffer = new int[size];
        head = tail = count = 0;
    }
    public void randomYield() {
        if (random.nextBoolean())
            Thread.currentThread().yield();
    }
    public void put(int i) {
        while (count >= size)  //buffer is full
            waitForNotification();
        count++;
        notifyOthers();
        randomYield();  //artificial processing delay
        buffer[head] = i;
        head++;
        if (head >= size)
            head = 0;
    }
    public int get() {
        while (count == 0 && writers > 0)
            waitForNotification();  //only if there is writer
        if (count == 0 && writers <= 0)
            return -1;
        int i = buffer[tail];
        count--;
        tail++;
        if (tail >= size)
            tail = 0;
        notifyOthers();
        randomYield();  //artificial processing delay
        return i;
    }
    public void registerWriter() {
        writers++;
    }
    public void unregisterWriter() {
        writers--;
        notifyOthers();
    }
    private void waitForNotification() {
        synchronized (this) {
            try {
                wait();  //required to be in a synchronized block
            } catch (InterruptedException e) {
            }
        }
    }
    private void notifyOthers() {
        synchronized(this) {
            notifyAll();  
        }
    }
}