FileDocCategorySizeDatePackage
BatchingPrinter.javaAPI DocExample2250Thu Nov 08 00:22:48 GMT 2001com.ora.rmibook.chapter12.printer.printers

BatchingPrinter.java

package com.ora.rmibook.chapter12.printer.printers;


import com.ora.rmibook.chapter12.printer.*;
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
import java.util.*;


public class BatchingPrinter extends UnicastRemoteObject implements Printer {
    private LinkedList _printQueue;
    private Printer _realPrinter;
    private Object _printerLock = new Object();
    private boolean _currentlyPrinting;

    public BatchingPrinter(Printer realPrinter) throws RemoteException {
        _printQueue = new LinkedList();
        _realPrinter = realPrinter;
        (new BackgroundThread()).start();
    }

    public synchronized boolean printerAvailable() throws RemoteException {
        if (_currentlyPrinting) {
            return false;
        }
        return _realPrinter.printerAvailable();
    }

    public synchronized boolean printDocument(DocumentDescription document)
        throws RemoteException, PrinterException {
        _printQueue.add(document);
        notifyAll();
        return true;
    }

    private synchronized void setCurrentlyPrinting(boolean currentlyPrinting) {
        _currentlyPrinting = currentlyPrinting;
    }

    private void printNextDocument() {
        try {
            DocumentDescription documentToPrint = getNextDocumentFromQueue();

            setCurrentlyPrinting(true);
            _realPrinter.printDocument(documentToPrint);
            setCurrentlyPrinting(false);
        } catch (Exception ignored) {

            /*
             This is a real issue-- what do we do with PrinterExceptions
             when we've batched things up like this. 
             */
        }
    }

    private synchronized DocumentDescription getNextDocumentFromQueue() {
        while (0 == _printQueue.size()) {
            try {
                wait();
            } catch (Exception ignored) {
            }
        }
        DocumentDescription nextDocument = (DocumentDescription) _printQueue.remove(0);

        return nextDocument;
    }

    private class BackgroundThread extends Thread {
        public void run() {
            while (true) {
                printNextDocument();
            }
        }
    }
}