See also Java Queues.
package com.etretatlogiciels.queue; /** * This is a queue element of work. */ public class WorkQueue { int workToDo; public WorkQueue() { } public WorkQueue( int work ) { this.workToDo = work; } public int getWorkToDo() { return workToDo; } public void setWorkToDo( int work ) { workToDo = work; } }
package com.etretatlogiciels.queue; public class WorkQueueElementNotFoundException extends Exception { private String message; public WorkQueueElementNotFoundException( String message ) { this.message = message; } @Override public String getMessage() { return this.message; } }
package com.etretatlogiciels.queue; import java.util.List; import java.util.NoSuchElementException; import java.util.Queue; import java.util.ArrayList; import java.util.concurrent.ConcurrentLinkedQueue; import static org.junit.Assert.fail; import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Before; import org.junit.Test; public class WorkQueueTest { private static final boolean PRINT = true; private static int RESERVE = 10; private static final List< Integer > workList = new ArrayList< Integer >( RESERVE ); static { for( int i = 0; i < RESERVE; i++ ) workList.add( i ); } private Queue< WorkQueue > queue = null; @Before public void setUp() throws Exception { // queue = new LinkedList< WorkQueue >(); // not thread-safe // queue = new LinkedBlockingQueue< WorkQueue >(); // thread-safe, blocks waiting for the queue not to be empty queue = new ConcurrentLinkedQueue< WorkQueue >(); // like LinkedList, but thread safe /* Simulate creating RESERVE number of elements ahead. */ for( int element = 0; element < RESERVE; element++ ) queue.add( new WorkQueue( element ) ); } @Test public void test() { fail( "Not yet implemented" ); } @Test public void testCreateAhead() { assertTrue( queue.size() == 10 ); for( WorkQueue q : queue ) assertTrue( workList.contains( q.getWorkToDo() ) ); } @Test( expected = WorkQueueElementNotFoundException.class ) public void testRunOutOfElements() throws WorkQueueElementNotFoundException { int expected = 0; while( true ) { try { int work = removeElement( expected ); expected = work + 1; } catch( WorkQueueElementNotFoundException e ) { System.out.println( e.getMessage() ); System.out.println( "Crash, bang, boom! Ran out of elements in queue!" ); break; } } } private int removeElement( int expected ) throws WorkQueueElementNotFoundException { try { int work; WorkQueue q = queue.remove(); printOrNot( work = q.getWorkToDo() ); return work; } catch( NoSuchElementException e ) { throw new WorkQueueElementNotFoundException( String.format( "Expecting element %d...", expected ) ); } } private static void printOrNot( Object o ) { if( !PRINT ) return; if( o instanceof String ) System.out.println( o ); else System.out.println( "" + o ); } }