OO Programming in Java

Class 8 Material


Threaded Resource Allocation

Occasionally there may be a single resource (a text to speech device for example) which several threads require access to, but only one thread at a time may use it. This would normally be a simple case of placing all the methods in one class and then synchronizing all of them.

There are times when this is not possible, perhaps a complex model where the routines are spread around many classes. Here is one way to accomplish resource allocation ....



class Talker {

    private String filepath        =    "c:\\bernard\\speakit.txt";
    private String speakCmd[]      = {  "c:\\bernard\\speakfile.exe"  };

    private boolean busy_;

    private static Talker instance_ = null;

    private Talker() {};

    public static Talker instance() {
        if (instance_ == null)
            instance_ = new Talker();
        return instance_;
    }

    public boolean busy () {
        return busy_;
    }

    public synchronized void busy(boolean busyIndicator) {
        busy_ = busyIndicator;
    }

    public void notifyNotBusy() {
        notifyAll();
    }

    public synchronized void awaitNotBusy() {
        while (this.busy()) {
            try {
                wait();
            }
            catch (InterruptedException ex) {}
        }
    }

    public synchronized void acquire() {
        this.awaitNotBusy();
        this.busy(true);
    }

    public synchronized void release() {
        this.busy(false);
        this.notifyNotBusy();
    }


To use it simply say:

Talker.acquire();
// do some work
Talker.release();

Talker.acquire() places your thread in a wait state.

Once the resource is available (someone else releases it) you are able to do your work.

Talker.release() releases the resource for others when you are done.