FileDocCategorySizeDatePackage
Baton.javaAPI DocphoneME MR2 API (J2ME)3341Wed May 02 18:00:00 BST 2007com.sun.midp.util

Baton

public class Baton extends Object
A concurrency control mechanism, a virtual baton that can be passed between two threads to control the order of execution. The main operation is pass(), which unblocks the other thread and then blocks this thread until the other thread passes the baton back. A typical use case is as follows: 1. Thread A creates the baton and passes it to thread B. 2. Thread A calls start() to wait for thread B to get to a known state. 3. Thread B calls pass() to pass the baton to A, and then B blocks. 4. Thread A unblocks does stuff, then calls pass() to pass the baton to B, and then A blocks. 4. Threads A and B alternately call pass() so that they execute in lock step. 5. One of the threads calls finish() to let the other thread continue indefinitely, ending the use of the baton. The baton can be passed between threads up to Integer.MAX_VALUE - 1 times before it ceases to function.

Fields Summary
int
count
Constructors Summary
public Baton()
Creates a new baton.

        count = 0;
    
Methods Summary
private voidawait(int seq)

        while (count < seq) {
            try {
                wait();
            } catch (InterruptedException ignore) { }
        }
    
public synchronized voidfinish()
Tells the other thread continue, and then returns. After a call to finish(), the baton becomes inoperative, and calls to pass() simply return.

        count = Integer.MAX_VALUE;
        notifyAll();
    
public synchronized voidpass()
Passes the baton to the other thread, unblocking it, and blocks until the baton is passed back. After finish() is called, simply returns without doing anything.

        if (count < Integer.MAX_VALUE) {
            count++;
            notifyAll();
            await(count + 1);
        }
    
public synchronized voidstart()
Starts the protocol by waiting for the first pass from the other thread.

throws
IllegalStateException if called after the protocol has been started

        if (count > 1) {
            throw new IllegalStateException();
        }
        await(1);