Monitors

Aims

What is a monitor?

Monitor behavior

Signal and exit semantics

One-slot buffer

Code for buffer, producer,
consumer, and the top level file that puts everything together (note that this code assumes different semantics than is provided in Java, and thus is not a working Java program)

N-slot buffer

Code for buffer, producer,
consumer, and the top level file that puts everything together (similarly to previous example, this code makes assumptions that are not true for the environment provided by Java)

Semaphores Vs. Monitors

Signaling Disciplines

Signal and continue

Interrupting threads

Exceptions discipline

    public void put(E e) throws InterruptedException {
        lock.lock();

        while (elem == S) toBeEmpty.await();

        buf[front] = e;
        front = (front+1)%S;
        elem++;

        toBeFull.signal();
        lock.unlock();
    }
    public void put(E e) throws InterruptedException {
        lock.lock();
        try {
            while (elem == S) toBeEmpty.await();

            buf[front] = e;
            front = (front+1)%S;
            elem++;

            toBeFull.signal();
        } finally {
            lock.unlock();
        }
    }

Fairness of monitors

Monitors (< Java 5)

    synchronized public void put(E e) throws InterruptedException {
        while (elem == S) wait();

        buf[front] = e;
        front = (front+1)%S ;
        elem++;

        notifyAll();
    }

Barrier synchronization

Summary



Concurrent Programming 2016 - Chalmers University of Technology & Gothenburg University