The operations queue is a simple utility class that runs in a separate
thread executing operations serially. The OperationsQueue
class
takes objects implementing the Operation
interface, making
it independent of the kind of operations executed. Operation
implementers
are expected to handle their exceptions locally since OperationsQueue
will
discard any exceptions thrown.
To create the OperationsQueue
class:
Create the OperationsQueue
class
file.
Import the required classes.
import java.util.*;
Define the interface.
// Simple Operations Queue // It runs in an independent thread and executes Operations serially class OperationsQueue implements Runnable { private volatile boolean running = true; private final Vector operations = new Vector(); OperationsQueue() { // Notice that all operations will be done in another // thread to avoid deadlocks with GUI thread new Thread(this).start(); } void enqueueOperation(Operation nextOperation) { operations.addElement(nextOperation); synchronized (this) { notify(); } } // stop the thread void abort() { running = false; synchronized (this) { notify(); } }
Use the run()
method
to execute the operations on the queue.
public void run() { while (running) { while (operations.size() > 0) { try { // execute the first operation on the queue ((Operation) operations.firstElement()).execute(); } catch (Exception e) { // Nothing to do. It is expected that each operations handle // their own locally exception but this block is to ensure // that the queue continues to operate } operations.removeElementAt(0); } synchronized (this) { try { wait(); } catch (InterruptedException e) { // it doesn't matter } } } } }
To create the Operation
interface: