backport-util-concurrent-3.1-src/ 0000755 0017507 0003772 00000000000 10643402427 015710 5 ustar dawidk dcl backport-util-concurrent-3.1-src/test/ 0000755 0017507 0003772 00000000000 10643402426 016666 5 ustar dawidk dcl backport-util-concurrent-3.1-src/test/tck/ 0000755 0017507 0003772 00000000000 10643402426 017447 5 ustar dawidk dcl backport-util-concurrent-3.1-src/test/tck/backport.util.concurrent.1.4.library 0000644 0017507 0003772 00000000702 10153210664 026274 0 ustar dawidk dcl
backport.util.concurrent.1.4[../../backport-util-concurrent.jar][../../backport-util-concurrent-src.jar][../../backport-util-concurrent-doc.jar]1101857966720
backport-util-concurrent-3.1-src/test/tck/tck.jpx 0000644 0017507 0003772 00000007720 10153210664 020756 0 ustar dawidk dcl
backport-util-concurrent-3.1-src/test/tck/src/ 0000755 0017507 0003772 00000000000 10643402426 020236 5 ustar dawidk dcl backport-util-concurrent-3.1-src/test/tck/src/AtomicMarkableReferenceTest.java 0000644 0017507 0003772 00000011707 10153210664 026436 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
public class AtomicMarkableReferenceTest extends JSR166TestCase{
public static void main (String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(AtomicMarkableReferenceTest.class);
}
/**
* constructor initializes to given reference and mark
*/
public void testConstructor(){
AtomicMarkableReference ai = new AtomicMarkableReference(one, false);
assertEquals(one,ai.getReference());
assertFalse(ai.isMarked());
AtomicMarkableReference a2 = new AtomicMarkableReference(null, true);
assertNull(a2.getReference());
assertTrue(a2.isMarked());
}
/**
* get returns the last values of reference and mark set
*/
public void testGetSet(){
boolean[] mark = new boolean[1];
AtomicMarkableReference ai = new AtomicMarkableReference(one, false);
assertEquals(one,ai.getReference());
assertFalse(ai.isMarked());
assertEquals(one, ai.get(mark));
assertFalse(mark[0]);
ai.set(two, false);
assertEquals(two,ai.getReference());
assertFalse(ai.isMarked());
assertEquals(two, ai.get(mark));
assertFalse(mark[0]);
ai.set(one, true);
assertEquals(one,ai.getReference());
assertTrue(ai.isMarked());
assertEquals(one, ai.get(mark));
assertTrue(mark[0]);
}
/**
* attemptMark succeeds in single thread
*/
public void testAttemptMark(){
boolean[] mark = new boolean[1];
AtomicMarkableReference ai = new AtomicMarkableReference(one, false);
assertFalse(ai.isMarked());
assertTrue(ai.attemptMark(one, true));
assertTrue(ai.isMarked());
assertEquals(one, ai.get(mark));
assertTrue(mark[0]);
}
/**
* compareAndSet succeeds in changing values if equal to expected reference
* and mark else fails
*/
public void testCompareAndSet(){
boolean[] mark = new boolean[1];
AtomicMarkableReference ai = new AtomicMarkableReference(one, false);
assertEquals(one, ai.get(mark));
assertFalse(ai.isMarked());
assertFalse(mark[0]);
assertTrue(ai.compareAndSet(one, two, false, false));
assertEquals(two, ai.get(mark));
assertFalse(mark[0]);
assertTrue(ai.compareAndSet(two, m3, false, true));
assertEquals(m3, ai.get(mark));
assertTrue(mark[0]);
assertFalse(ai.compareAndSet(two, m3, true, true));
assertEquals(m3, ai.get(mark));
assertTrue(mark[0]);
}
/**
* compareAndSet in one thread enables another waiting for reference value
* to succeed
*/
public void testCompareAndSetInMultipleThreads() {
final AtomicMarkableReference ai = new AtomicMarkableReference(one, false);
Thread t = new Thread(new Runnable() {
public void run() {
while(!ai.compareAndSet(two, three, false, false)) Thread.yield();
}});
try {
t.start();
assertTrue(ai.compareAndSet(one, two, false, false));
t.join(LONG_DELAY_MS);
assertFalse(t.isAlive());
assertEquals(ai.getReference(), three);
assertFalse(ai.isMarked());
}
catch(Exception e) {
unexpectedException();
}
}
/**
* compareAndSet in one thread enables another waiting for mark value
* to succeed
*/
public void testCompareAndSetInMultipleThreads2() {
final AtomicMarkableReference ai = new AtomicMarkableReference(one, false);
Thread t = new Thread(new Runnable() {
public void run() {
while(!ai.compareAndSet(one, one, true, false)) Thread.yield();
}});
try {
t.start();
assertTrue(ai.compareAndSet(one, one, false, true));
t.join(LONG_DELAY_MS);
assertFalse(t.isAlive());
assertEquals(ai.getReference(), one);
assertFalse(ai.isMarked());
}
catch(Exception e) {
unexpectedException();
}
}
/**
* repeated weakCompareAndSet succeeds in changing values when equal
* to expected
*/
public void testWeakCompareAndSet(){
boolean[] mark = new boolean[1];
AtomicMarkableReference ai = new AtomicMarkableReference(one, false);
assertEquals(one, ai.get(mark));
assertFalse(ai.isMarked());
assertFalse(mark[0]);
while(!ai.weakCompareAndSet(one, two, false, false));
assertEquals(two, ai.get(mark));
assertFalse(mark[0]);
while(!ai.weakCompareAndSet(two, m3, false, true));
assertEquals(m3, ai.get(mark));
assertTrue(mark[0]);
}
}
backport-util-concurrent-3.1-src/test/tck/src/LinkedBlockingQueueTest.java 0000644 0017507 0003772 00000076306 10365510635 025644 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.io.*;
import java.util.NoSuchElementException;
import java.util.Iterator;
import java.util.ConcurrentModificationException;
import java.util.ArrayList;
public class LinkedBlockingQueueTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(LinkedBlockingQueueTest.class);
}
/**
* Create a queue of given size containing consecutive
* Integers 0 ... n.
*/
private LinkedBlockingQueue populatedQueue(int n) {
LinkedBlockingQueue q = new LinkedBlockingQueue(n);
assertTrue(q.isEmpty());
for(int i = 0; i < n; i++)
assertTrue(q.offer(new Integer(i)));
assertFalse(q.isEmpty());
assertEquals(0, q.remainingCapacity());
assertEquals(n, q.size());
return q;
}
/**
* A new queue has the indicated capacity, or Integer.MAX_VALUE if
* none given
*/
public void testConstructor1() {
assertEquals(SIZE, new LinkedBlockingQueue(SIZE).remainingCapacity());
assertEquals(Integer.MAX_VALUE, new LinkedBlockingQueue().remainingCapacity());
}
/**
* Constructor throws IAE if capacity argument nonpositive
*/
public void testConstructor2() {
try {
LinkedBlockingQueue q = new LinkedBlockingQueue(0);
shouldThrow();
}
catch (IllegalArgumentException success) {}
}
/**
* Initializing from null Collection throws NPE
*/
public void testConstructor3() {
try {
LinkedBlockingQueue q = new LinkedBlockingQueue(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from Collection of null elements throws NPE
*/
public void testConstructor4() {
try {
Integer[] ints = new Integer[SIZE];
LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from Collection with some null elements throws NPE
*/
public void testConstructor5() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Queue contains all elements of collection used to initialize
*/
public void testConstructor6() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* Queue transitions from empty to full when elements added
*/
public void testEmptyFull() {
LinkedBlockingQueue q = new LinkedBlockingQueue(2);
assertTrue(q.isEmpty());
assertEquals("should have room for 2", 2, q.remainingCapacity());
q.add(one);
assertFalse(q.isEmpty());
q.add(two);
assertFalse(q.isEmpty());
assertEquals(0, q.remainingCapacity());
assertFalse(q.offer(three));
}
/**
* remainingCapacity decreases on add, increases on remove
*/
public void testRemainingCapacity() {
LinkedBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.remainingCapacity());
assertEquals(SIZE-i, q.size());
q.remove();
}
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i, q.remainingCapacity());
assertEquals(i, q.size());
q.add(new Integer(i));
}
}
/**
* offer(null) throws NPE
*/
public void testOfferNull() {
try {
LinkedBlockingQueue q = new LinkedBlockingQueue(1);
q.offer(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* add(null) throws NPE
*/
public void testAddNull() {
try {
LinkedBlockingQueue q = new LinkedBlockingQueue(1);
q.add(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* Offer succeeds if not full; fails if full
*/
public void testOffer() {
LinkedBlockingQueue q = new LinkedBlockingQueue(1);
assertTrue(q.offer(zero));
assertFalse(q.offer(one));
}
/**
* add succeeds if not full; throws ISE if full
*/
public void testAdd() {
try {
LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.add(new Integer(i)));
}
assertEquals(0, q.remainingCapacity());
q.add(new Integer(SIZE));
} catch (IllegalStateException success){
}
}
/**
* addAll(null) throws NPE
*/
public void testAddAll1() {
try {
LinkedBlockingQueue q = new LinkedBlockingQueue(1);
q.addAll(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll(this) throws IAE
*/
public void testAddAllSelf() {
try {
LinkedBlockingQueue q = populatedQueue(SIZE);
q.addAll(q);
shouldThrow();
}
catch (IllegalArgumentException success) {}
}
/**
* addAll of a collection with null elements throws NPE
*/
public void testAddAll2() {
try {
LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
Integer[] ints = new Integer[SIZE];
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with any null elements throws NPE after
* possibly adding some elements
*/
public void testAddAll3() {
try {
LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll throws ISE if not enough room
*/
public void testAddAll4() {
try {
LinkedBlockingQueue q = new LinkedBlockingQueue(1);
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (IllegalStateException success) {}
}
/**
* Queue contains all elements, in traversal order, of successful addAll
*/
public void testAddAll5() {
try {
Integer[] empty = new Integer[0];
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
assertFalse(q.addAll(Arrays.asList(empty)));
assertTrue(q.addAll(Arrays.asList(ints)));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* put(null) throws NPE
*/
public void testPutNull() {
try {
LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
q.put(null);
shouldThrow();
}
catch (NullPointerException success){
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* all elements successfully put are contained
*/
public void testPut() {
try {
LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
Integer I = new Integer(i);
q.put(I);
assertTrue(q.contains(I));
}
assertEquals(0, q.remainingCapacity());
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* put blocks interruptibly if full
*/
public void testBlockingPut() {
Thread t = new Thread(new Runnable() {
public void run() {
int added = 0;
try {
LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
q.put(new Integer(i));
++added;
}
q.put(new Integer(SIZE));
threadShouldThrow();
} catch (InterruptedException ie){
threadAssertEquals(added, SIZE);
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* put blocks waiting for take when full
*/
public void testPutWithTake() {
final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
Thread t = new Thread(new Runnable() {
public void run() {
int added = 0;
try {
q.put(new Object());
++added;
q.put(new Object());
++added;
q.put(new Object());
++added;
q.put(new Object());
++added;
threadShouldThrow();
} catch (InterruptedException e){
threadAssertTrue(added >= 2);
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
q.take();
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* timed offer times out if full and elements not taken
*/
public void testTimedOffer() {
final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.put(new Object());
q.put(new Object());
threadAssertFalse(q.offer(new Object(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
q.offer(new Object(), LONG_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch (InterruptedException success){}
}
});
try {
t.start();
Thread.sleep(SMALL_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* take retrieves elements in FIFO order
*/
public void testTake() {
try {
LinkedBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.take()).intValue());
}
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* take blocks interruptibly when empty
*/
public void testTakeFromEmpty() {
final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.take();
threadShouldThrow();
} catch (InterruptedException success){ }
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* Take removes existing elements until empty, then blocks interruptibly
*/
public void testBlockingTake() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
LinkedBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.take()).intValue());
}
q.take();
threadShouldThrow();
} catch (InterruptedException success){
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* poll succeeds unless empty
*/
public void testPoll() {
LinkedBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.poll()).intValue());
}
assertNull(q.poll());
}
/**
* timed pool with zero timeout succeeds when non-empty, else times out
*/
public void testTimedPoll0() {
try {
LinkedBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.poll(0, TimeUnit.MILLISECONDS)).intValue());
}
assertNull(q.poll(0, TimeUnit.MILLISECONDS));
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* timed pool with nonzero timeout succeeds when non-empty, else times out
*/
public void testTimedPoll() {
try {
LinkedBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
}
assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* Interrupted timed poll throws InterruptedException instead of
* returning timeout status
*/
public void testInterruptedTimedPoll() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
LinkedBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
threadAssertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
}
threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch (InterruptedException success){
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* timed poll before a delayed offer fails; after offer succeeds;
* on interruption throws
*/
public void testTimedPollWithOffer() {
final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch (InterruptedException success) { }
}
});
try {
t.start();
Thread.sleep(SMALL_DELAY_MS);
assertTrue(q.offer(zero, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* peek returns next element, or null if empty
*/
public void testPeek() {
LinkedBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.peek()).intValue());
q.poll();
assertTrue(q.peek() == null ||
i != ((Integer)q.peek()).intValue());
}
assertNull(q.peek());
}
/**
* element returns next element, or throws NSEE if empty
*/
public void testElement() {
LinkedBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.element()).intValue());
q.poll();
}
try {
q.element();
shouldThrow();
}
catch (NoSuchElementException success) {}
}
/**
* remove removes next element, or throws NSEE if empty
*/
public void testRemove() {
LinkedBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.remove()).intValue());
}
try {
q.remove();
shouldThrow();
} catch (NoSuchElementException success){
}
}
/**
* remove(x) removes x and returns true if present
*/
public void testRemoveElement() {
LinkedBlockingQueue q = populatedQueue(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
assertFalse(q.remove(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* An add following remove(x) succeeds
*/
public void testRemoveElementAndAdd() {
try {
LinkedBlockingQueue q = new LinkedBlockingQueue();
assertTrue(q.add(new Integer(1)));
assertTrue(q.add(new Integer(2)));
assertTrue(q.remove(new Integer(1)));
assertTrue(q.remove(new Integer(2)));
assertTrue(q.add(new Integer(3)));
assertTrue(q.take() != null);
} catch (Exception e){
unexpectedException();
}
}
/**
* contains(x) reports true when elements added but not yet removed
*/
public void testContains() {
LinkedBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.contains(new Integer(i)));
q.poll();
assertFalse(q.contains(new Integer(i)));
}
}
/**
* clear removes all elements
*/
public void testClear() {
LinkedBlockingQueue q = populatedQueue(SIZE);
q.clear();
assertTrue(q.isEmpty());
assertEquals(0, q.size());
assertEquals(SIZE, q.remainingCapacity());
q.add(one);
assertFalse(q.isEmpty());
assertTrue(q.contains(one));
q.clear();
assertTrue(q.isEmpty());
}
/**
* containsAll(c) is true when c contains a subset of elements
*/
public void testContainsAll() {
LinkedBlockingQueue q = populatedQueue(SIZE);
LinkedBlockingQueue p = new LinkedBlockingQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.containsAll(p));
assertFalse(p.containsAll(q));
p.add(new Integer(i));
}
assertTrue(p.containsAll(q));
}
/**
* retainAll(c) retains only those elements of c and reports true if changed
*/
public void testRetainAll() {
LinkedBlockingQueue q = populatedQueue(SIZE);
LinkedBlockingQueue p = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
boolean changed = q.retainAll(p);
if (i == 0)
assertFalse(changed);
else
assertTrue(changed);
assertTrue(q.containsAll(p));
assertEquals(SIZE-i, q.size());
p.remove();
}
}
/**
* removeAll(c) removes only those elements of c and reports true if changed
*/
public void testRemoveAll() {
for (int i = 1; i < SIZE; ++i) {
LinkedBlockingQueue q = populatedQueue(SIZE);
LinkedBlockingQueue p = populatedQueue(i);
assertTrue(q.removeAll(p));
assertEquals(SIZE-i, q.size());
for (int j = 0; j < i; ++j) {
Integer I = (Integer)(p.remove());
assertFalse(q.contains(I));
}
}
}
/**
* toArray contains all elements
*/
public void testToArray() {
LinkedBlockingQueue q = populatedQueue(SIZE);
Object[] o = q.toArray();
try {
for(int i = 0; i < o.length; i++)
assertEquals(o[i], q.take());
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* toArray(a) contains all elements
*/
public void testToArray2() {
LinkedBlockingQueue q = populatedQueue(SIZE);
Integer[] ints = new Integer[SIZE];
ints = (Integer[])q.toArray(ints);
try {
for(int i = 0; i < ints.length; i++)
assertEquals(ints[i], q.take());
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* toArray(null) throws NPE
*/
public void testToArray_BadArg() {
try {
LinkedBlockingQueue q = populatedQueue(SIZE);
Object o[] = q.toArray(null);
shouldThrow();
} catch(NullPointerException success){}
}
/**
* toArray with incompatible array type throws CCE
*/
public void testToArray1_BadArg() {
try {
LinkedBlockingQueue q = populatedQueue(SIZE);
Object o[] = q.toArray(new String[10] );
shouldThrow();
} catch(ArrayStoreException success){}
}
/**
* iterator iterates through all elements
*/
public void testIterator() {
LinkedBlockingQueue q = populatedQueue(SIZE);
Iterator it = q.iterator();
try {
while(it.hasNext()){
assertEquals(it.next(), q.take());
}
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* iterator.remove removes current element
*/
public void testIteratorRemove () {
final LinkedBlockingQueue q = new LinkedBlockingQueue(3);
q.add(two);
q.add(one);
q.add(three);
Iterator it = q.iterator();
it.next();
it.remove();
it = q.iterator();
assertEquals(it.next(), one);
assertEquals(it.next(), three);
assertFalse(it.hasNext());
}
/**
* iterator ordering is FIFO
*/
public void testIteratorOrdering() {
final LinkedBlockingQueue q = new LinkedBlockingQueue(3);
q.add(one);
q.add(two);
q.add(three);
assertEquals(0, q.remainingCapacity());
int k = 0;
for (Iterator it = q.iterator(); it.hasNext();) {
int i = ((Integer)(it.next())).intValue();
assertEquals(++k, i);
}
assertEquals(3, k);
}
/**
* Modifications do not cause iterators to fail
*/
public void testWeaklyConsistentIteration () {
final LinkedBlockingQueue q = new LinkedBlockingQueue(3);
q.add(one);
q.add(two);
q.add(three);
try {
for (Iterator it = q.iterator(); it.hasNext();) {
q.remove();
it.next();
}
}
catch (ConcurrentModificationException e) {
unexpectedException();
}
assertEquals(0, q.size());
}
/**
* toString contains toStrings of elements
*/
public void testToString() {
LinkedBlockingQueue q = populatedQueue(SIZE);
String s = q.toString();
for (int i = 0; i < SIZE; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
/**
* offer transfers elements across Executor tasks
*/
public void testOfferInExecutor() {
final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
q.add(one);
q.add(two);
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new Runnable() {
public void run() {
threadAssertFalse(q.offer(three));
try {
threadAssertTrue(q.offer(three, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
threadAssertEquals(0, q.remainingCapacity());
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
executor.execute(new Runnable() {
public void run() {
try {
Thread.sleep(SMALL_DELAY_MS);
threadAssertEquals(one, q.take());
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
joinPool(executor);
}
/**
* poll retrieves elements across Executor threads
*/
public void testPollInExecutor() {
final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new Runnable() {
public void run() {
threadAssertNull(q.poll());
try {
threadAssertTrue(null != q.poll(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
threadAssertTrue(q.isEmpty());
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
executor.execute(new Runnable() {
public void run() {
try {
Thread.sleep(SMALL_DELAY_MS);
q.put(one);
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
joinPool(executor);
}
/**
* A deserialized serialized queue has same elements in same order
*/
public void testSerialization() {
LinkedBlockingQueue q = populatedQueue(SIZE);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
LinkedBlockingQueue r = (LinkedBlockingQueue)in.readObject();
assertEquals(q.size(), r.size());
while (!q.isEmpty())
assertEquals(q.remove(), r.remove());
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* drainTo(null) throws NPE
*/
public void testDrainToNull() {
LinkedBlockingQueue q = populatedQueue(SIZE);
try {
q.drainTo(null);
shouldThrow();
} catch(NullPointerException success) {
}
}
/**
* drainTo(this) throws IAE
*/
public void testDrainToSelf() {
LinkedBlockingQueue q = populatedQueue(SIZE);
try {
q.drainTo(q);
shouldThrow();
} catch(IllegalArgumentException success) {
}
}
/**
* drainTo(c) empties queue into another collection c
*/
public void testDrainTo() {
LinkedBlockingQueue q = populatedQueue(SIZE);
ArrayList l = new ArrayList();
q.drainTo(l);
assertEquals(q.size(), 0);
assertEquals(l.size(), SIZE);
for (int i = 0; i < SIZE; ++i)
assertEquals(l.get(i), new Integer(i));
q.add(zero);
q.add(one);
assertFalse(q.isEmpty());
assertTrue(q.contains(zero));
assertTrue(q.contains(one));
l.clear();
q.drainTo(l);
assertEquals(q.size(), 0);
assertEquals(l.size(), 2);
for (int i = 0; i < 2; ++i)
assertEquals(l.get(i), new Integer(i));
}
/**
* drainTo empties full queue, unblocking a waiting put.
*/
public void testDrainToWithActivePut() {
final LinkedBlockingQueue q = populatedQueue(SIZE);
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.put(new Integer(SIZE+1));
} catch (InterruptedException ie){
threadUnexpectedException();
}
}
});
try {
t.start();
ArrayList l = new ArrayList();
q.drainTo(l);
assertTrue(l.size() >= SIZE);
for (int i = 0; i < SIZE; ++i)
assertEquals(l.get(i), new Integer(i));
t.join();
assertTrue(q.size() + l.size() >= SIZE);
} catch(Exception e){
unexpectedException();
}
}
/**
* drainTo(null, n) throws NPE
*/
public void testDrainToNullN() {
LinkedBlockingQueue q = populatedQueue(SIZE);
try {
q.drainTo(null, 0);
shouldThrow();
} catch(NullPointerException success) {
}
}
/**
* drainTo(this, n) throws IAE
*/
public void testDrainToSelfN() {
LinkedBlockingQueue q = populatedQueue(SIZE);
try {
q.drainTo(q, 0);
shouldThrow();
} catch(IllegalArgumentException success) {
}
}
/**
* drainTo(c, n) empties first max {n, size} elements of queue into c
*/
public void testDrainToN() {
LinkedBlockingQueue q = new LinkedBlockingQueue();
for (int i = 0; i < SIZE + 2; ++i) {
for(int j = 0; j < SIZE; j++)
assertTrue(q.offer(new Integer(j)));
ArrayList l = new ArrayList();
q.drainTo(l, i);
int k = (i < SIZE)? i : SIZE;
assertEquals(l.size(), k);
assertEquals(q.size(), SIZE-k);
for (int j = 0; j < k; ++j)
assertEquals(l.get(j), new Integer(j));
while (q.poll() != null) ;
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/SynchronousQueueTest.java 0000644 0017507 0003772 00000061351 10346121124 025277 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.io.*;
import edu.emory.mathcs.backport.java.util.*;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Iterator;
import java.util.ArrayList;
public class SynchronousQueueTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(SynchronousQueueTest.class);
}
/**
* A SynchronousQueue is both empty and full
*/
public void testEmptyFull() {
SynchronousQueue q = new SynchronousQueue();
assertTrue(q.isEmpty());
assertEquals(0, q.size());
assertEquals(0, q.remainingCapacity());
assertFalse(q.offer(zero));
}
/**
* A fair SynchronousQueue is both empty and full
*/
public void testFairEmptyFull() {
SynchronousQueue q = new SynchronousQueue(true);
assertTrue(q.isEmpty());
assertEquals(0, q.size());
assertEquals(0, q.remainingCapacity());
assertFalse(q.offer(zero));
}
/**
* offer(null) throws NPE
*/
public void testOfferNull() {
try {
SynchronousQueue q = new SynchronousQueue();
q.offer(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* add(null) throws NPE
*/
public void testAddNull() {
try {
SynchronousQueue q = new SynchronousQueue();
q.add(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* offer fails if no active taker
*/
public void testOffer() {
SynchronousQueue q = new SynchronousQueue();
assertFalse(q.offer(one));
}
/**
* add throws ISE if no active taker
*/
public void testAdd() {
try {
SynchronousQueue q = new SynchronousQueue();
assertEquals(0, q.remainingCapacity());
q.add(one);
shouldThrow();
} catch (IllegalStateException success){
}
}
/**
* addAll(null) throws NPE
*/
public void testAddAll1() {
try {
SynchronousQueue q = new SynchronousQueue();
q.addAll(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll(this) throws IAE
*/
public void testAddAllSelf() {
try {
SynchronousQueue q = new SynchronousQueue();
q.addAll(q);
shouldThrow();
}
catch (IllegalArgumentException success) {}
}
/**
* addAll of a collection with null elements throws NPE
*/
public void testAddAll2() {
try {
SynchronousQueue q = new SynchronousQueue();
Integer[] ints = new Integer[1];
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll throws ISE if no active taker
*/
public void testAddAll4() {
try {
SynchronousQueue q = new SynchronousQueue();
Integer[] ints = new Integer[1];
for (int i = 0; i < 1; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (IllegalStateException success) {}
}
/**
* put(null) throws NPE
*/
public void testPutNull() {
try {
SynchronousQueue q = new SynchronousQueue();
q.put(null);
shouldThrow();
}
catch (NullPointerException success){
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* put blocks interruptibly if no active taker
*/
public void testBlockingPut() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
SynchronousQueue q = new SynchronousQueue();
q.put(zero);
threadShouldThrow();
} catch (InterruptedException ie){
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* put blocks waiting for take
*/
public void testPutWithTake() {
final SynchronousQueue q = new SynchronousQueue();
Thread t = new Thread(new Runnable() {
public void run() {
int added = 0;
try {
q.put(new Object());
++added;
q.put(new Object());
++added;
q.put(new Object());
++added;
q.put(new Object());
++added;
threadShouldThrow();
} catch (InterruptedException e){
assertTrue(added >= 1);
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
q.take();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* timed offer times out if elements not taken
*/
public void testTimedOffer() {
final SynchronousQueue q = new SynchronousQueue();
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertFalse(q.offer(new Object(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
q.offer(new Object(), LONG_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch (InterruptedException success){}
}
});
try {
t.start();
Thread.sleep(SMALL_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* take blocks interruptibly when empty
*/
public void testTakeFromEmpty() {
final SynchronousQueue q = new SynchronousQueue();
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.take();
threadShouldThrow();
} catch (InterruptedException success){ }
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* put blocks interruptibly if no active taker
*/
public void testFairBlockingPut() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
SynchronousQueue q = new SynchronousQueue(true);
q.put(zero);
threadShouldThrow();
} catch (InterruptedException ie){
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* put blocks waiting for take
*/
public void testFairPutWithTake() {
final SynchronousQueue q = new SynchronousQueue(true);
Thread t = new Thread(new Runnable() {
public void run() {
int added = 0;
try {
q.put(new Object());
++added;
q.put(new Object());
++added;
q.put(new Object());
++added;
q.put(new Object());
++added;
threadShouldThrow();
} catch (InterruptedException e){
assertTrue(added >= 1);
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
q.take();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* timed offer times out if elements not taken
*/
public void testFairTimedOffer() {
final SynchronousQueue q = new SynchronousQueue(true);
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertFalse(q.offer(new Object(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
q.offer(new Object(), LONG_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch (InterruptedException success){}
}
});
try {
t.start();
Thread.sleep(SMALL_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* take blocks interruptibly when empty
*/
public void testFairTakeFromEmpty() {
final SynchronousQueue q = new SynchronousQueue(true);
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.take();
threadShouldThrow();
} catch (InterruptedException success){ }
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* poll fails unless active taker
*/
public void testPoll() {
SynchronousQueue q = new SynchronousQueue();
assertNull(q.poll());
}
/**
* timed pool with zero timeout times out if no active taker
*/
public void testTimedPoll0() {
try {
SynchronousQueue q = new SynchronousQueue();
assertNull(q.poll(0, TimeUnit.MILLISECONDS));
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* timed pool with nonzero timeout times out if no active taker
*/
public void testTimedPoll() {
try {
SynchronousQueue q = new SynchronousQueue();
assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* Interrupted timed poll throws InterruptedException instead of
* returning timeout status
*/
public void testInterruptedTimedPoll() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
SynchronousQueue q = new SynchronousQueue();
assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch (InterruptedException success){
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* timed poll before a delayed offer fails; after offer succeeds;
* on interruption throws
*/
public void testTimedPollWithOffer() {
final SynchronousQueue q = new SynchronousQueue();
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch (InterruptedException success) { }
}
});
try {
t.start();
Thread.sleep(SMALL_DELAY_MS);
assertTrue(q.offer(zero, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* Interrupted timed poll throws InterruptedException instead of
* returning timeout status
*/
public void testFairInterruptedTimedPoll() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
SynchronousQueue q = new SynchronousQueue(true);
assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch (InterruptedException success){
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* timed poll before a delayed offer fails; after offer succeeds;
* on interruption throws
*/
public void testFairTimedPollWithOffer() {
final SynchronousQueue q = new SynchronousQueue(true);
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch (InterruptedException success) { }
}
});
try {
t.start();
Thread.sleep(SMALL_DELAY_MS);
assertTrue(q.offer(zero, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* peek returns null
*/
public void testPeek() {
SynchronousQueue q = new SynchronousQueue();
assertNull(q.peek());
}
/**
* element throws NSEE
*/
public void testElement() {
SynchronousQueue q = new SynchronousQueue();
try {
q.element();
shouldThrow();
}
catch (NoSuchElementException success) {}
}
/**
* remove throws NSEE if no active taker
*/
public void testRemove() {
SynchronousQueue q = new SynchronousQueue();
try {
q.remove();
shouldThrow();
} catch (NoSuchElementException success){
}
}
/**
* remove(x) returns false
*/
public void testRemoveElement() {
SynchronousQueue q = new SynchronousQueue();
assertFalse(q.remove(zero));
assertTrue(q.isEmpty());
}
/**
* contains returns false
*/
public void testContains() {
SynchronousQueue q = new SynchronousQueue();
assertFalse(q.contains(zero));
}
/**
* clear ensures isEmpty
*/
public void testClear() {
SynchronousQueue q = new SynchronousQueue();
q.clear();
assertTrue(q.isEmpty());
}
/**
* containsAll returns false unless empty
*/
public void testContainsAll() {
SynchronousQueue q = new SynchronousQueue();
Integer[] empty = new Integer[0];
assertTrue(q.containsAll(Arrays.asList(empty)));
Integer[] ints = new Integer[1]; ints[0] = zero;
assertFalse(q.containsAll(Arrays.asList(ints)));
}
/**
* retainAll returns false
*/
public void testRetainAll() {
SynchronousQueue q = new SynchronousQueue();
Integer[] empty = new Integer[0];
assertFalse(q.retainAll(Arrays.asList(empty)));
Integer[] ints = new Integer[1]; ints[0] = zero;
assertFalse(q.retainAll(Arrays.asList(ints)));
}
/**
* removeAll returns false
*/
public void testRemoveAll() {
SynchronousQueue q = new SynchronousQueue();
Integer[] empty = new Integer[0];
assertFalse(q.removeAll(Arrays.asList(empty)));
Integer[] ints = new Integer[1]; ints[0] = zero;
assertFalse(q.containsAll(Arrays.asList(ints)));
}
/**
* toArray is empty
*/
public void testToArray() {
SynchronousQueue q = new SynchronousQueue();
Object[] o = q.toArray();
assertEquals(o.length, 0);
}
/**
* toArray(a) is nulled at position 0
*/
public void testToArray2() {
SynchronousQueue q = new SynchronousQueue();
Integer[] ints = new Integer[1];
assertNull(ints[0]);
}
/**
* toArray(null) throws NPE
*/
public void testToArray_BadArg() {
try {
SynchronousQueue q = new SynchronousQueue();
Object o[] = q.toArray(null);
shouldThrow();
} catch(NullPointerException success){}
}
/**
* iterator does not traverse any elements
*/
public void testIterator() {
SynchronousQueue q = new SynchronousQueue();
Iterator it = q.iterator();
assertFalse(it.hasNext());
try {
Object x = it.next();
shouldThrow();
}
catch (NoSuchElementException success) {}
}
/**
* iterator remove throws ISE
*/
public void testIteratorRemove() {
SynchronousQueue q = new SynchronousQueue();
Iterator it = q.iterator();
try {
it.remove();
shouldThrow();
}
catch (IllegalStateException success) {}
}
/**
* toString returns a non-null string
*/
public void testToString() {
SynchronousQueue q = new SynchronousQueue();
String s = q.toString();
assertNotNull(s);
}
/**
* offer transfers elements across Executor tasks
*/
public void testOfferInExecutor() {
final SynchronousQueue q = new SynchronousQueue();
ExecutorService executor = Executors.newFixedThreadPool(2);
final Integer one = new Integer(1);
executor.execute(new Runnable() {
public void run() {
threadAssertFalse(q.offer(one));
try {
threadAssertTrue(q.offer(one, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
threadAssertEquals(0, q.remainingCapacity());
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
executor.execute(new Runnable() {
public void run() {
try {
Thread.sleep(SMALL_DELAY_MS);
threadAssertEquals(one, q.take());
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
joinPool(executor);
}
/**
* poll retrieves elements across Executor threads
*/
public void testPollInExecutor() {
final SynchronousQueue q = new SynchronousQueue();
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new Runnable() {
public void run() {
threadAssertNull(q.poll());
try {
threadAssertTrue(null != q.poll(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
threadAssertTrue(q.isEmpty());
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
executor.execute(new Runnable() {
public void run() {
try {
Thread.sleep(SMALL_DELAY_MS);
q.put(new Integer(1));
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
joinPool(executor);
}
/**
* a deserialized serialized queue is usable
*/
public void testSerialization() {
SynchronousQueue q = new SynchronousQueue();
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
SynchronousQueue r = (SynchronousQueue)in.readObject();
assertEquals(q.size(), r.size());
while (!q.isEmpty())
assertEquals(q.remove(), r.remove());
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* drainTo(null) throws NPE
*/
public void testDrainToNull() {
SynchronousQueue q = new SynchronousQueue();
try {
q.drainTo(null);
shouldThrow();
} catch(NullPointerException success) {
}
}
/**
* drainTo(this) throws IAE
*/
public void testDrainToSelf() {
SynchronousQueue q = new SynchronousQueue();
try {
q.drainTo(q);
shouldThrow();
} catch(IllegalArgumentException success) {
}
}
/**
* drainTo(c) of empty queue doesn't transfer elements
*/
public void testDrainTo() {
SynchronousQueue q = new SynchronousQueue();
ArrayList l = new ArrayList();
q.drainTo(l);
assertEquals(q.size(), 0);
assertEquals(l.size(), 0);
}
/**
* drainTo empties queue, unblocking a waiting put.
*/
public void testDrainToWithActivePut() {
final SynchronousQueue q = new SynchronousQueue();
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.put(new Integer(1));
} catch (InterruptedException ie){
threadUnexpectedException();
}
}
});
try {
t.start();
ArrayList l = new ArrayList();
Thread.sleep(SHORT_DELAY_MS);
q.drainTo(l);
assertTrue(l.size() <= 1);
if (l.size() > 0)
assertEquals(l.get(0), new Integer(1));
t.join();
assertTrue(l.size() <= 1);
} catch(Exception e){
unexpectedException();
}
}
/**
* drainTo(null, n) throws NPE
*/
public void testDrainToNullN() {
SynchronousQueue q = new SynchronousQueue();
try {
q.drainTo(null, 0);
shouldThrow();
} catch(NullPointerException success) {
}
}
/**
* drainTo(this, n) throws IAE
*/
public void testDrainToSelfN() {
SynchronousQueue q = new SynchronousQueue();
try {
q.drainTo(q, 0);
shouldThrow();
} catch(IllegalArgumentException success) {
}
}
/**
* drainTo(c, n) empties up to n elements of queue into c
*/
public void testDrainToN() {
final SynchronousQueue q = new SynchronousQueue();
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
q.put(one);
} catch (InterruptedException ie){
threadUnexpectedException();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
q.put(two);
} catch (InterruptedException ie){
threadUnexpectedException();
}
}
});
try {
t1.start();
t2.start();
ArrayList l = new ArrayList();
Thread.sleep(SHORT_DELAY_MS);
q.drainTo(l, 1);
assertTrue(l.size() == 1);
q.drainTo(l, 1);
assertTrue(l.size() == 2);
assertTrue(l.contains(one));
assertTrue(l.contains(two));
t1.join();
t2.join();
} catch(Exception e){
unexpectedException();
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/ThreadTest.java 0000644 0017507 0003772 00000004654 10153210664 023156 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
public class ThreadTest extends JSR166TestCase {
// public static void main(String[] args) {
// junit.textui.TestRunner.run(suite());
// }
//
// public static Test suite() {
// return new TestSuite(ThreadTest.class);
// }
// static class MyHandler implements Thread.UncaughtExceptionHandler {
// public void uncaughtException(Thread t, Throwable e) {
// e.printStackTrace();
// }
// }
// /**
// * getUncaughtExceptionHandler returns ThreadGroup unless set,
// * otherwise returning value of last setUncaughtExceptionHandler.
// */
// public void testGetAndSetUncaughtExceptionHandler() {
// // these must be done all at once to avoid state
// // dependencies across tests
// Thread current = Thread.currentThread();
// ThreadGroup tg = current.getThreadGroup();
// MyHandler eh = new MyHandler();
// assertEquals(tg, current.getUncaughtExceptionHandler());
// current.setUncaughtExceptionHandler(eh);
// assertEquals(eh, current.getUncaughtExceptionHandler());
// current.setUncaughtExceptionHandler(null);
// assertEquals(tg, current.getUncaughtExceptionHandler());
// }
//
// /**
// * getDefaultUncaughtExceptionHandler returns value of last
// * setDefaultUncaughtExceptionHandler.
// */
// public void testGetAndSetDefaultUncaughtExceptionHandler() {
// assertEquals(null, Thread.getDefaultUncaughtExceptionHandler());
// // failure due to securityException is OK.
// // Would be nice to explicitly test both ways, but cannot yet.
// try {
// Thread current = Thread.currentThread();
// ThreadGroup tg = current.getThreadGroup();
// MyHandler eh = new MyHandler();
// Thread.setDefaultUncaughtExceptionHandler(eh);
// assertEquals(eh, Thread.getDefaultUncaughtExceptionHandler());
// Thread.setDefaultUncaughtExceptionHandler(null);
// }
// catch(SecurityException ok) {
// }
// assertEquals(null, Thread.getDefaultUncaughtExceptionHandler());
// }
// How to test actually using UEH within junit?
}
backport-util-concurrent-3.1-src/test/tck/src/ConcurrentSkipListMapTest.java 0000644 0017507 0003772 00000112704 10431777323 026217 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.io.*;
import java.util.Random;
import java.util.BitSet;
import java.util.Set;
import java.util.Iterator;
import java.util.Map;
import java.util.Collection;
import java.util.ArrayList;
import java.util.NoSuchElementException;
public class ConcurrentSkipListMapTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(ConcurrentSkipListMapTest.class);
}
/**
* Create a map from Integers 1-5 to Strings "A"-"E".
*/
private static ConcurrentSkipListMap map5() {
ConcurrentSkipListMap map = new ConcurrentSkipListMap();
assertTrue(map.isEmpty());
map.put(one, "A");
map.put(five, "E");
map.put(three, "C");
map.put(two, "B");
map.put(four, "D");
assertFalse(map.isEmpty());
assertEquals(5, map.size());
return map;
}
/**
* clear removes all pairs
*/
public void testClear() {
ConcurrentSkipListMap map = map5();
map.clear();
assertEquals(map.size(), 0);
}
/**
*
*/
public void testConstructFromSorted() {
ConcurrentSkipListMap map = map5();
ConcurrentSkipListMap map2 = new ConcurrentSkipListMap(map);
assertEquals(map, map2);
}
/**
* Maps with same contents are equal
*/
public void testEquals() {
ConcurrentSkipListMap map1 = map5();
ConcurrentSkipListMap map2 = map5();
assertEquals(map1, map2);
assertEquals(map2, map1);
map1.clear();
assertFalse(map1.equals(map2));
assertFalse(map2.equals(map1));
}
/**
* containsKey returns true for contained key
*/
public void testContainsKey() {
ConcurrentSkipListMap map = map5();
assertTrue(map.containsKey(one));
assertFalse(map.containsKey(zero));
}
/**
* containsValue returns true for held values
*/
public void testContainsValue() {
ConcurrentSkipListMap map = map5();
assertTrue(map.containsValue("A"));
assertFalse(map.containsValue("Z"));
}
/**
* get returns the correct element at the given key,
* or null if not present
*/
public void testGet() {
ConcurrentSkipListMap map = map5();
assertEquals("A", (String)map.get(one));
ConcurrentSkipListMap empty = new ConcurrentSkipListMap();
assertNull(empty.get(one));
}
/**
* isEmpty is true of empty map and false for non-empty
*/
public void testIsEmpty() {
ConcurrentSkipListMap empty = new ConcurrentSkipListMap();
ConcurrentSkipListMap map = map5();
assertTrue(empty.isEmpty());
assertFalse(map.isEmpty());
}
/**
* firstKey returns first key
*/
public void testFirstKey() {
ConcurrentSkipListMap map = map5();
assertEquals(one, map.firstKey());
}
/**
* lastKey returns last key
*/
public void testLastKey() {
ConcurrentSkipListMap map = map5();
assertEquals(five, map.lastKey());
}
/**
* keySet.toArray returns contains all keys
*/
public void testKeySetToArray() {
ConcurrentSkipListMap map = map5();
Set s = map.keySet();
Object[] ar = s.toArray();
assertTrue(s.containsAll(Arrays.asList(ar)));
assertEquals(5, ar.length);
ar[0] = m10;
assertFalse(s.containsAll(Arrays.asList(ar)));
}
/**
* descendingkeySet.toArray returns contains all keys
*/
public void testDescendingKeySetToArray() {
ConcurrentSkipListMap map = map5();
Set s = map.descendingKeySet();
Object[] ar = s.toArray();
assertEquals(5, ar.length);
assertTrue(s.containsAll(Arrays.asList(ar)));
ar[0] = m10;
assertFalse(s.containsAll(Arrays.asList(ar)));
}
/**
* keySet returns a Set containing all the keys
*/
public void testKeySet() {
ConcurrentSkipListMap map = map5();
Set s = map.keySet();
assertEquals(5, s.size());
assertTrue(s.contains(one));
assertTrue(s.contains(two));
assertTrue(s.contains(three));
assertTrue(s.contains(four));
assertTrue(s.contains(five));
}
/**
* keySet is ordered
*/
public void testKeySetOrder() {
ConcurrentSkipListMap map = map5();
Set s = map.keySet();
Iterator i = s.iterator();
Integer last = (Integer)i.next();
assertEquals(last, one);
while (i.hasNext()) {
Integer k = (Integer)i.next();
assertTrue(last.compareTo(k) < 0);
last = k;
}
}
/**
* descendingKeySet is ordered
*/
public void testDescendingKeySetOrder() {
ConcurrentSkipListMap map = map5();
Set s = map.descendingKeySet();
Iterator i = s.iterator();
Integer last = (Integer)i.next();
assertEquals(last, five);
while (i.hasNext()) {
Integer k = (Integer)i.next();
assertTrue(last.compareTo(k) > 0);
last = k;
}
}
/**
* Values.toArray contains all values
*/
public void testValuesToArray() {
ConcurrentSkipListMap map = map5();
Collection v = map.values();
Object[] ar = v.toArray();
ArrayList s = new ArrayList(Arrays.asList(ar));
assertEquals(5, ar.length);
assertTrue(s.contains("A"));
assertTrue(s.contains("B"));
assertTrue(s.contains("C"));
assertTrue(s.contains("D"));
assertTrue(s.contains("E"));
}
/**
* values collection contains all values
*/
public void testValues() {
ConcurrentSkipListMap map = map5();
Collection s = map.values();
assertEquals(5, s.size());
assertTrue(s.contains("A"));
assertTrue(s.contains("B"));
assertTrue(s.contains("C"));
assertTrue(s.contains("D"));
assertTrue(s.contains("E"));
}
/**
* entrySet contains all pairs
*/
public void testEntrySet() {
ConcurrentSkipListMap map = map5();
Set s = map.entrySet();
assertEquals(5, s.size());
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
assertTrue(
(e.getKey().equals(one) && e.getValue().equals("A")) ||
(e.getKey().equals(two) && e.getValue().equals("B")) ||
(e.getKey().equals(three) && e.getValue().equals("C")) ||
(e.getKey().equals(four) && e.getValue().equals("D")) ||
(e.getKey().equals(five) && e.getValue().equals("E")));
}
}
/**
* descendingEntrySet contains all pairs
*/
public void testDescendingEntrySet() {
ConcurrentSkipListMap map = map5();
Set s = map.descendingMap().entrySet();
assertEquals(5, s.size());
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
assertTrue(
(e.getKey().equals(one) && e.getValue().equals("A")) ||
(e.getKey().equals(two) && e.getValue().equals("B")) ||
(e.getKey().equals(three) && e.getValue().equals("C")) ||
(e.getKey().equals(four) && e.getValue().equals("D")) ||
(e.getKey().equals(five) && e.getValue().equals("E")));
}
}
/**
* entrySet.toArray contains all entries
*/
public void testEntrySetToArray() {
ConcurrentSkipListMap map = map5();
Set s = map.entrySet();
Object[] ar = s.toArray();
assertEquals(5, ar.length);
for (int i = 0; i < 5; ++i) {
assertTrue(map.containsKey(((Map.Entry)(ar[i])).getKey()));
assertTrue(map.containsValue(((Map.Entry)(ar[i])).getValue()));
}
}
/**
* descendingEntrySet.toArray contains all entries
*/
public void testDescendingEntrySetToArray() {
ConcurrentSkipListMap map = map5();
Set s = map.descendingMap().entrySet();
Object[] ar = s.toArray();
assertEquals(5, ar.length);
for (int i = 0; i < 5; ++i) {
assertTrue(map.containsKey(((Map.Entry)(ar[i])).getKey()));
assertTrue(map.containsValue(((Map.Entry)(ar[i])).getValue()));
}
}
/**
* putAll adds all key-value pairs from the given map
*/
public void testPutAll() {
ConcurrentSkipListMap empty = new ConcurrentSkipListMap();
ConcurrentSkipListMap map = map5();
empty.putAll(map);
assertEquals(5, empty.size());
assertTrue(empty.containsKey(one));
assertTrue(empty.containsKey(two));
assertTrue(empty.containsKey(three));
assertTrue(empty.containsKey(four));
assertTrue(empty.containsKey(five));
}
/**
* putIfAbsent works when the given key is not present
*/
public void testPutIfAbsent() {
ConcurrentSkipListMap map = map5();
map.putIfAbsent(six, "Z");
assertTrue(map.containsKey(six));
}
/**
* putIfAbsent does not add the pair if the key is already present
*/
public void testPutIfAbsent2() {
ConcurrentSkipListMap map = map5();
assertEquals("A", map.putIfAbsent(one, "Z"));
}
/**
* replace fails when the given key is not present
*/
public void testReplace() {
ConcurrentSkipListMap map = map5();
assertNull(map.replace(six, "Z"));
assertFalse(map.containsKey(six));
}
/**
* replace succeeds if the key is already present
*/
public void testReplace2() {
ConcurrentSkipListMap map = map5();
assertNotNull(map.replace(one, "Z"));
assertEquals("Z", map.get(one));
}
/**
* replace value fails when the given key not mapped to expected value
*/
public void testReplaceValue() {
ConcurrentSkipListMap map = map5();
assertEquals("A", map.get(one));
assertFalse(map.replace(one, "Z", "Z"));
assertEquals("A", map.get(one));
}
/**
* replace value succeeds when the given key mapped to expected value
*/
public void testReplaceValue2() {
ConcurrentSkipListMap map = map5();
assertEquals("A", map.get(one));
assertTrue(map.replace(one, "A", "Z"));
assertEquals("Z", map.get(one));
}
/**
* remove removes the correct key-value pair from the map
*/
public void testRemove() {
ConcurrentSkipListMap map = map5();
map.remove(five);
assertEquals(4, map.size());
assertFalse(map.containsKey(five));
}
/**
* remove(key,value) removes only if pair present
*/
public void testRemove2() {
ConcurrentSkipListMap map = map5();
assertTrue(map.containsKey(five));
assertEquals("E", map.get(five));
map.remove(five, "E");
assertEquals(4, map.size());
assertFalse(map.containsKey(five));
map.remove(four, "A");
assertEquals(4, map.size());
assertTrue(map.containsKey(four));
}
/**
* lowerEntry returns preceding entry.
*/
public void testLowerEntry() {
ConcurrentSkipListMap map = map5();
Map.Entry e1 = map.lowerEntry(three);
assertEquals(two, e1.getKey());
Map.Entry e2 = map.lowerEntry(six);
assertEquals(five, e2.getKey());
Map.Entry e3 = map.lowerEntry(one);
assertNull(e3);
Map.Entry e4 = map.lowerEntry(zero);
assertNull(e4);
}
/**
* higherEntry returns next entry.
*/
public void testHigherEntry() {
ConcurrentSkipListMap map = map5();
Map.Entry e1 = map.higherEntry(three);
assertEquals(four, e1.getKey());
Map.Entry e2 = map.higherEntry(zero);
assertEquals(one, e2.getKey());
Map.Entry e3 = map.higherEntry(five);
assertNull(e3);
Map.Entry e4 = map.higherEntry(six);
assertNull(e4);
}
/**
* floorEntry returns preceding entry.
*/
public void testFloorEntry() {
ConcurrentSkipListMap map = map5();
Map.Entry e1 = map.floorEntry(three);
assertEquals(three, e1.getKey());
Map.Entry e2 = map.floorEntry(six);
assertEquals(five, e2.getKey());
Map.Entry e3 = map.floorEntry(one);
assertEquals(one, e3.getKey());
Map.Entry e4 = map.floorEntry(zero);
assertNull(e4);
}
/**
* ceilingEntry returns next entry.
*/
public void testCeilingEntry() {
ConcurrentSkipListMap map = map5();
Map.Entry e1 = map.ceilingEntry(three);
assertEquals(three, e1.getKey());
Map.Entry e2 = map.ceilingEntry(zero);
assertEquals(one, e2.getKey());
Map.Entry e3 = map.ceilingEntry(five);
assertEquals(five, e3.getKey());
Map.Entry e4 = map.ceilingEntry(six);
assertNull(e4);
}
/**
* lowerEntry, higherEntry, ceilingEntry, and floorEntry return
* imutable entries
*/
public void testEntryImmutablity() {
ConcurrentSkipListMap map = map5();
Map.Entry e = map.lowerEntry(three);
assertEquals(two, e.getKey());
try {
e.setValue("X");
fail();
} catch(UnsupportedOperationException success) {}
e = map.higherEntry(zero);
assertEquals(one, e.getKey());
try {
e.setValue("X");
fail();
} catch(UnsupportedOperationException success) {}
e = map.floorEntry(one);
assertEquals(one, e.getKey());
try {
e.setValue("X");
fail();
} catch(UnsupportedOperationException success) {}
e = map.ceilingEntry(five);
assertEquals(five, e.getKey());
try {
e.setValue("X");
fail();
} catch(UnsupportedOperationException success) {}
}
/**
* lowerKey returns preceding element
*/
public void testLowerKey() {
ConcurrentSkipListMap q = map5();
Object e1 = q.lowerKey(three);
assertEquals(two, e1);
Object e2 = q.lowerKey(six);
assertEquals(five, e2);
Object e3 = q.lowerKey(one);
assertNull(e3);
Object e4 = q.lowerKey(zero);
assertNull(e4);
}
/**
* higherKey returns next element
*/
public void testHigherKey() {
ConcurrentSkipListMap q = map5();
Object e1 = q.higherKey(three);
assertEquals(four, e1);
Object e2 = q.higherKey(zero);
assertEquals(one, e2);
Object e3 = q.higherKey(five);
assertNull(e3);
Object e4 = q.higherKey(six);
assertNull(e4);
}
/**
* floorKey returns preceding element
*/
public void testFloorKey() {
ConcurrentSkipListMap q = map5();
Object e1 = q.floorKey(three);
assertEquals(three, e1);
Object e2 = q.floorKey(six);
assertEquals(five, e2);
Object e3 = q.floorKey(one);
assertEquals(one, e3);
Object e4 = q.floorKey(zero);
assertNull(e4);
}
/**
* ceilingKey returns next element
*/
public void testCeilingKey() {
ConcurrentSkipListMap q = map5();
Object e1 = q.ceilingKey(three);
assertEquals(three, e1);
Object e2 = q.ceilingKey(zero);
assertEquals(one, e2);
Object e3 = q.ceilingKey(five);
assertEquals(five, e3);
Object e4 = q.ceilingKey(six);
assertNull(e4);
}
/**
* pollFirstEntry returns entries in order
*/
public void testPollFirstEntry() {
ConcurrentSkipListMap map = map5();
Map.Entry e = map.pollFirstEntry();
assertEquals(one, e.getKey());
assertEquals("A", e.getValue());
e = map.pollFirstEntry();
assertEquals(two, e.getKey());
map.put(one, "A");
e = map.pollFirstEntry();
assertEquals(one, e.getKey());
assertEquals("A", e.getValue());
e = map.pollFirstEntry();
assertEquals(three, e.getKey());
map.remove(four);
e = map.pollFirstEntry();
assertEquals(five, e.getKey());
try {
e.setValue("A");
shouldThrow();
} catch (Exception ok) {
}
e = map.pollFirstEntry();
assertNull(e);
}
/**
* pollLastEntry returns entries in order
*/
public void testPollLastEntry() {
ConcurrentSkipListMap map = map5();
Map.Entry e = map.pollLastEntry();
assertEquals(five, e.getKey());
assertEquals("E", e.getValue());
e = map.pollLastEntry();
assertEquals(four, e.getKey());
map.put(five, "E");
e = map.pollLastEntry();
assertEquals(five, e.getKey());
assertEquals("E", e.getValue());
e = map.pollLastEntry();
assertEquals(three, e.getKey());
map.remove(two);
e = map.pollLastEntry();
assertEquals(one, e.getKey());
try {
e.setValue("E");
shouldThrow();
} catch (Exception ok) {
}
e = map.pollLastEntry();
assertNull(e);
}
/**
* size returns the correct values
*/
public void testSize() {
ConcurrentSkipListMap map = map5();
ConcurrentSkipListMap empty = new ConcurrentSkipListMap();
assertEquals(0, empty.size());
assertEquals(5, map.size());
}
/**
* toString contains toString of elements
*/
public void testToString() {
ConcurrentSkipListMap map = map5();
String s = map.toString();
for (int i = 1; i <= 5; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
// Exception tests
/**
* get(null) of nonempty map throws NPE
*/
public void testGet_NullPointerException() {
try {
ConcurrentSkipListMap c = map5();
c.get(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* containsKey(null) of nonempty map throws NPE
*/
public void testContainsKey_NullPointerException() {
try {
ConcurrentSkipListMap c = map5();
c.containsKey(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* containsValue(null) throws NPE
*/
public void testContainsValue_NullPointerException() {
try {
ConcurrentSkipListMap c = new ConcurrentSkipListMap();
c.containsValue(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* put(null,x) throws NPE
*/
public void testPut1_NullPointerException() {
try {
ConcurrentSkipListMap c = map5();
c.put(null, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* putIfAbsent(null, x) throws NPE
*/
public void testPutIfAbsent1_NullPointerException() {
try {
ConcurrentSkipListMap c = map5();
c.putIfAbsent(null, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* replace(null, x) throws NPE
*/
public void testReplace_NullPointerException() {
try {
ConcurrentSkipListMap c = map5();
c.replace(null, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* replace(null, x, y) throws NPE
*/
public void testReplaceValue_NullPointerException() {
try {
ConcurrentSkipListMap c = map5();
c.replace(null, one, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* remove(null) throws NPE
*/
public void testRemove1_NullPointerException() {
try {
ConcurrentSkipListMap c = new ConcurrentSkipListMap();
c.put("sadsdf", "asdads");
c.remove(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* remove(null, x) throws NPE
*/
public void testRemove2_NullPointerException() {
try {
ConcurrentSkipListMap c = new ConcurrentSkipListMap();
c.put("sadsdf", "asdads");
c.remove(null, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* remove(x, null) returns false
*/
public void testRemove3() {
try {
ConcurrentSkipListMap c = new ConcurrentSkipListMap();
c.put("sadsdf", "asdads");
assertFalse(c.remove("sadsdf", null));
} catch(NullPointerException e){
fail();
}
}
/**
* A deserialized map equals original
*/
public void testSerialization() {
ConcurrentSkipListMap q = map5();
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
ConcurrentSkipListMap r = (ConcurrentSkipListMap)in.readObject();
assertEquals(q.size(), r.size());
assertTrue(q.equals(r));
assertTrue(r.equals(q));
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* subMap returns map with keys in requested range
*/
public void testSubMapContents() {
ConcurrentSkipListMap map = map5();
NavigableMap sm = map.subMap(two, true, four, false);
assertEquals(two, sm.firstKey());
assertEquals(three, sm.lastKey());
assertEquals(2, sm.size());
assertFalse(sm.containsKey(one));
assertTrue(sm.containsKey(two));
assertTrue(sm.containsKey(three));
assertFalse(sm.containsKey(four));
assertFalse(sm.containsKey(five));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
assertFalse(i.hasNext());
Iterator r = sm.descendingKeySet().iterator();
k = (Integer)(r.next());
assertEquals(three, k);
k = (Integer)(r.next());
assertEquals(two, k);
assertFalse(r.hasNext());
Iterator j = sm.keySet().iterator();
j.next();
j.remove();
assertFalse(map.containsKey(two));
assertEquals(4, map.size());
assertEquals(1, sm.size());
assertEquals(three, sm.firstKey());
assertEquals(three, sm.lastKey());
assertTrue(sm.remove(three) != null);
assertTrue(sm.isEmpty());
assertEquals(3, map.size());
}
public void testSubMapContents2() {
ConcurrentSkipListMap map = map5();
NavigableMap sm = map.subMap(two, true, three, false);
assertEquals(1, sm.size());
assertEquals(two, sm.firstKey());
assertEquals(two, sm.lastKey());
assertFalse(sm.containsKey(one));
assertTrue(sm.containsKey(two));
assertFalse(sm.containsKey(three));
assertFalse(sm.containsKey(four));
assertFalse(sm.containsKey(five));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
assertFalse(i.hasNext());
Iterator r = sm.descendingKeySet().iterator();
k = (Integer)(r.next());
assertEquals(two, k);
assertFalse(r.hasNext());
Iterator j = sm.keySet().iterator();
j.next();
j.remove();
assertFalse(map.containsKey(two));
assertEquals(4, map.size());
assertEquals(0, sm.size());
assertTrue(sm.isEmpty());
assertTrue(sm.remove(three) == null);
assertEquals(4, map.size());
}
/**
* headMap returns map with keys in requested range
*/
public void testHeadMapContents() {
ConcurrentSkipListMap map = map5();
NavigableMap sm = map.headMap(four, false);
assertTrue(sm.containsKey(one));
assertTrue(sm.containsKey(two));
assertTrue(sm.containsKey(three));
assertFalse(sm.containsKey(four));
assertFalse(sm.containsKey(five));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(one, k);
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
assertFalse(i.hasNext());
sm.clear();
assertTrue(sm.isEmpty());
assertEquals(2, map.size());
assertEquals(four, map.firstKey());
}
/**
* tailMap returns map with keys in requested range
*/
public void testTailMapContents() {
ConcurrentSkipListMap map = map5();
NavigableMap sm = map.tailMap(two, true);
assertFalse(sm.containsKey(one));
assertTrue(sm.containsKey(two));
assertTrue(sm.containsKey(three));
assertTrue(sm.containsKey(four));
assertTrue(sm.containsKey(five));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
k = (Integer)(i.next());
assertEquals(four, k);
k = (Integer)(i.next());
assertEquals(five, k);
assertFalse(i.hasNext());
Iterator r = sm.descendingKeySet().iterator();
k = (Integer)(r.next());
assertEquals(five, k);
k = (Integer)(r.next());
assertEquals(four, k);
k = (Integer)(r.next());
assertEquals(three, k);
k = (Integer)(r.next());
assertEquals(two, k);
assertFalse(r.hasNext());
Iterator ei = sm.entrySet().iterator();
Map.Entry e;
e = (Map.Entry)(ei.next());
assertEquals(two, e.getKey());
assertEquals("B", e.getValue());
e = (Map.Entry)(ei.next());
assertEquals(three, e.getKey());
assertEquals("C", e.getValue());
e = (Map.Entry)(ei.next());
assertEquals(four, e.getKey());
assertEquals("D", e.getValue());
e = (Map.Entry)(ei.next());
assertEquals(five, e.getKey());
assertEquals("E", e.getValue());
assertFalse(i.hasNext());
NavigableMap ssm = sm.tailMap(four, true);
assertEquals(four, ssm.firstKey());
assertEquals(five, ssm.lastKey());
assertTrue(ssm.remove(four) != null);
assertEquals(1, ssm.size());
assertEquals(3, sm.size());
assertEquals(4, map.size());
}
Random rnd = new Random(666);
BitSet bs;
/**
* Submaps of submaps subdivide correctly
*/
public void testRecursiveSubMaps() {
int mapSize = 1000;
Class cl = ConcurrentSkipListMap.class;
NavigableMap map = newMap(cl);
bs = new BitSet(mapSize);
populate(map, mapSize);
check(map, 0, mapSize - 1, true);
check(map.descendingMap(), 0, mapSize - 1, false);
mutateMap(map, 0, mapSize - 1);
check(map, 0, mapSize - 1, true);
check(map.descendingMap(), 0, mapSize - 1, false);
bashSubMap(map.subMap(new Integer(0), true, new Integer(mapSize), false),
0, mapSize - 1, true);
}
static NavigableMap newMap(Class cl) {
NavigableMap result = null;
try {
result = (NavigableMap) cl.newInstance();
} catch(Exception e) {
fail();
}
assertEquals(result.size(), 0);
assertFalse(result.keySet().iterator().hasNext());
return result;
}
void populate(NavigableMap map, int limit) {
for (int i = 0, n = 2 * limit / 3; i < n; i++) {
int key = rnd.nextInt(limit);
put(map, key);
}
}
void mutateMap(NavigableMap map, int min, int max) {
int size = map.size();
int rangeSize = max - min + 1;
// Remove a bunch of entries directly
for (int i = 0, n = rangeSize / 2; i < n; i++) {
remove(map, min - 5 + rnd.nextInt(rangeSize + 10));
}
// Remove a bunch of entries with iterator
for(Iterator it = map.keySet().iterator(); it.hasNext(); ) {
if (rnd.nextBoolean()) {
bs.clear(((Integer)it.next()).intValue());
it.remove();
}
}
// Add entries till we're back to original size
while (map.size() < size) {
int key = min + rnd.nextInt(rangeSize);
assertTrue(key >= min && key<= max);
put(map, key);
}
}
void mutateSubMap(NavigableMap map, int min, int max) {
int size = map.size();
int rangeSize = max - min + 1;
// Remove a bunch of entries directly
for (int i = 0, n = rangeSize / 2; i < n; i++) {
remove(map, min - 5 + rnd.nextInt(rangeSize + 10));
}
// Remove a bunch of entries with iterator
for(Iterator it = map.keySet().iterator(); it.hasNext(); ) {
if (rnd.nextBoolean()) {
bs.clear(((Integer)it.next()).intValue());
it.remove();
}
}
// Add entries till we're back to original size
while (map.size() < size) {
int key = min - 5 + rnd.nextInt(rangeSize + 10);
if (key >= min && key<= max) {
put(map, key);
} else {
try {
map.put(new Integer(key), new Integer(2 * key));
fail();
} catch(IllegalArgumentException e) {
// expected
}
}
}
}
void put(NavigableMap map, int key) {
if (map.put(new Integer(key), new Integer(2 * key)) == null)
bs.set(key);
}
void remove(NavigableMap map, int key) {
if (map.remove(new Integer(key)) != null)
bs.clear(key);
}
void bashSubMap(NavigableMap map,
int min, int max, boolean ascending) {
check(map, min, max, ascending);
check(map.descendingMap(), min, max, !ascending);
mutateSubMap(map, min, max);
check(map, min, max, ascending);
check(map.descendingMap(), min, max, !ascending);
// Recurse
if (max - min < 2)
return;
int midPoint = (min + max) / 2;
// headMap - pick direction and endpoint inclusion randomly
boolean incl = rnd.nextBoolean();
NavigableMap hm = map.headMap(new Integer(midPoint), incl);
if (ascending) {
if (rnd.nextBoolean())
bashSubMap(hm, min, midPoint - (incl ? 0 : 1), true);
else
bashSubMap(hm.descendingMap(), min, midPoint - (incl ? 0 : 1),
false);
} else {
if (rnd.nextBoolean())
bashSubMap(hm, midPoint + (incl ? 0 : 1), max, false);
else
bashSubMap(hm.descendingMap(), midPoint + (incl ? 0 : 1), max,
true);
}
// tailMap - pick direction and endpoint inclusion randomly
incl = rnd.nextBoolean();
NavigableMap tm = map.tailMap(new Integer(midPoint),incl);
if (ascending) {
if (rnd.nextBoolean())
bashSubMap(tm, midPoint + (incl ? 0 : 1), max, true);
else
bashSubMap(tm.descendingMap(), midPoint + (incl ? 0 : 1), max,
false);
} else {
if (rnd.nextBoolean()) {
bashSubMap(tm, min, midPoint - (incl ? 0 : 1), false);
} else {
bashSubMap(tm.descendingMap(), min, midPoint - (incl ? 0 : 1),
true);
}
}
// subMap - pick direction and endpoint inclusion randomly
int rangeSize = max - min + 1;
int[] endpoints = new int[2];
endpoints[0] = min + rnd.nextInt(rangeSize);
endpoints[1] = min + rnd.nextInt(rangeSize);
Arrays.sort(endpoints);
boolean lowIncl = rnd.nextBoolean();
boolean highIncl = rnd.nextBoolean();
if (ascending) {
NavigableMap sm = map.subMap(
new Integer(endpoints[0]), lowIncl, new Integer(endpoints[1]), highIncl);
if (rnd.nextBoolean())
bashSubMap(sm, endpoints[0] + (lowIncl ? 0 : 1),
endpoints[1] - (highIncl ? 0 : 1), true);
else
bashSubMap(sm.descendingMap(), endpoints[0] + (lowIncl ? 0 : 1),
endpoints[1] - (highIncl ? 0 : 1), false);
} else {
NavigableMap sm = map.subMap(
new Integer(endpoints[1]), highIncl, new Integer(endpoints[0]), lowIncl);
if (rnd.nextBoolean())
bashSubMap(sm, endpoints[0] + (lowIncl ? 0 : 1),
endpoints[1] - (highIncl ? 0 : 1), false);
else
bashSubMap(sm.descendingMap(), endpoints[0] + (lowIncl ? 0 : 1),
endpoints[1] - (highIncl ? 0 : 1), true);
}
}
/**
* min and max are both inclusive. If max < min, interval is empty.
*/
void check(NavigableMap map,
final int min, final int max, final boolean ascending) {
class ReferenceSet {
int lower(int key) {
return ascending ? lowerAscending(key) : higherAscending(key);
}
int floor(int key) {
return ascending ? floorAscending(key) : ceilingAscending(key);
}
int ceiling(int key) {
return ascending ? ceilingAscending(key) : floorAscending(key);
}
int higher(int key) {
return ascending ? higherAscending(key) : lowerAscending(key);
}
int first() {
return ascending ? firstAscending() : lastAscending();
}
int last() {
return ascending ? lastAscending() : firstAscending();
}
int lowerAscending(int key) {
return floorAscending(key - 1);
}
int floorAscending(int key) {
if (key < min)
return -1;
else if (key > max)
key = max;
// BitSet should support this! Test would run much faster
while (key >= min) {
if (bs.get(key))
return(key);
key--;
}
return -1;
}
int ceilingAscending(int key) {
if (key < min)
key = min;
else if (key > max)
return -1;
int result = bs.nextSetBit(key);
return result > max ? -1 : result;
}
int higherAscending(int key) {
return ceilingAscending(key + 1);
}
private int firstAscending() {
int result = ceilingAscending(min);
return result > max ? -1 : result;
}
private int lastAscending() {
int result = floorAscending(max);
return result < min ? -1 : result;
}
}
ReferenceSet rs = new ReferenceSet();
// Test contents using containsKey
int size = 0;
for (int i = min; i <= max; i++) {
boolean bsContainsI = bs.get(i);
assertEquals(bsContainsI, map.containsKey(new Integer(i)));
if (bsContainsI)
size++;
}
assertEquals(map.size(), size);
// Test contents using contains keySet iterator
int size2 = 0;
int previousKey = -1;
for (Iterator itr = map.keySet().iterator(); itr.hasNext();) {
int key = ((Integer)itr.next()).intValue();
assertTrue(bs.get(key));
size2++;
assertTrue(previousKey < 0 ||
(ascending ? key - previousKey > 0 : key - previousKey < 0));
previousKey = key;
}
assertEquals(size2, size);
// Test navigation ops
for (int key = min - 1; key <= max + 1; key++) {
assertEq((Integer)map.lowerKey(new Integer(key)), rs.lower(key));
assertEq((Integer)map.floorKey(new Integer(key)), rs.floor(key));
assertEq((Integer)map.higherKey(new Integer(key)), rs.higher(key));
assertEq((Integer)map.ceilingKey(new Integer(key)), rs.ceiling(key));
}
// Test extrema
if (map.size() != 0) {
assertEq((Integer)map.firstKey(), rs.first());
assertEq((Integer)map.lastKey(), rs.last());
} else {
assertEq(new Integer(rs.first()), -1);
assertEq(new Integer(rs.last()), -1);
try {
map.firstKey();
fail();
} catch(NoSuchElementException e) {
// expected
}
try {
map.lastKey();
fail();
} catch(NoSuchElementException e) {
// expected
}
}
}
static void assertEq(Integer i, int j) {
if (i == null)
assertEquals(j, -1);
else
assertEquals(i.intValue(), j);
}
static boolean eq(Integer i, int j) {
return i == null ? j == -1 : i.intValue() == j;
}
}
backport-util-concurrent-3.1-src/test/tck/src/TreeSubMapTest.java 0000644 0017507 0003772 00000100021 10431777323 023750 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.io.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.ArrayList;
public class TreeSubMapTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(TreeSubMapTest.class);
}
/**
* Create a map from Integers 1-5 to Strings "A"-"E".
*/
private static NavigableMap map5() {
TreeMap map = new TreeMap();
assertTrue(map.isEmpty());
map.put(zero, "Z");
map.put(one, "A");
map.put(five, "E");
map.put(three, "C");
map.put(two, "B");
map.put(four, "D");
map.put(seven, "F");
assertFalse(map.isEmpty());
assertEquals(7, map.size());
return map.subMap(one, true, seven, false);
}
private static NavigableMap map0() {
TreeMap map = new TreeMap();
assertTrue(map.isEmpty());
return map.tailMap(one, true);
}
/**
* Create a map from Integers -5 to -1 to Strings "A"-"E".
*/
private static NavigableMap dmap5() {
TreeMap map = new TreeMap();
assertTrue(map.isEmpty());
map.put(m1, "A");
map.put(m5, "E");
map.put(m3, "C");
map.put(m2, "B");
map.put(m4, "D");
assertFalse(map.isEmpty());
assertEquals(5, map.size());
return map.descendingMap();
}
private static NavigableMap dmap0() {
TreeMap map = new TreeMap();
assertTrue(map.isEmpty());
return map;
}
/**
* clear removes all pairs
*/
public void testClear() {
NavigableMap map = map5();
map.clear();
assertEquals(map.size(), 0);
}
/**
* Maps with same contents are equal
*/
public void testEquals() {
NavigableMap map1 = map5();
NavigableMap map2 = map5();
assertEquals(map1, map2);
assertEquals(map2, map1);
map1.clear();
assertFalse(map1.equals(map2));
assertFalse(map2.equals(map1));
}
/**
* containsKey returns true for contained key
*/
public void testContainsKey() {
NavigableMap map = map5();
assertTrue(map.containsKey(one));
assertFalse(map.containsKey(zero));
}
/**
* containsValue returns true for held values
*/
public void testContainsValue() {
NavigableMap map = map5();
assertTrue(map.containsValue("A"));
assertFalse(map.containsValue("Z"));
}
/**
* get returns the correct element at the given key,
* or null if not present
*/
public void testGet() {
NavigableMap map = map5();
assertEquals("A", (String)map.get(one));
NavigableMap empty = map0();
assertNull(empty.get(one));
}
/**
* isEmpty is true of empty map and false for non-empty
*/
public void testIsEmpty() {
NavigableMap empty = map0();
NavigableMap map = map5();
assertTrue(empty.isEmpty());
assertFalse(map.isEmpty());
}
/**
* firstKey returns first key
*/
public void testFirstKey() {
NavigableMap map = map5();
assertEquals(one, map.firstKey());
}
/**
* lastKey returns last key
*/
public void testLastKey() {
NavigableMap map = map5();
assertEquals(five, map.lastKey());
}
/**
* keySet returns a Set containing all the keys
*/
public void testKeySet() {
NavigableMap map = map5();
Set s = map.keySet();
assertEquals(5, s.size());
assertTrue(s.contains(one));
assertTrue(s.contains(two));
assertTrue(s.contains(three));
assertTrue(s.contains(four));
assertTrue(s.contains(five));
}
/**
* keySet is ordered
*/
public void testKeySetOrder() {
NavigableMap map = map5();
Set s = map.keySet();
Iterator i = s.iterator();
Integer last = (Integer)i.next();
assertEquals(last, one);
while (i.hasNext()) {
Integer k = (Integer)i.next();
assertTrue(last.compareTo(k) < 0);
last = k;
}
}
/**
* values collection contains all values
*/
public void testValues() {
NavigableMap map = map5();
Collection s = map.values();
assertEquals(5, s.size());
assertTrue(s.contains("A"));
assertTrue(s.contains("B"));
assertTrue(s.contains("C"));
assertTrue(s.contains("D"));
assertTrue(s.contains("E"));
}
/**
* entrySet contains all pairs
*/
public void testEntrySet() {
NavigableMap map = map5();
Set s = map.entrySet();
assertEquals(5, s.size());
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
assertTrue(
(e.getKey().equals(one) && e.getValue().equals("A")) ||
(e.getKey().equals(two) && e.getValue().equals("B")) ||
(e.getKey().equals(three) && e.getValue().equals("C")) ||
(e.getKey().equals(four) && e.getValue().equals("D")) ||
(e.getKey().equals(five) && e.getValue().equals("E")));
}
}
/**
* putAll adds all key-value pairs from the given map
*/
public void testPutAll() {
NavigableMap empty = map0();
NavigableMap map = map5();
empty.putAll(map);
assertEquals(5, empty.size());
assertTrue(empty.containsKey(one));
assertTrue(empty.containsKey(two));
assertTrue(empty.containsKey(three));
assertTrue(empty.containsKey(four));
assertTrue(empty.containsKey(five));
}
/**
* remove removes the correct key-value pair from the map
*/
public void testRemove() {
NavigableMap map = map5();
map.remove(five);
assertEquals(4, map.size());
assertFalse(map.containsKey(five));
}
/**
* lowerEntry returns preceding entry.
*/
public void testLowerEntry() {
NavigableMap map = map5();
Map.Entry e1 = map.lowerEntry(three);
assertEquals(two, e1.getKey());
Map.Entry e2 = map.lowerEntry(six);
assertEquals(five, e2.getKey());
Map.Entry e3 = map.lowerEntry(one);
assertNull(e3);
Map.Entry e4 = map.lowerEntry(zero);
assertNull(e4);
}
/**
* higherEntry returns next entry.
*/
public void testHigherEntry() {
NavigableMap map = map5();
Map.Entry e1 = map.higherEntry(three);
assertEquals(four, e1.getKey());
Map.Entry e2 = map.higherEntry(zero);
assertEquals(one, e2.getKey());
Map.Entry e3 = map.higherEntry(five);
assertNull(e3);
Map.Entry e4 = map.higherEntry(six);
assertNull(e4);
}
/**
* floorEntry returns preceding entry.
*/
public void testFloorEntry() {
NavigableMap map = map5();
Map.Entry e1 = map.floorEntry(three);
assertEquals(three, e1.getKey());
Map.Entry e2 = map.floorEntry(six);
assertEquals(five, e2.getKey());
Map.Entry e3 = map.floorEntry(one);
assertEquals(one, e3.getKey());
Map.Entry e4 = map.floorEntry(zero);
assertNull(e4);
}
/**
* ceilingEntry returns next entry.
*/
public void testCeilingEntry() {
NavigableMap map = map5();
Map.Entry e1 = map.ceilingEntry(three);
assertEquals(three, e1.getKey());
Map.Entry e2 = map.ceilingEntry(zero);
assertEquals(one, e2.getKey());
Map.Entry e3 = map.ceilingEntry(five);
assertEquals(five, e3.getKey());
Map.Entry e4 = map.ceilingEntry(six);
assertNull(e4);
}
/**
* pollFirstEntry returns entries in order
*/
public void testPollFirstEntry() {
NavigableMap map = map5();
Map.Entry e = map.pollFirstEntry();
assertEquals(one, e.getKey());
assertEquals("A", e.getValue());
e = map.pollFirstEntry();
assertEquals(two, e.getKey());
map.put(one, "A");
e = map.pollFirstEntry();
assertEquals(one, e.getKey());
assertEquals("A", e.getValue());
e = map.pollFirstEntry();
assertEquals(three, e.getKey());
map.remove(four);
e = map.pollFirstEntry();
assertEquals(five, e.getKey());
try {
e.setValue("A");
shouldThrow();
} catch (Exception ok) {
}
assertTrue(map.isEmpty());
Map.Entry f = map.firstEntry();
assertNull(f);
e = map.pollFirstEntry();
assertNull(e);
}
/**
* pollLastEntry returns entries in order
*/
public void testPollLastEntry() {
NavigableMap map = map5();
Map.Entry e = map.pollLastEntry();
assertEquals(five, e.getKey());
assertEquals("E", e.getValue());
e = map.pollLastEntry();
assertEquals(four, e.getKey());
map.put(five, "E");
e = map.pollLastEntry();
assertEquals(five, e.getKey());
assertEquals("E", e.getValue());
e = map.pollLastEntry();
assertEquals(three, e.getKey());
map.remove(two);
e = map.pollLastEntry();
assertEquals(one, e.getKey());
try {
e.setValue("E");
shouldThrow();
} catch (Exception ok) {
}
e = map.pollLastEntry();
assertNull(e);
}
/**
* size returns the correct values
*/
public void testSize() {
NavigableMap map = map5();
NavigableMap empty = map0();
assertEquals(0, empty.size());
assertEquals(5, map.size());
}
/**
* toString contains toString of elements
*/
public void testToString() {
NavigableMap map = map5();
String s = map.toString();
for (int i = 1; i <= 5; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
// Exception tests
/**
* get(null) of nonempty map throws NPE
*/
public void testGet_NullPointerException() {
try {
NavigableMap c = map5();
c.get(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* containsKey(null) of nonempty map throws NPE
*/
public void testContainsKey_NullPointerException() {
try {
NavigableMap c = map5();
c.containsKey(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* put(null,x) throws NPE
*/
public void testPut1_NullPointerException() {
try {
NavigableMap c = map5();
c.put(null, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* remove(null) throws NPE
*/
public void testRemove1_NullPointerException() {
try {
NavigableMap c = map5();
c.remove(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* A deserialized map equals original
*/
public void testSerialization() {
NavigableMap q = map5();
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
NavigableMap r = (NavigableMap)in.readObject();
assertFalse(r.isEmpty());
assertEquals(q.size(), r.size());
assertTrue(q.equals(r));
assertTrue(r.equals(q));
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* subMap returns map with keys in requested range
*/
public void testSubMapContents() {
NavigableMap map = map5();
SortedMap sm = map.subMap(two, four);
assertEquals(two, sm.firstKey());
assertEquals(three, sm.lastKey());
assertEquals(2, sm.size());
assertFalse(sm.containsKey(one));
assertTrue(sm.containsKey(two));
assertTrue(sm.containsKey(three));
assertFalse(sm.containsKey(four));
assertFalse(sm.containsKey(five));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
assertFalse(i.hasNext());
Iterator j = sm.keySet().iterator();
j.next();
j.remove();
assertFalse(map.containsKey(two));
assertEquals(4, map.size());
assertEquals(1, sm.size());
assertEquals(three, sm.firstKey());
assertEquals(three, sm.lastKey());
assertTrue(sm.remove(three) != null);
assertTrue(sm.isEmpty());
assertEquals(3, map.size());
}
public void testSubMapContents2() {
NavigableMap map = map5();
SortedMap sm = map.subMap(two, three);
assertEquals(1, sm.size());
assertEquals(two, sm.firstKey());
assertEquals(two, sm.lastKey());
assertFalse(sm.containsKey(one));
assertTrue(sm.containsKey(two));
assertFalse(sm.containsKey(three));
assertFalse(sm.containsKey(four));
assertFalse(sm.containsKey(five));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
assertFalse(i.hasNext());
Iterator j = sm.keySet().iterator();
j.next();
j.remove();
assertFalse(map.containsKey(two));
assertEquals(4, map.size());
assertEquals(0, sm.size());
assertTrue(sm.isEmpty());
assertTrue(sm.remove(three) == null);
assertEquals(4, map.size());
}
/**
* headMap returns map with keys in requested range
*/
public void testHeadMapContents() {
NavigableMap map = map5();
SortedMap sm = map.headMap(four);
assertTrue(sm.containsKey(one));
assertTrue(sm.containsKey(two));
assertTrue(sm.containsKey(three));
assertFalse(sm.containsKey(four));
assertFalse(sm.containsKey(five));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(one, k);
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
assertFalse(i.hasNext());
sm.clear();
assertTrue(sm.isEmpty());
assertEquals(2, map.size());
assertEquals(four, map.firstKey());
}
/**
* headMap returns map with keys in requested range
*/
public void testTailMapContents() {
NavigableMap map = map5();
SortedMap sm = map.tailMap(two);
assertFalse(sm.containsKey(one));
assertTrue(sm.containsKey(two));
assertTrue(sm.containsKey(three));
assertTrue(sm.containsKey(four));
assertTrue(sm.containsKey(five));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
k = (Integer)(i.next());
assertEquals(four, k);
k = (Integer)(i.next());
assertEquals(five, k);
assertFalse(i.hasNext());
Iterator ei = sm.entrySet().iterator();
Map.Entry e;
e = (Map.Entry)(ei.next());
assertEquals(two, e.getKey());
assertEquals("B", e.getValue());
e = (Map.Entry)(ei.next());
assertEquals(three, e.getKey());
assertEquals("C", e.getValue());
e = (Map.Entry)(ei.next());
assertEquals(four, e.getKey());
assertEquals("D", e.getValue());
e = (Map.Entry)(ei.next());
assertEquals(five, e.getKey());
assertEquals("E", e.getValue());
assertFalse(i.hasNext());
SortedMap ssm = sm.tailMap(four);
assertEquals(four, ssm.firstKey());
assertEquals(five, ssm.lastKey());
assertTrue(ssm.remove(four) != null);
assertEquals(1, ssm.size());
assertEquals(3, sm.size());
assertEquals(4, map.size());
}
/**
* clear removes all pairs
*/
public void testDescendingClear() {
NavigableMap map = dmap5();
map.clear();
assertEquals(map.size(), 0);
}
/**
* Maps with same contents are equal
*/
public void testDescendingEquals() {
NavigableMap map1 = dmap5();
NavigableMap map2 = dmap5();
assertEquals(map1, map2);
assertEquals(map2, map1);
map1.clear();
assertFalse(map1.equals(map2));
assertFalse(map2.equals(map1));
}
/**
* containsKey returns true for contained key
*/
public void testDescendingContainsKey() {
NavigableMap map = dmap5();
assertTrue(map.containsKey(m1));
assertFalse(map.containsKey(zero));
}
/**
* containsValue returns true for held values
*/
public void testDescendingContainsValue() {
NavigableMap map = dmap5();
assertTrue(map.containsValue("A"));
assertFalse(map.containsValue("Z"));
}
/**
* get returns the correct element at the given key,
* or null if not present
*/
public void testDescendingGet() {
NavigableMap map = dmap5();
assertEquals("A", (String)map.get(m1));
NavigableMap empty = dmap0();
assertNull(empty.get(m1));
}
/**
* isEmpty is true of empty map and false for non-empty
*/
public void testDescendingIsEmpty() {
NavigableMap empty = dmap0();
NavigableMap map = dmap5();
assertTrue(empty.isEmpty());
assertFalse(map.isEmpty());
}
/**
* firstKey returns first key
*/
public void testDescendingFirstKey() {
NavigableMap map = dmap5();
assertEquals(m1, map.firstKey());
}
/**
* lastKey returns last key
*/
public void testDescendingLastKey() {
NavigableMap map = dmap5();
assertEquals(m5, map.lastKey());
}
/**
* keySet returns a Set containing all the keys
*/
public void testDescendingKeySet() {
NavigableMap map = dmap5();
Set s = map.keySet();
assertEquals(5, s.size());
assertTrue(s.contains(m1));
assertTrue(s.contains(m2));
assertTrue(s.contains(m3));
assertTrue(s.contains(m4));
assertTrue(s.contains(m5));
}
/**
* keySet is ordered
*/
public void testDescendingKeySetOrder() {
NavigableMap map = dmap5();
Set s = map.keySet();
Iterator i = s.iterator();
Integer last = (Integer)i.next();
assertEquals(last, m1);
while (i.hasNext()) {
Integer k = (Integer)i.next();
assertTrue(last.compareTo(k) > 0);
last = k;
}
}
/**
* values collection contains all values
*/
public void testDescendingValues() {
NavigableMap map = dmap5();
Collection s = map.values();
assertEquals(5, s.size());
assertTrue(s.contains("A"));
assertTrue(s.contains("B"));
assertTrue(s.contains("C"));
assertTrue(s.contains("D"));
assertTrue(s.contains("E"));
}
/**
* keySet.toArray returns contains all keys
*/
public void testDescendingAscendingKeySetToArray() {
NavigableMap map = dmap5();
Set s = map.keySet();
Object[] ar = s.toArray();
assertTrue(s.containsAll(Arrays.asList(ar)));
assertEquals(5, ar.length);
ar[0] = m10;
assertFalse(s.containsAll(Arrays.asList(ar)));
}
/**
* descendingkeySet.toArray returns contains all keys
*/
public void testDescendingDescendingKeySetToArray() {
NavigableMap map = dmap5();
Set s = map.descendingKeySet();
Object[] ar = s.toArray();
assertEquals(5, ar.length);
assertTrue(s.containsAll(Arrays.asList(ar)));
ar[0] = m10;
assertFalse(s.containsAll(Arrays.asList(ar)));
}
/**
* Values.toArray contains all values
*/
public void testDescendingValuesToArray() {
NavigableMap map = dmap5();
Collection v = map.values();
Object[] ar = v.toArray();
ArrayList s = new ArrayList(Arrays.asList(ar));
assertEquals(5, ar.length);
assertTrue(s.contains("A"));
assertTrue(s.contains("B"));
assertTrue(s.contains("C"));
assertTrue(s.contains("D"));
assertTrue(s.contains("E"));
}
/**
* entrySet contains all pairs
*/
public void testDescendingEntrySet() {
NavigableMap map = dmap5();
Set s = map.entrySet();
assertEquals(5, s.size());
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
assertTrue(
(e.getKey().equals(m1) && e.getValue().equals("A")) ||
(e.getKey().equals(m2) && e.getValue().equals("B")) ||
(e.getKey().equals(m3) && e.getValue().equals("C")) ||
(e.getKey().equals(m4) && e.getValue().equals("D")) ||
(e.getKey().equals(m5) && e.getValue().equals("E")));
}
}
/**
* putAll adds all key-value pairs from the given map
*/
public void testDescendingPutAll() {
NavigableMap empty = dmap0();
NavigableMap map = dmap5();
empty.putAll(map);
assertEquals(5, empty.size());
assertTrue(empty.containsKey(m1));
assertTrue(empty.containsKey(m2));
assertTrue(empty.containsKey(m3));
assertTrue(empty.containsKey(m4));
assertTrue(empty.containsKey(m5));
}
/**
* remove removes the correct key-value pair from the map
*/
public void testDescendingRemove() {
NavigableMap map = dmap5();
map.remove(m5);
assertEquals(4, map.size());
assertFalse(map.containsKey(m5));
}
/**
* lowerEntry returns preceding entry.
*/
public void testDescendingLowerEntry() {
NavigableMap map = dmap5();
Map.Entry e1 = map.lowerEntry(m3);
assertEquals(m2, e1.getKey());
Map.Entry e2 = map.lowerEntry(m6);
assertEquals(m5, e2.getKey());
Map.Entry e3 = map.lowerEntry(m1);
assertNull(e3);
Map.Entry e4 = map.lowerEntry(zero);
assertNull(e4);
}
/**
* higherEntry returns next entry.
*/
public void testDescendingHigherEntry() {
NavigableMap map = dmap5();
Map.Entry e1 = map.higherEntry(m3);
assertEquals(m4, e1.getKey());
Map.Entry e2 = map.higherEntry(zero);
assertEquals(m1, e2.getKey());
Map.Entry e3 = map.higherEntry(m5);
assertNull(e3);
Map.Entry e4 = map.higherEntry(m6);
assertNull(e4);
}
/**
* floorEntry returns preceding entry.
*/
public void testDescendingFloorEntry() {
NavigableMap map = dmap5();
Map.Entry e1 = map.floorEntry(m3);
assertEquals(m3, e1.getKey());
Map.Entry e2 = map.floorEntry(m6);
assertEquals(m5, e2.getKey());
Map.Entry e3 = map.floorEntry(m1);
assertEquals(m1, e3.getKey());
Map.Entry e4 = map.floorEntry(zero);
assertNull(e4);
}
/**
* ceilingEntry returns next entry.
*/
public void testDescendingCeilingEntry() {
NavigableMap map = dmap5();
Map.Entry e1 = map.ceilingEntry(m3);
assertEquals(m3, e1.getKey());
Map.Entry e2 = map.ceilingEntry(zero);
assertEquals(m1, e2.getKey());
Map.Entry e3 = map.ceilingEntry(m5);
assertEquals(m5, e3.getKey());
Map.Entry e4 = map.ceilingEntry(m6);
assertNull(e4);
}
/**
* pollFirstEntry returns entries in order
*/
public void testDescendingPollFirstEntry() {
NavigableMap map = dmap5();
Map.Entry e = map.pollFirstEntry();
assertEquals(m1, e.getKey());
assertEquals("A", e.getValue());
e = map.pollFirstEntry();
assertEquals(m2, e.getKey());
map.put(m1, "A");
e = map.pollFirstEntry();
assertEquals(m1, e.getKey());
assertEquals("A", e.getValue());
e = map.pollFirstEntry();
assertEquals(m3, e.getKey());
map.remove(m4);
e = map.pollFirstEntry();
assertEquals(m5, e.getKey());
try {
e.setValue("A");
shouldThrow();
} catch (Exception ok) {
}
e = map.pollFirstEntry();
assertNull(e);
}
/**
* pollLastEntry returns entries in order
*/
public void testDescendingPollLastEntry() {
NavigableMap map = dmap5();
Map.Entry e = map.pollLastEntry();
assertEquals(m5, e.getKey());
assertEquals("E", e.getValue());
e = map.pollLastEntry();
assertEquals(m4, e.getKey());
map.put(m5, "E");
e = map.pollLastEntry();
assertEquals(m5, e.getKey());
assertEquals("E", e.getValue());
e = map.pollLastEntry();
assertEquals(m3, e.getKey());
map.remove(m2);
e = map.pollLastEntry();
assertEquals(m1, e.getKey());
try {
e.setValue("E");
shouldThrow();
} catch (Exception ok) {
}
e = map.pollLastEntry();
assertNull(e);
}
/**
* size returns the correct values
*/
public void testDescendingSize() {
NavigableMap map = dmap5();
NavigableMap empty = dmap0();
assertEquals(0, empty.size());
assertEquals(5, map.size());
}
/**
* toString contains toString of elements
*/
public void testDescendingToString() {
NavigableMap map = dmap5();
String s = map.toString();
for (int i = 1; i <= 5; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
// Exception testDescendings
/**
* get(null) of nonempty map throws NPE
*/
public void testDescendingGet_NullPointerException() {
try {
NavigableMap c = dmap5();
c.get(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* put(null,x) throws NPE
*/
public void testDescendingPut1_NullPointerException() {
try {
NavigableMap c = dmap5();
c.put(null, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* A deserialized map equals original
*/
public void testDescendingSerialization() {
NavigableMap q = dmap5();
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
NavigableMap r = (NavigableMap)in.readObject();
assertEquals(q.size(), r.size());
assertTrue(q.equals(r));
assertTrue(r.equals(q));
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* subMap returns map with keys in requested range
*/
public void testDescendingSubMapContents() {
NavigableMap map = dmap5();
SortedMap sm = map.subMap(m2, m4);
assertEquals(m2, sm.firstKey());
assertEquals(m3, sm.lastKey());
assertEquals(2, sm.size());
assertFalse(sm.containsKey(m1));
assertTrue(sm.containsKey(m2));
assertTrue(sm.containsKey(m3));
assertFalse(sm.containsKey(m4));
assertFalse(sm.containsKey(m5));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(m2, k);
k = (Integer)(i.next());
assertEquals(m3, k);
assertFalse(i.hasNext());
Iterator j = sm.keySet().iterator();
j.next();
j.remove();
assertFalse(map.containsKey(m2));
assertEquals(4, map.size());
assertEquals(1, sm.size());
assertEquals(m3, sm.firstKey());
assertEquals(m3, sm.lastKey());
assertTrue(sm.remove(m3) != null);
assertTrue(sm.isEmpty());
assertEquals(3, map.size());
}
public void testDescendingSubMapContents2() {
NavigableMap map = dmap5();
SortedMap sm = map.subMap(m2, m3);
assertEquals(1, sm.size());
assertEquals(m2, sm.firstKey());
assertEquals(m2, sm.lastKey());
assertFalse(sm.containsKey(m1));
assertTrue(sm.containsKey(m2));
assertFalse(sm.containsKey(m3));
assertFalse(sm.containsKey(m4));
assertFalse(sm.containsKey(m5));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(m2, k);
assertFalse(i.hasNext());
Iterator j = sm.keySet().iterator();
j.next();
j.remove();
assertFalse(map.containsKey(m2));
assertEquals(4, map.size());
assertEquals(0, sm.size());
assertTrue(sm.isEmpty());
assertTrue(sm.remove(m3) == null);
assertEquals(4, map.size());
}
/**
* headMap returns map with keys in requested range
*/
public void testDescendingHeadMapContents() {
NavigableMap map = dmap5();
SortedMap sm = map.headMap(m4);
assertTrue(sm.containsKey(m1));
assertTrue(sm.containsKey(m2));
assertTrue(sm.containsKey(m3));
assertFalse(sm.containsKey(m4));
assertFalse(sm.containsKey(m5));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(m1, k);
k = (Integer)(i.next());
assertEquals(m2, k);
k = (Integer)(i.next());
assertEquals(m3, k);
assertFalse(i.hasNext());
sm.clear();
assertTrue(sm.isEmpty());
assertEquals(2, map.size());
assertEquals(m4, map.firstKey());
}
/**
* headMap returns map with keys in requested range
*/
public void testDescendingTailMapContents() {
NavigableMap map = dmap5();
SortedMap sm = map.tailMap(m2);
assertFalse(sm.containsKey(m1));
assertTrue(sm.containsKey(m2));
assertTrue(sm.containsKey(m3));
assertTrue(sm.containsKey(m4));
assertTrue(sm.containsKey(m5));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(m2, k);
k = (Integer)(i.next());
assertEquals(m3, k);
k = (Integer)(i.next());
assertEquals(m4, k);
k = (Integer)(i.next());
assertEquals(m5, k);
assertFalse(i.hasNext());
Iterator ei = sm.entrySet().iterator();
Map.Entry e;
e = (Map.Entry)(ei.next());
assertEquals(m2, e.getKey());
assertEquals("B", e.getValue());
e = (Map.Entry)(ei.next());
assertEquals(m3, e.getKey());
assertEquals("C", e.getValue());
e = (Map.Entry)(ei.next());
assertEquals(m4, e.getKey());
assertEquals("D", e.getValue());
e = (Map.Entry)(ei.next());
assertEquals(m5, e.getKey());
assertEquals("E", e.getValue());
assertFalse(i.hasNext());
SortedMap ssm = sm.tailMap(m4);
assertEquals(m4, ssm.firstKey());
assertEquals(m5, ssm.lastKey());
assertTrue(ssm.remove(m4) != null);
assertEquals(1, ssm.size());
assertEquals(3, sm.size());
assertEquals(4, map.size());
}
}
backport-util-concurrent-3.1-src/test/tck/src/AbstractQueueTest.java 0000644 0017507 0003772 00000011325 10365510635 024516 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import java.io.*;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class AbstractQueueTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(AbstractQueueTest.class);
}
static class Succeed extends AbstractQueue {
public boolean offer(Object x) {
if (x == null) throw new NullPointerException();
return true;
}
public Object peek() { return one; }
public Object poll() { return one; }
public int size() { return 0; }
public Iterator iterator() { return null; } // not needed
}
static class Fail extends AbstractQueue {
public boolean offer(Object x) {
if (x == null) throw new NullPointerException();
return false;
}
public Object peek() { return null; }
public Object poll() { return null; }
public int size() { return 0; }
public Iterator iterator() { return null; } // not needed
}
/**
* add returns true if offer succeeds
*/
public void testAddS() {
Succeed q = new Succeed();
assertTrue(q.add(two));
}
/**
* add throws ISE true if offer fails
*/
public void testAddF() {
Fail q = new Fail();
try {
q.add(one);
shouldThrow();
} catch (IllegalStateException success) {
}
}
/**
* add throws NPE if offer does
*/
public void testAddNPE() {
Succeed q = new Succeed();
try {
q.add(null);
shouldThrow();
} catch (NullPointerException success) {
}
}
/**
* remove returns normally if poll succeeds
*/
public void testRemoveS() {
Succeed q = new Succeed();
q.remove();
}
/**
* remove throws NSEE if poll returns null
*/
public void testRemoveF() {
Fail q = new Fail();
try {
q.remove();
shouldThrow();
} catch (NoSuchElementException success) {
}
}
/**
* element returns normally if peek succeeds
*/
public void testElementS() {
Succeed q = new Succeed();
q.element();
}
/**
* element throws NSEE if peek returns null
*/
public void testElementF() {
Fail q = new Fail();
try {
q.element();
shouldThrow();
} catch (NoSuchElementException success) {
}
}
/**
* addAll(null) throws NPE
*/
public void testAddAll1() {
try {
Succeed q = new Succeed();
q.addAll(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll(this) throws IAE
*/
public void testAddAllSelf() {
try {
Succeed q = new Succeed();
q.addAll(q);
shouldThrow();
}
catch (IllegalArgumentException success) {}
}
/**
* addAll of a collection with null elements throws NPE
*/
public void testAddAll2() {
try {
Succeed q = new Succeed();
Integer[] ints = new Integer[SIZE];
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with any null elements throws NPE after
* possibly adding some elements
*/
public void testAddAll3() {
try {
Succeed q = new Succeed();
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll throws ISE if an add fails
*/
public void testAddAll4() {
try {
Fail q = new Fail();
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (IllegalStateException success) {}
}
}
backport-util-concurrent-3.1-src/test/tck/src/ReentrantLockTest.java 0000644 0017507 0003772 00000105142 10434507235 024521 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.helpers.Utils;
import java.io.*;
import java.util.Collection;
public class ReentrantLockTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(ReentrantLockTest.class);
}
/**
* A runnable calling lockInterruptibly
*/
class InterruptibleLockRunnable implements Runnable {
final ReentrantLock lock;
InterruptibleLockRunnable(ReentrantLock l) { lock = l; }
public void run() {
try {
lock.lockInterruptibly();
} catch(InterruptedException success){}
}
}
/**
* A runnable calling lockInterruptibly that expects to be
* interrupted
*/
class InterruptedLockRunnable implements Runnable {
final ReentrantLock lock;
InterruptedLockRunnable(ReentrantLock l) { lock = l; }
public void run() {
try {
lock.lockInterruptibly();
threadShouldThrow();
} catch(InterruptedException success){}
}
}
/**
* Subclass to expose protected methods
*/
static class PublicReentrantLock extends ReentrantLock {
PublicReentrantLock() { super(); }
PublicReentrantLock(boolean fair) { super(fair); }
public Collection getQueuedThreads() {
return super.getQueuedThreads();
}
public Collection getWaitingThreads(Condition c) {
return super.getWaitingThreads(c);
}
}
/**
* Constructor sets given fairness
*/
public void testConstructor() {
ReentrantLock rl = new ReentrantLock();
assertFalse(rl.isFair());
ReentrantLock r2 = new ReentrantLock(true);
assertTrue(r2.isFair());
}
/**
* locking an unlocked lock succeeds
*/
public void testLock() {
ReentrantLock rl = new ReentrantLock();
rl.lock();
assertTrue(rl.isLocked());
rl.unlock();
}
/**
* locking an unlocked fair lock succeeds
*/
public void testFairLock() {
ReentrantLock rl = new ReentrantLock(true);
rl.lock();
assertTrue(rl.isLocked());
rl.unlock();
}
/**
* Unlocking an unlocked lock throws IllegalMonitorStateException
*/
public void testUnlock_IllegalMonitorStateException() {
ReentrantLock rl = new ReentrantLock();
try {
rl.unlock();
shouldThrow();
} catch(IllegalMonitorStateException success){}
}
/**
* tryLock on an unlocked lock succeeds
*/
public void testTryLock() {
ReentrantLock rl = new ReentrantLock();
assertTrue(rl.tryLock());
assertTrue(rl.isLocked());
rl.unlock();
}
/**
* hasQueuedThreads reports whether there are waiting threads
*/
public void testhasQueuedThreads() {
final ReentrantLock lock = new ReentrantLock(true); // originally was non-fair
Thread t1 = new Thread(new InterruptedLockRunnable(lock));
Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
try {
assertFalse(lock.hasQueuedThreads());
lock.lock();
t1.start();
Thread.sleep(SHORT_DELAY_MS);
assertTrue(lock.hasQueuedThreads());
t2.start();
Thread.sleep(SHORT_DELAY_MS);
assertTrue(lock.hasQueuedThreads());
t1.interrupt();
Thread.sleep(SHORT_DELAY_MS);
assertTrue(lock.hasQueuedThreads());
lock.unlock();
Thread.sleep(SHORT_DELAY_MS);
assertFalse(lock.hasQueuedThreads());
t1.join();
t2.join();
} catch(Exception e){
unexpectedException();
}
}
/**
* getQueueLength reports number of waiting threads
*/
public void testGetQueueLength() {
final ReentrantLock lock = new ReentrantLock(true); // originally was non-fair
Thread t1 = new Thread(new InterruptedLockRunnable(lock));
Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
try {
assertEquals(0, lock.getQueueLength());
lock.lock();
t1.start();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(1, lock.getQueueLength());
t2.start();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(2, lock.getQueueLength());
t1.interrupt();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(1, lock.getQueueLength());
lock.unlock();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(0, lock.getQueueLength());
t1.join();
t2.join();
} catch(Exception e){
unexpectedException();
}
}
/**
* getQueueLength reports number of waiting threads
*/
public void testGetQueueLength_fair() {
final ReentrantLock lock = new ReentrantLock(true);
Thread t1 = new Thread(new InterruptedLockRunnable(lock));
Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
try {
assertEquals(0, lock.getQueueLength());
lock.lock();
t1.start();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(1, lock.getQueueLength());
t2.start();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(2, lock.getQueueLength());
t1.interrupt();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(1, lock.getQueueLength());
lock.unlock();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(0, lock.getQueueLength());
t1.join();
t2.join();
} catch(Exception e){
unexpectedException();
}
}
/**
* hasQueuedThread(null) throws NPE
*/
public void testHasQueuedThreadNPE() {
final ReentrantLock sync = new ReentrantLock(true); // originally was non-fair
try {
sync.hasQueuedThread(null);
shouldThrow();
} catch (NullPointerException success) {
}
}
/**
* hasQueuedThread reports whether a thread is queued.
*/
public void testHasQueuedThread() {
final ReentrantLock sync = new ReentrantLock(true); // originally was non-fair
Thread t1 = new Thread(new InterruptedLockRunnable(sync));
Thread t2 = new Thread(new InterruptibleLockRunnable(sync));
try {
assertFalse(sync.hasQueuedThread(t1));
assertFalse(sync.hasQueuedThread(t2));
sync.lock();
t1.start();
Thread.sleep(SHORT_DELAY_MS);
assertTrue(sync.hasQueuedThread(t1));
t2.start();
Thread.sleep(SHORT_DELAY_MS);
assertTrue(sync.hasQueuedThread(t1));
assertTrue(sync.hasQueuedThread(t2));
t1.interrupt();
Thread.sleep(SHORT_DELAY_MS);
assertFalse(sync.hasQueuedThread(t1));
assertTrue(sync.hasQueuedThread(t2));
sync.unlock();
Thread.sleep(SHORT_DELAY_MS);
assertFalse(sync.hasQueuedThread(t1));
Thread.sleep(SHORT_DELAY_MS);
assertFalse(sync.hasQueuedThread(t2));
t1.join();
t2.join();
} catch(Exception e){
unexpectedException();
}
}
/**
* getQueuedThreads includes waiting threads
*/
public void testGetQueuedThreads() {
final PublicReentrantLock lock = new PublicReentrantLock(true); // originally was non-fair
Thread t1 = new Thread(new InterruptedLockRunnable(lock));
Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
try {
assertTrue(lock.getQueuedThreads().isEmpty());
lock.lock();
assertTrue(lock.getQueuedThreads().isEmpty());
t1.start();
Thread.sleep(SHORT_DELAY_MS);
assertTrue(lock.getQueuedThreads().contains(t1));
t2.start();
Thread.sleep(SHORT_DELAY_MS);
assertTrue(lock.getQueuedThreads().contains(t1));
assertTrue(lock.getQueuedThreads().contains(t2));
t1.interrupt();
Thread.sleep(SHORT_DELAY_MS);
assertFalse(lock.getQueuedThreads().contains(t1));
assertTrue(lock.getQueuedThreads().contains(t2));
lock.unlock();
Thread.sleep(SHORT_DELAY_MS);
assertTrue(lock.getQueuedThreads().isEmpty());
t1.join();
t2.join();
} catch(Exception e){
unexpectedException();
}
}
/**
* timed tryLock is interruptible.
*/
public void testInterruptedException2() {
final ReentrantLock lock = new ReentrantLock();
lock.lock();
Thread t = new Thread(new Runnable() {
public void run() {
try {
lock.tryLock(MEDIUM_DELAY_MS,TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch(InterruptedException success){}
}
});
try {
t.start();
t.interrupt();
} catch(Exception e){
unexpectedException();
}
}
/**
* TryLock on a locked lock fails
*/
public void testTryLockWhenLocked() {
final ReentrantLock lock = new ReentrantLock();
lock.lock();
Thread t = new Thread(new Runnable() {
public void run() {
threadAssertFalse(lock.tryLock());
}
});
try {
t.start();
t.join();
lock.unlock();
} catch(Exception e){
unexpectedException();
}
}
/**
* Timed tryLock on a locked lock times out
*/
public void testTryLock_Timeout() {
final ReentrantLock lock = new ReentrantLock();
lock.lock();
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertFalse(lock.tryLock(1, TimeUnit.MILLISECONDS));
} catch (Exception ex) {
threadUnexpectedException();
}
}
});
try {
t.start();
t.join();
lock.unlock();
} catch(Exception e){
unexpectedException();
}
}
/**
* getHoldCount returns number of recursive holds
*/
public void testGetHoldCount() {
ReentrantLock lock = new ReentrantLock();
for(int i = 1; i <= SIZE; i++) {
lock.lock();
assertEquals(i,lock.getHoldCount());
}
for(int i = SIZE; i > 0; i--) {
lock.unlock();
assertEquals(i-1,lock.getHoldCount());
}
}
/**
* isLocked is true when locked and false when not
*/
public void testIsLocked() {
final ReentrantLock lock = new ReentrantLock();
lock.lock();
assertTrue(lock.isLocked());
lock.unlock();
assertFalse(lock.isLocked());
Thread t = new Thread(new Runnable() {
public void run() {
lock.lock();
try {
Thread.sleep(SMALL_DELAY_MS);
}
catch(Exception e) {
threadUnexpectedException();
}
lock.unlock();
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
assertTrue(lock.isLocked());
t.join();
assertFalse(lock.isLocked());
} catch(Exception e){
unexpectedException();
}
}
/**
* lockInterruptibly is interruptible.
*/
public void testLockInterruptibly1() {
final ReentrantLock lock = new ReentrantLock();
lock.lock();
Thread t = new Thread(new InterruptedLockRunnable(lock));
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
Thread.sleep(SHORT_DELAY_MS);
lock.unlock();
t.join();
} catch(Exception e){
unexpectedException();
}
}
/**
* lockInterruptibly succeeds when unlocked, else is interruptible
*/
public void testLockInterruptibly2() {
final ReentrantLock lock = new ReentrantLock();
try {
lock.lockInterruptibly();
} catch(Exception e) {
unexpectedException();
}
Thread t = new Thread(new InterruptedLockRunnable(lock));
try {
t.start();
t.interrupt();
assertTrue(lock.isLocked());
assertTrue(lock.isHeldByCurrentThread());
t.join();
} catch(Exception e){
unexpectedException();
}
}
/**
* Calling await without holding lock throws IllegalMonitorStateException
*/
public void testAwait_IllegalMonitor() {
final ReentrantLock lock = new ReentrantLock();
final Condition c = lock.newCondition();
try {
c.await();
shouldThrow();
}
catch (IllegalMonitorStateException success) {
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* Calling signal without holding lock throws IllegalMonitorStateException
*/
public void testSignal_IllegalMonitor() {
final ReentrantLock lock = new ReentrantLock();
final Condition c = lock.newCondition();
try {
c.signal();
shouldThrow();
}
catch (IllegalMonitorStateException success) {
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* awaitNanos without a signal times out
*/
public void testAwaitNanos_Timeout() {
final ReentrantLock lock = new ReentrantLock();
final Condition c = lock.newCondition();
try {
lock.lock();
long t = Utils.awaitNanos(c, 100);
assertTrue(t <= 0);
lock.unlock();
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* timed await without a signal times out
*/
public void testAwait_Timeout() {
final ReentrantLock lock = new ReentrantLock();
final Condition c = lock.newCondition();
try {
lock.lock();
c.await(SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
lock.unlock();
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* awaitUntil without a signal times out
*/
public void testAwaitUntil_Timeout() {
final ReentrantLock lock = new ReentrantLock();
final Condition c = lock.newCondition();
try {
lock.lock();
java.util.Date d = new java.util.Date();
c.awaitUntil(new java.util.Date(d.getTime() + 10));
lock.unlock();
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* await returns when signalled
*/
public void testAwait() {
final ReentrantLock lock = new ReentrantLock();
final Condition c = lock.newCondition();
Thread t = new Thread(new Runnable() {
public void run() {
try {
lock.lock();
c.await();
lock.unlock();
}
catch(InterruptedException e) {
threadUnexpectedException();
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
lock.lock();
c.signal();
lock.unlock();
t.join(SHORT_DELAY_MS);
assertFalse(t.isAlive());
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* hasWaiters throws NPE if null
*/
public void testHasWaitersNPE() {
final ReentrantLock lock = new ReentrantLock();
try {
lock.hasWaiters(null);
shouldThrow();
} catch (NullPointerException success) {
} catch (Exception ex) {
unexpectedException();
}
}
/**
* getWaitQueueLength throws NPE if null
*/
public void testGetWaitQueueLengthNPE() {
final ReentrantLock lock = new ReentrantLock();
try {
lock.getWaitQueueLength(null);
shouldThrow();
} catch (NullPointerException success) {
} catch (Exception ex) {
unexpectedException();
}
}
/**
* getWaitingThreads throws NPE if null
*/
public void testGetWaitingThreadsNPE() {
final PublicReentrantLock lock = new PublicReentrantLock(true); // originally was non-fair
try {
lock.getWaitingThreads(null);
shouldThrow();
} catch (NullPointerException success) {
} catch (Exception ex) {
unexpectedException();
}
}
/**
* hasWaiters throws IAE if not owned
*/
public void testHasWaitersIAE() {
final ReentrantLock lock = new ReentrantLock();
final Condition c = (lock.newCondition());
final ReentrantLock lock2 = new ReentrantLock();
try {
lock2.hasWaiters(c);
shouldThrow();
} catch (IllegalArgumentException success) {
} catch (Exception ex) {
unexpectedException();
}
}
/**
* hasWaiters throws IMSE if not locked
*/
public void testHasWaitersIMSE() {
final ReentrantLock lock = new ReentrantLock(true); // originally was non-fair
final Condition c = (lock.newCondition());
try {
lock.hasWaiters(c);
shouldThrow();
} catch (IllegalMonitorStateException success) {
} catch (Exception ex) {
unexpectedException();
}
}
/**
* getWaitQueueLength throws IAE if not owned
*/
public void testGetWaitQueueLengthIAE() {
final ReentrantLock lock = new ReentrantLock();
final Condition c = (lock.newCondition());
final ReentrantLock lock2 = new ReentrantLock();
try {
lock2.getWaitQueueLength(c);
shouldThrow();
} catch (IllegalArgumentException success) {
} catch (Exception ex) {
unexpectedException();
}
}
/**
* getWaitQueueLength throws IMSE if not locked
*/
public void testGetWaitQueueLengthIMSE() {
final ReentrantLock lock = new ReentrantLock(true); // originally was non-fair
final Condition c = (lock.newCondition());
try {
lock.getWaitQueueLength(c);
shouldThrow();
} catch (IllegalMonitorStateException success) {
} catch (Exception ex) {
unexpectedException();
}
}
/**
* getWaitingThreads throws IAE if not owned
*/
public void testGetWaitingThreadsIAE() {
final PublicReentrantLock lock = new PublicReentrantLock();
final Condition c = (lock.newCondition());
final PublicReentrantLock lock2 = new PublicReentrantLock();
try {
lock2.getWaitingThreads(c);
shouldThrow();
} catch (IllegalArgumentException success) {
} catch (Exception ex) {
unexpectedException();
}
}
/**
* getWaitingThreads throws IMSE if not locked
*/
public void testGetWaitingThreadsIMSE() {
final PublicReentrantLock lock = new PublicReentrantLock(true); // originally was non-fair
final Condition c = (lock.newCondition());
try {
lock.getWaitingThreads(c);
shouldThrow();
} catch (IllegalMonitorStateException success) {
} catch (Exception ex) {
unexpectedException();
}
}
/**
* hasWaiters returns true when a thread is waiting, else false
*/
public void testHasWaiters() {
final ReentrantLock lock = new ReentrantLock(true); // originally was non-fair
final Condition c = lock.newCondition();
Thread t = new Thread(new Runnable() {
public void run() {
try {
lock.lock();
threadAssertFalse(lock.hasWaiters(c));
threadAssertEquals(0, lock.getWaitQueueLength(c));
c.await();
lock.unlock();
}
catch(InterruptedException e) {
threadUnexpectedException();
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
lock.lock();
assertTrue(lock.hasWaiters(c));
assertEquals(1, lock.getWaitQueueLength(c));
c.signal();
lock.unlock();
Thread.sleep(SHORT_DELAY_MS);
lock.lock();
assertFalse(lock.hasWaiters(c));
assertEquals(0, lock.getWaitQueueLength(c));
lock.unlock();
t.join(SHORT_DELAY_MS);
assertFalse(t.isAlive());
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* getWaitQueueLength returns number of waiting threads
*/
public void testGetWaitQueueLength() {
final ReentrantLock lock = new ReentrantLock(true); // originally was non-fair
final Condition c = lock.newCondition();
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
lock.lock();
threadAssertFalse(lock.hasWaiters(c));
threadAssertEquals(0, lock.getWaitQueueLength(c));
c.await();
lock.unlock();
}
catch(InterruptedException e) {
threadUnexpectedException();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
lock.lock();
threadAssertTrue(lock.hasWaiters(c));
threadAssertEquals(1, lock.getWaitQueueLength(c));
c.await();
lock.unlock();
}
catch(InterruptedException e) {
threadUnexpectedException();
}
}
});
try {
t1.start();
Thread.sleep(SHORT_DELAY_MS);
t2.start();
Thread.sleep(SHORT_DELAY_MS);
lock.lock();
assertTrue(lock.hasWaiters(c));
assertEquals(2, lock.getWaitQueueLength(c));
c.signalAll();
lock.unlock();
Thread.sleep(SHORT_DELAY_MS);
lock.lock();
assertFalse(lock.hasWaiters(c));
assertEquals(0, lock.getWaitQueueLength(c));
lock.unlock();
t1.join(SHORT_DELAY_MS);
t2.join(SHORT_DELAY_MS);
assertFalse(t1.isAlive());
assertFalse(t2.isAlive());
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* getWaitingThreads returns only and all waiting threads
*/
public void testGetWaitingThreads() {
final PublicReentrantLock lock = new PublicReentrantLock(true); // originally was non-fair
final Condition c = lock.newCondition();
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
lock.lock();
threadAssertTrue(lock.getWaitingThreads(c).isEmpty());
c.await();
lock.unlock();
}
catch(InterruptedException e) {
threadUnexpectedException();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
lock.lock();
threadAssertFalse(lock.getWaitingThreads(c).isEmpty());
c.await();
lock.unlock();
}
catch(InterruptedException e) {
threadUnexpectedException();
}
}
});
try {
lock.lock();
assertTrue(lock.getWaitingThreads(c).isEmpty());
lock.unlock();
t1.start();
Thread.sleep(SHORT_DELAY_MS);
t2.start();
Thread.sleep(SHORT_DELAY_MS);
lock.lock();
assertTrue(lock.hasWaiters(c));
assertTrue(lock.getWaitingThreads(c).contains(t1));
assertTrue(lock.getWaitingThreads(c).contains(t2));
c.signalAll();
lock.unlock();
Thread.sleep(SHORT_DELAY_MS);
lock.lock();
assertFalse(lock.hasWaiters(c));
assertTrue(lock.getWaitingThreads(c).isEmpty());
lock.unlock();
t1.join(SHORT_DELAY_MS);
t2.join(SHORT_DELAY_MS);
assertFalse(t1.isAlive());
assertFalse(t2.isAlive());
}
catch (Exception ex) {
unexpectedException();
}
}
/** A helper class for uninterruptible wait tests */
class UninterruptableThread extends Thread {
private ReentrantLock lock;
private Condition c;
public volatile boolean canAwake = false;
public volatile boolean interrupted = false;
public volatile boolean lockStarted = false;
public UninterruptableThread(ReentrantLock lock, Condition c) {
this.lock = lock;
this.c = c;
}
public synchronized void run() {
lock.lock();
lockStarted = true;
while (!canAwake) {
c.awaitUninterruptibly();
}
interrupted = isInterrupted();
lock.unlock();
}
}
/**
* awaitUninterruptibly doesn't abort on interrupt
*/
public void testAwaitUninterruptibly() {
final ReentrantLock lock = new ReentrantLock();
final Condition c = lock.newCondition();
UninterruptableThread thread = new UninterruptableThread(lock, c);
try {
thread.start();
while (!thread.lockStarted) {
Thread.sleep(100);
}
lock.lock();
try {
thread.interrupt();
thread.canAwake = true;
c.signal();
} finally {
lock.unlock();
}
thread.join();
assertTrue(thread.interrupted);
assertFalse(thread.isAlive());
} catch (Exception ex) {
unexpectedException();
}
}
/**
* await is interruptible
*/
public void testAwait_Interrupt() {
final ReentrantLock lock = new ReentrantLock();
final Condition c = lock.newCondition();
Thread t = new Thread(new Runnable() {
public void run() {
try {
lock.lock();
c.await();
lock.unlock();
threadShouldThrow();
}
catch(InterruptedException success) {
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join(SHORT_DELAY_MS);
assertFalse(t.isAlive());
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* awaitNanos is interruptible
*/
public void testAwaitNanos_Interrupt() {
final ReentrantLock lock = new ReentrantLock();
final Condition c = lock.newCondition();
Thread t = new Thread(new Runnable() {
public void run() {
try {
lock.lock();
Utils.awaitNanos(c, 1000 * 1000 * 1000); // 1 sec
lock.unlock();
threadShouldThrow();
}
catch(InterruptedException success) {
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join(SHORT_DELAY_MS);
assertFalse(t.isAlive());
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* awaitUntil is interruptible
*/
public void testAwaitUntil_Interrupt() {
final ReentrantLock lock = new ReentrantLock();
final Condition c = lock.newCondition();
Thread t = new Thread(new Runnable() {
public void run() {
try {
lock.lock();
java.util.Date d = new java.util.Date();
c.awaitUntil(new java.util.Date(d.getTime() + 10000));
lock.unlock();
threadShouldThrow();
}
catch(InterruptedException success) {
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join(SHORT_DELAY_MS);
assertFalse(t.isAlive());
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* signalAll wakes up all threads
*/
public void testSignalAll() {
final ReentrantLock lock = new ReentrantLock();
final Condition c = lock.newCondition();
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
lock.lock();
c.await();
lock.unlock();
}
catch(InterruptedException e) {
threadUnexpectedException();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
lock.lock();
c.await();
lock.unlock();
}
catch(InterruptedException e) {
threadUnexpectedException();
}
}
});
try {
t1.start();
t2.start();
Thread.sleep(SHORT_DELAY_MS);
lock.lock();
c.signalAll();
lock.unlock();
t1.join(SHORT_DELAY_MS);
t2.join(SHORT_DELAY_MS);
assertFalse(t1.isAlive());
assertFalse(t2.isAlive());
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* await after multiple reentrant locking preserves lock count
*/
public void testAwaitLockCount() {
final ReentrantLock lock = new ReentrantLock();
final Condition c = lock.newCondition();
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
lock.lock();
threadAssertEquals(1, lock.getHoldCount());
c.await();
threadAssertEquals(1, lock.getHoldCount());
lock.unlock();
}
catch(InterruptedException e) {
threadUnexpectedException();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
lock.lock();
lock.lock();
threadAssertEquals(2, lock.getHoldCount());
c.await();
threadAssertEquals(2, lock.getHoldCount());
lock.unlock();
lock.unlock();
}
catch(InterruptedException e) {
threadUnexpectedException();
}
}
});
try {
t1.start();
t2.start();
Thread.sleep(SHORT_DELAY_MS);
lock.lock();
c.signalAll();
lock.unlock();
t1.join(SHORT_DELAY_MS);
t2.join(SHORT_DELAY_MS);
assertFalse(t1.isAlive());
assertFalse(t2.isAlive());
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* A serialized lock deserializes as unlocked
*/
public void testSerialization() {
ReentrantLock l = new ReentrantLock();
l.lock();
l.unlock();
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(l);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
ReentrantLock r = (ReentrantLock) in.readObject();
r.lock();
r.unlock();
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* toString indicates current lock state
*/
public void testToString() {
ReentrantLock lock = new ReentrantLock();
String us = lock.toString();
assertTrue(us.indexOf("Unlocked") >= 0);
lock.lock();
String ls = lock.toString();
assertTrue(ls.indexOf("Locked") >= 0);
}
}
backport-util-concurrent-3.1-src/test/tck/src/ExecutorCompletionServiceTest.java 0000644 0017507 0003772 00000016614 10346121124 027113 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
public class ExecutorCompletionServiceTest extends JSR166TestCase{
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(ExecutorCompletionServiceTest.class);
}
/**
* Creating a new ECS with null Executor throw NPE
*/
public void testConstructorNPE() {
try {
ExecutorCompletionService ecs = new ExecutorCompletionService(null);
shouldThrow();
} catch (NullPointerException success) {
}
}
/**
* Creating a new ECS with null queue throw NPE
*/
public void testConstructorNPE2() {
try {
ExecutorService e = Executors.newCachedThreadPool();
ExecutorCompletionService ecs = new ExecutorCompletionService(e, null);
shouldThrow();
} catch (NullPointerException success) {
}
}
/**
* Submitting a null callable throws NPE
*/
public void testSubmitNPE() {
ExecutorService e = Executors.newCachedThreadPool();
ExecutorCompletionService ecs = new ExecutorCompletionService(e);
try {
Callable c = null;
ecs.submit(c);
shouldThrow();
} catch (NullPointerException success) {
} finally {
joinPool(e);
}
}
/**
* Submitting a null runnable throws NPE
*/
public void testSubmitNPE2() {
ExecutorService e = Executors.newCachedThreadPool();
ExecutorCompletionService ecs = new ExecutorCompletionService(e);
try {
Runnable r = null;
ecs.submit(r, Boolean.TRUE);
shouldThrow();
} catch (NullPointerException success) {
} finally {
joinPool(e);
}
}
/**
* A taken submitted task is completed
*/
public void testTake() {
ExecutorService e = Executors.newCachedThreadPool();
ExecutorCompletionService ecs = new ExecutorCompletionService(e);
try {
Callable c = new StringTask();
ecs.submit(c);
Future f = ecs.take();
assertTrue(f.isDone());
} catch (Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* Take returns the same future object returned by submit
*/
public void testTake2() {
ExecutorService e = Executors.newCachedThreadPool();
ExecutorCompletionService ecs = new ExecutorCompletionService(e);
try {
Callable c = new StringTask();
Future f1 = ecs.submit(c);
Future f2 = ecs.take();
assertSame(f1, f2);
} catch (Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* If poll returns non-null, the returned task is completed
*/
public void testPoll1() {
ExecutorService e = Executors.newCachedThreadPool();
ExecutorCompletionService ecs = new ExecutorCompletionService(e);
try {
assertNull(ecs.poll());
Callable c = new StringTask();
ecs.submit(c);
Thread.sleep(SHORT_DELAY_MS);
for (;;) {
Future f = ecs.poll();
if (f != null) {
assertTrue(f.isDone());
break;
}
}
} catch (Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* If timed poll returns non-null, the returned task is completed
*/
public void testPoll2() {
ExecutorService e = Executors.newCachedThreadPool();
ExecutorCompletionService ecs = new ExecutorCompletionService(e);
try {
assertNull(ecs.poll());
Callable c = new StringTask();
ecs.submit(c);
Future f = ecs.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
if (f != null)
assertTrue(f.isDone());
} catch (Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* Submitting to underlying AES that overrides newTaskFor(Callable)
* returns and eventually runs Future returned by newTaskFor.
*/
public void testNewTaskForCallable() {
final AtomicBoolean done = new AtomicBoolean(false);
class MyCallableFuture extends FutureTask {
MyCallableFuture(Callable c) { super(c); }
protected void done() { done.set(true); }
}
ExecutorService e = new ThreadPoolExecutor(
1, 1, 30L, TimeUnit.SECONDS,
new ArrayBlockingQueue(1)) {
protected RunnableFuture newTaskFor(Callable c) {
return new MyCallableFuture(c);
}
};
ExecutorCompletionService ecs =
new ExecutorCompletionService(e);
try {
assertNull(ecs.poll());
Callable c = new StringTask();
Future f1 = ecs.submit(c);
assertTrue("submit must return MyCallableFuture",
f1 instanceof MyCallableFuture);
Future f2 = ecs.take();
assertSame("submit and take must return same objects", f1, f2);
assertTrue("completed task must have set done", done.get());
} catch (Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* Submitting to underlying AES that overrides newTaskFor(Runnable,T)
* returns and eventually runs Future returned by newTaskFor.
*/
public void testNewTaskForRunnable() {
final AtomicBoolean done = new AtomicBoolean(false);
class MyRunnableFuture extends FutureTask {
MyRunnableFuture(Runnable t, Object r) { super(t, r); }
protected void done() { done.set(true); }
}
ExecutorService e = new ThreadPoolExecutor(
1, 1, 30L, TimeUnit.SECONDS,
new ArrayBlockingQueue(1)) {
protected RunnableFuture newTaskFor(Runnable t, Object r) {
return new MyRunnableFuture(t, r);
}
};
ExecutorCompletionService ecs =
new ExecutorCompletionService(e);
try {
assertNull(ecs.poll());
Runnable r = new NoOpRunnable();
Future f1 = ecs.submit(r, null);
assertTrue("submit must return MyRunnableFuture",
f1 instanceof MyRunnableFuture);
Future f2 = ecs.take();
assertSame("submit and take must return same objects", f1, f2);
assertTrue("completed task must have set done", done.get());
} catch (Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/TreeSetTest.java 0000644 0017507 0003772 00000072737 10431777323 023342 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.io.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.BitSet;
public class TreeSetTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(TreeSetTest.class);
}
static class MyReverseComparator implements Comparator {
public int compare(Object x, Object y) {
int i = ((Integer)x).intValue();
int j = ((Integer)y).intValue();
if (i < j) return 1;
if (i > j) return -1;
return 0;
}
}
/**
* The number of elements to place in collections, arrays, etc.
*/
static final int SIZE = 20;
/**
* Create a set of given size containing consecutive
* Integers 0 ... n.
*/
private TreeSet populatedSet(int n) {
TreeSet q = new TreeSet();
assertTrue(q.isEmpty());
for(int i = n-1; i >= 0; i-=2)
assertTrue(q.add(new Integer(i)));
for(int i = (n & 1); i < n; i+=2)
assertTrue(q.add(new Integer(i)));
assertFalse(q.isEmpty());
assertEquals(n, q.size());
return q;
}
/**
* Create set of first 5 ints
*/
private TreeSet set5() {
TreeSet q = new TreeSet();
assertTrue(q.isEmpty());
q.add(one);
q.add(two);
q.add(three);
q.add(four);
q.add(five);
assertEquals(5, q.size());
return q;
}
/**
* A new set has unbounded capacity
*/
public void testConstructor1() {
assertEquals(0, new TreeSet().size());
}
/**
* Initializing from null Collection throws NPE
*/
public void testConstructor3() {
try {
TreeSet q = new TreeSet((Collection)null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from Collection of null elements throws NPE
*/
public void testConstructor4() {
try {
Integer[] ints = new Integer[SIZE];
TreeSet q = new TreeSet(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from Collection with some null elements throws NPE
*/
public void testConstructor5() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
TreeSet q = new TreeSet(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Set contains all elements of collection used to initialize
*/
public void testConstructor6() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
TreeSet q = new TreeSet(Arrays.asList(ints));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.pollFirst());
}
finally {}
}
/**
* The comparator used in constructor is used
*/
public void testConstructor7() {
try {
MyReverseComparator cmp = new MyReverseComparator();
TreeSet q = new TreeSet(cmp);
assertEquals(cmp, q.comparator());
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
for (int i = SIZE-1; i >= 0; --i)
assertEquals(ints[i], q.pollFirst());
}
finally {}
}
/**
* isEmpty is true before add, false after
*/
public void testEmpty() {
TreeSet q = new TreeSet();
assertTrue(q.isEmpty());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.add(new Integer(2));
q.pollFirst();
q.pollFirst();
assertTrue(q.isEmpty());
}
/**
* size changes when elements added and removed
*/
public void testSize() {
TreeSet q = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i, q.size());
q.pollFirst();
}
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
q.add(new Integer(i));
}
}
/**
* add(null) throws NPE if nonempty
*/
public void testAddNull() {
try {
TreeSet q = populatedSet(SIZE);
q.add(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* Add of comparable element succeeds
*/
public void testAdd() {
TreeSet q = new TreeSet();
assertTrue(q.add(zero));
assertTrue(q.add(one));
}
/**
* Add of duplicate element fails
*/
public void testAddDup() {
TreeSet q = new TreeSet();
assertTrue(q.add(zero));
assertFalse(q.add(zero));
}
/**
* Add of non-Comparable throws CCE
*/
public void testAddNonComparable() {
try {
TreeSet q = new TreeSet();
q.add(new Object());
q.add(new Object());
q.add(new Object());
shouldThrow();
}
catch(ClassCastException success) {}
}
/**
* addAll(null) throws NPE
*/
public void testAddAll1() {
try {
TreeSet q = new TreeSet();
q.addAll(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with null elements throws NPE
*/
public void testAddAll2() {
try {
TreeSet q = new TreeSet();
Integer[] ints = new Integer[SIZE];
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with any null elements throws NPE after
* possibly adding some elements
*/
public void testAddAll3() {
try {
TreeSet q = new TreeSet();
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Set contains all elements of successful addAll
*/
public void testAddAll5() {
try {
Integer[] empty = new Integer[0];
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(SIZE-1-i);
TreeSet q = new TreeSet();
assertFalse(q.addAll(Arrays.asList(empty)));
assertTrue(q.addAll(Arrays.asList(ints)));
for (int i = 0; i < SIZE; ++i)
assertEquals(new Integer(i), q.pollFirst());
}
finally {}
}
/**
* pollFirst succeeds unless empty
*/
public void testPollFirst() {
TreeSet q = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.pollFirst()).intValue());
}
assertNull(q.pollFirst());
}
/**
* pollLast succeeds unless empty
*/
public void testPollLast() {
TreeSet q = populatedSet(SIZE);
for (int i = SIZE-1; i >= 0; --i) {
assertEquals(i, ((Integer)q.pollLast()).intValue());
}
assertNull(q.pollFirst());
}
/**
* remove(x) removes x and returns true if present
*/
public void testRemoveElement() {
TreeSet q = populatedSet(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
assertFalse(q.remove(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* contains(x) reports true when elements added but not yet removed
*/
public void testContains() {
TreeSet q = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.contains(new Integer(i)));
q.pollFirst();
assertFalse(q.contains(new Integer(i)));
}
}
/**
* clear removes all elements
*/
public void testClear() {
TreeSet q = populatedSet(SIZE);
q.clear();
assertTrue(q.isEmpty());
assertEquals(0, q.size());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.clear();
assertTrue(q.isEmpty());
}
/**
* containsAll(c) is true when c contains a subset of elements
*/
public void testContainsAll() {
TreeSet q = populatedSet(SIZE);
TreeSet p = new TreeSet();
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.containsAll(p));
assertFalse(p.containsAll(q));
p.add(new Integer(i));
}
assertTrue(p.containsAll(q));
}
/**
* retainAll(c) retains only those elements of c and reports true if changed
*/
public void testRetainAll() {
TreeSet q = populatedSet(SIZE);
TreeSet p = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
boolean changed = q.retainAll(p);
if (i == 0)
assertFalse(changed);
else
assertTrue(changed);
assertTrue(q.containsAll(p));
assertEquals(SIZE-i, q.size());
p.pollFirst();
}
}
/**
* removeAll(c) removes only those elements of c and reports true if changed
*/
public void testRemoveAll() {
for (int i = 1; i < SIZE; ++i) {
TreeSet q = populatedSet(SIZE);
TreeSet p = populatedSet(i);
assertTrue(q.removeAll(p));
assertEquals(SIZE-i, q.size());
for (int j = 0; j < i; ++j) {
Integer I = (Integer)(p.pollFirst());
assertFalse(q.contains(I));
}
}
}
/**
* lower returns preceding element
*/
public void testLower() {
TreeSet q = set5();
Object e1 = q.lower(three);
assertEquals(two, e1);
Object e2 = q.lower(six);
assertEquals(five, e2);
Object e3 = q.lower(one);
assertNull(e3);
Object e4 = q.lower(zero);
assertNull(e4);
}
/**
* higher returns next element
*/
public void testHigher() {
TreeSet q = set5();
Object e1 = q.higher(three);
assertEquals(four, e1);
Object e2 = q.higher(zero);
assertEquals(one, e2);
Object e3 = q.higher(five);
assertNull(e3);
Object e4 = q.higher(six);
assertNull(e4);
}
/**
* floor returns preceding element
*/
public void testFloor() {
TreeSet q = set5();
Object e1 = q.floor(three);
assertEquals(three, e1);
Object e2 = q.floor(six);
assertEquals(five, e2);
Object e3 = q.floor(one);
assertEquals(one, e3);
Object e4 = q.floor(zero);
assertNull(e4);
}
/**
* ceiling returns next element
*/
public void testCeiling() {
TreeSet q = set5();
Object e1 = q.ceiling(three);
assertEquals(three, e1);
Object e2 = q.ceiling(zero);
assertEquals(one, e2);
Object e3 = q.ceiling(five);
assertEquals(five, e3);
Object e4 = q.ceiling(six);
assertNull(e4);
}
/**
* toArray contains all elements
*/
public void testToArray() {
TreeSet q = populatedSet(SIZE);
Object[] o = q.toArray();
Arrays.sort(o);
for(int i = 0; i < o.length; i++)
assertEquals(o[i], q.pollFirst());
}
/**
* toArray(a) contains all elements
*/
public void testToArray2() {
TreeSet q = populatedSet(SIZE);
Integer[] ints = new Integer[SIZE];
ints = (Integer[])q.toArray(ints);
Arrays.sort(ints);
for(int i = 0; i < ints.length; i++)
assertEquals(ints[i], q.pollFirst());
}
/**
* iterator iterates through all elements
*/
public void testIterator() {
TreeSet q = populatedSet(SIZE);
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, SIZE);
}
/**
* iterator of empty set has no elements
*/
public void testEmptyIterator() {
TreeSet q = new TreeSet();
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, 0);
}
/**
* iterator.remove removes current element
*/
public void testIteratorRemove () {
final TreeSet q = new TreeSet();
q.add(new Integer(2));
q.add(new Integer(1));
q.add(new Integer(3));
Iterator it = q.iterator();
it.next();
it.remove();
it = q.iterator();
assertEquals(it.next(), new Integer(2));
assertEquals(it.next(), new Integer(3));
assertFalse(it.hasNext());
}
/**
* toString contains toStrings of elements
*/
public void testToString() {
TreeSet q = populatedSet(SIZE);
String s = q.toString();
for (int i = 0; i < SIZE; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
/**
* A deserialized serialized set has same elements
*/
public void testSerialization() {
TreeSet q = populatedSet(SIZE);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
TreeSet r = (TreeSet)in.readObject();
assertEquals(q.size(), r.size());
while (!q.isEmpty())
assertEquals(q.pollFirst(), r.pollFirst());
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* subSet returns set with keys in requested range
*/
public void testSubSetContents() {
TreeSet set = set5();
SortedSet sm = set.subSet(two, four);
assertEquals(two, sm.first());
assertEquals(three, sm.last());
assertEquals(2, sm.size());
assertFalse(sm.contains(one));
assertTrue(sm.contains(two));
assertTrue(sm.contains(three));
assertFalse(sm.contains(four));
assertFalse(sm.contains(five));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
assertFalse(i.hasNext());
Iterator j = sm.iterator();
j.next();
j.remove();
assertFalse(set.contains(two));
assertEquals(4, set.size());
assertEquals(1, sm.size());
assertEquals(three, sm.first());
assertEquals(three, sm.last());
assertTrue(sm.remove(three));
assertTrue(sm.isEmpty());
assertEquals(3, set.size());
}
public void testSubSetContents2() {
TreeSet set = set5();
SortedSet sm = set.subSet(two, three);
assertEquals(1, sm.size());
assertEquals(two, sm.first());
assertEquals(two, sm.last());
assertFalse(sm.contains(one));
assertTrue(sm.contains(two));
assertFalse(sm.contains(three));
assertFalse(sm.contains(four));
assertFalse(sm.contains(five));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
assertFalse(i.hasNext());
Iterator j = sm.iterator();
j.next();
j.remove();
assertFalse(set.contains(two));
assertEquals(4, set.size());
assertEquals(0, sm.size());
assertTrue(sm.isEmpty());
assertFalse(sm.remove(three));
assertEquals(4, set.size());
}
/**
* headSet returns set with keys in requested range
*/
public void testHeadSetContents() {
TreeSet set = set5();
SortedSet sm = set.headSet(four);
assertTrue(sm.contains(one));
assertTrue(sm.contains(two));
assertTrue(sm.contains(three));
assertFalse(sm.contains(four));
assertFalse(sm.contains(five));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(one, k);
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
assertFalse(i.hasNext());
sm.clear();
assertTrue(sm.isEmpty());
assertEquals(2, set.size());
assertEquals(four, set.first());
}
/**
* tailSet returns set with keys in requested range
*/
public void testTailSetContents() {
TreeSet set = set5();
SortedSet sm = set.tailSet(two);
assertFalse(sm.contains(one));
assertTrue(sm.contains(two));
assertTrue(sm.contains(three));
assertTrue(sm.contains(four));
assertTrue(sm.contains(five));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
k = (Integer)(i.next());
assertEquals(four, k);
k = (Integer)(i.next());
assertEquals(five, k);
assertFalse(i.hasNext());
SortedSet ssm = sm.tailSet(four);
assertEquals(four, ssm.first());
assertEquals(five, ssm.last());
assertTrue(ssm.remove(four));
assertEquals(1, ssm.size());
assertEquals(3, sm.size());
assertEquals(4, set.size());
}
Random rnd = new Random(666);
BitSet bs;
/**
* Subsets of subsets subdivide correctly
*/
public void testRecursiveSubSets() {
int setSize = 1000;
Class cl = TreeSet.class;
NavigableSet set = newSet(cl);
bs = new BitSet(setSize);
populate(set, setSize);
check(set, 0, setSize - 1, true);
check(set.descendingSet(), 0, setSize - 1, false);
mutateSet(set, 0, setSize - 1);
check(set, 0, setSize - 1, true);
check(set.descendingSet(), 0, setSize - 1, false);
bashSubSet(set.subSet(new Integer(0), true, new Integer(setSize), false),
0, setSize - 1, true);
}
static NavigableSet newSet(Class cl) {
NavigableSet result = null;
try {
result = (NavigableSet) cl.newInstance();
} catch(Exception e) {
fail();
}
assertEquals(result.size(), 0);
assertFalse(result.iterator().hasNext());
return result;
}
void populate(NavigableSet set, int limit) {
for (int i = 0, n = 2 * limit / 3; i < n; i++) {
int element = rnd.nextInt(limit);
put(set, element);
}
}
void mutateSet(NavigableSet set, int min, int max) {
int size = set.size();
int rangeSize = max - min + 1;
// Remove a bunch of entries directly
for (int i = 0, n = rangeSize / 2; i < n; i++) {
remove(set, min - 5 + rnd.nextInt(rangeSize + 10));
}
// Remove a bunch of entries with iterator
for(Iterator it = set.iterator(); it.hasNext(); ) {
if (rnd.nextBoolean()) {
bs.clear(((Integer)it.next()).intValue());
it.remove();
}
}
// Add entries till we're back to original size
while (set.size() < size) {
int element = min + rnd.nextInt(rangeSize);
assertTrue(element >= min && element<= max);
put(set, element);
}
}
void mutateSubSet(NavigableSet set, int min, int max) {
int size = set.size();
int rangeSize = max - min + 1;
// Remove a bunch of entries directly
for (int i = 0, n = rangeSize / 2; i < n; i++) {
remove(set, min - 5 + rnd.nextInt(rangeSize + 10));
}
// Remove a bunch of entries with iterator
for(Iterator it = set.iterator(); it.hasNext(); ) {
if (rnd.nextBoolean()) {
bs.clear(((Integer)it.next()).intValue());
it.remove();
}
}
// Add entries till we're back to original size
while (set.size() < size) {
int element = min - 5 + rnd.nextInt(rangeSize + 10);
if (element >= min && element<= max) {
put(set, element);
} else {
try {
set.add(new Integer(element));
fail();
} catch(IllegalArgumentException e) {
// expected
}
}
}
}
void put(NavigableSet set, int element) {
if (set.add(new Integer(element)))
bs.set(element);
}
void remove(NavigableSet set, int element) {
if (set.remove(new Integer(element)))
bs.clear(element);
}
void bashSubSet(NavigableSet set,
int min, int max, boolean ascending) {
check(set, min, max, ascending);
check(set.descendingSet(), min, max, !ascending);
mutateSubSet(set, min, max);
check(set, min, max, ascending);
check(set.descendingSet(), min, max, !ascending);
// Recurse
if (max - min < 2)
return;
int midPoint = (min + max) / 2;
// headSet - pick direction and endpoint inclusion randomly
boolean incl = rnd.nextBoolean();
NavigableSet hm = set.headSet(new Integer(midPoint), incl);
if (ascending) {
if (rnd.nextBoolean())
bashSubSet(hm, min, midPoint - (incl ? 0 : 1), true);
else
bashSubSet(hm.descendingSet(), min, midPoint - (incl ? 0 : 1),
false);
} else {
if (rnd.nextBoolean())
bashSubSet(hm, midPoint + (incl ? 0 : 1), max, false);
else
bashSubSet(hm.descendingSet(), midPoint + (incl ? 0 : 1), max,
true);
}
// tailSet - pick direction and endpoint inclusion randomly
incl = rnd.nextBoolean();
NavigableSet tm = set.tailSet(new Integer(midPoint),incl);
if (ascending) {
if (rnd.nextBoolean())
bashSubSet(tm, midPoint + (incl ? 0 : 1), max, true);
else
bashSubSet(tm.descendingSet(), midPoint + (incl ? 0 : 1), max,
false);
} else {
if (rnd.nextBoolean()) {
bashSubSet(tm, min, midPoint - (incl ? 0 : 1), false);
} else {
bashSubSet(tm.descendingSet(), min, midPoint - (incl ? 0 : 1),
true);
}
}
// subSet - pick direction and endpoint inclusion randomly
int rangeSize = max - min + 1;
int[] endpoints = new int[2];
endpoints[0] = min + rnd.nextInt(rangeSize);
endpoints[1] = min + rnd.nextInt(rangeSize);
Arrays.sort(endpoints);
boolean lowIncl = rnd.nextBoolean();
boolean highIncl = rnd.nextBoolean();
if (ascending) {
NavigableSet sm = set.subSet(
new Integer(endpoints[0]), lowIncl, new Integer(endpoints[1]), highIncl);
if (rnd.nextBoolean())
bashSubSet(sm, endpoints[0] + (lowIncl ? 0 : 1),
endpoints[1] - (highIncl ? 0 : 1), true);
else
bashSubSet(sm.descendingSet(), endpoints[0] + (lowIncl ? 0 : 1),
endpoints[1] - (highIncl ? 0 : 1), false);
} else {
NavigableSet sm = set.subSet(
new Integer(endpoints[1]), highIncl, new Integer(endpoints[0]), lowIncl);
if (rnd.nextBoolean())
bashSubSet(sm, endpoints[0] + (lowIncl ? 0 : 1),
endpoints[1] - (highIncl ? 0 : 1), false);
else
bashSubSet(sm.descendingSet(), endpoints[0] + (lowIncl ? 0 : 1),
endpoints[1] - (highIncl ? 0 : 1), true);
}
}
/**
* min and max are both inclusive. If max < min, interval is empty.
*/
void check(NavigableSet set,
final int min, final int max, final boolean ascending) {
class ReferenceSet {
int lower(int element) {
return ascending ?
lowerAscending(element) : higherAscending(element);
}
int floor(int element) {
return ascending ?
floorAscending(element) : ceilingAscending(element);
}
int ceiling(int element) {
return ascending ?
ceilingAscending(element) : floorAscending(element);
}
int higher(int element) {
return ascending ?
higherAscending(element) : lowerAscending(element);
}
int first() {
return ascending ? firstAscending() : lastAscending();
}
int last() {
return ascending ? lastAscending() : firstAscending();
}
int lowerAscending(int element) {
return floorAscending(element - 1);
}
int floorAscending(int element) {
if (element < min)
return -1;
else if (element > max)
element = max;
// BitSet should support this! Test would run much faster
while (element >= min) {
if (bs.get(element))
return(element);
element--;
}
return -1;
}
int ceilingAscending(int element) {
if (element < min)
element = min;
else if (element > max)
return -1;
int result = bs.nextSetBit(element);
return result > max ? -1 : result;
}
int higherAscending(int element) {
return ceilingAscending(element + 1);
}
private int firstAscending() {
int result = ceilingAscending(min);
return result > max ? -1 : result;
}
private int lastAscending() {
int result = floorAscending(max);
return result < min ? -1 : result;
}
}
ReferenceSet rs = new ReferenceSet();
// Test contents using containsElement
int size = 0;
for (int i = min; i <= max; i++) {
boolean bsContainsI = bs.get(i);
assertEquals(bsContainsI, set.contains(new Integer(i)));
if (bsContainsI)
size++;
}
assertEquals(set.size(), size);
// Test contents using contains elementSet iterator
int size2 = 0;
int previousElement = -1;
for (Iterator itr = set.iterator(); itr.hasNext();) {
int element = ((Integer)itr.next()).intValue();
assertTrue(bs.get(element));
size2++;
assertTrue(previousElement < 0 || (ascending ?
element - previousElement > 0 : element - previousElement < 0));
previousElement = element;
}
assertEquals(size2, size);
// Test navigation ops
for (int element = min - 1; element <= max + 1; element++) {
assertEq((Integer)set.lower(new Integer(element)), rs.lower(element));
assertEq((Integer)set.floor(new Integer(element)), rs.floor(element));
assertEq((Integer)set.higher(new Integer(element)), rs.higher(element));
assertEq((Integer)set.ceiling(new Integer(element)), rs.ceiling(element));
}
// Test extrema
if (set.size() != 0) {
assertEq((Integer)set.first(), rs.first());
assertEq((Integer)set.last(), rs.last());
} else {
assertEq(new Integer(rs.first()), -1);
assertEq(new Integer(rs.last()), -1);
try {
set.first();
fail();
} catch(NoSuchElementException e) {
// expected
}
try {
set.last();
fail();
} catch(NoSuchElementException e) {
// expected
}
}
}
static void assertEq(Integer i, int j) {
if (i == null)
assertEquals(j, -1);
else
assertEquals(i.intValue(), j);
}
static boolean eq(Integer i, int j) {
return i == null ? j == -1 : i.intValue() == j;
}
}
backport-util-concurrent-3.1-src/test/tck/src/AtomicBooleanTest.java 0000644 0017507 0003772 00000011023 10253674160 024455 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import java.io.*;
public class AtomicBooleanTest extends JSR166TestCase {
public static void main (String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(AtomicBooleanTest.class);
}
/**
* constructor initializes to given value
*/
public void testConstructor() {
AtomicBoolean ai = new AtomicBoolean(true);
assertEquals(true,ai.get());
}
/**
* default constructed initializes to false
*/
public void testConstructor2() {
AtomicBoolean ai = new AtomicBoolean();
assertEquals(false,ai.get());
}
/**
* get returns the last value set
*/
public void testGetSet() {
AtomicBoolean ai = new AtomicBoolean(true);
assertEquals(true,ai.get());
ai.set(false);
assertEquals(false,ai.get());
ai.set(true);
assertEquals(true,ai.get());
}
/**
* get returns the last value lazySet in same thread
*/
public void testGetLazySet() {
AtomicBoolean ai = new AtomicBoolean(true);
assertEquals(true,ai.get());
ai.lazySet(false);
assertEquals(false,ai.get());
ai.lazySet(true);
assertEquals(true,ai.get());
}
/**
* compareAndSet succeeds in changing value if equal to expected else fails
*/
public void testCompareAndSet() {
AtomicBoolean ai = new AtomicBoolean(true);
assertTrue(ai.compareAndSet(true,false));
assertEquals(false,ai.get());
assertTrue(ai.compareAndSet(false,false));
assertEquals(false,ai.get());
assertFalse(ai.compareAndSet(true,false));
assertFalse((ai.get()));
assertTrue(ai.compareAndSet(false,true));
assertEquals(true,ai.get());
}
/**
* compareAndSet in one thread enables another waiting for value
* to succeed
*/
public void testCompareAndSetInMultipleThreads() {
final AtomicBoolean ai = new AtomicBoolean(true);
Thread t = new Thread(new Runnable() {
public void run() {
while(!ai.compareAndSet(false, true)) Thread.yield();
}});
try {
t.start();
assertTrue(ai.compareAndSet(true, false));
t.join(LONG_DELAY_MS);
assertFalse(t.isAlive());
}
catch(Exception e) {
unexpectedException();
}
}
/**
* repeated weakCompareAndSet succeeds in changing value when equal
* to expected
*/
public void testWeakCompareAndSet() {
AtomicBoolean ai = new AtomicBoolean(true);
while(!ai.weakCompareAndSet(true,false));
assertEquals(false,ai.get());
while(!ai.weakCompareAndSet(false,false));
assertEquals(false,ai.get());
while(!ai.weakCompareAndSet(false,true));
assertEquals(true,ai.get());
}
/**
* getAndSet returns previous value and sets to given value
*/
public void testGetAndSet() {
AtomicBoolean ai = new AtomicBoolean(true);
assertEquals(true,ai.getAndSet(false));
assertEquals(false,ai.getAndSet(false));
assertEquals(false,ai.getAndSet(true));
assertEquals(true,ai.get());
}
/**
* a deserialized serialized atomic holds same value
*/
public void testSerialization() {
AtomicBoolean l = new AtomicBoolean();
try {
l.set(true);
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(l);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
AtomicBoolean r = (AtomicBoolean) in.readObject();
assertEquals(l.get(), r.get());
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* toString returns current value.
*/
public void testToString() {
AtomicBoolean ai = new AtomicBoolean();
assertEquals(ai.toString(), Boolean.toString(false));
ai.set(true);
assertEquals(ai.toString(), Boolean.toString(true));
}
}
backport-util-concurrent-3.1-src/test/tck/src/ThreadLocalTest.java 0000644 0017507 0003772 00000005750 10153210664 024127 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.Semaphore;
public class ThreadLocalTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static Test suite() {
return new TestSuite(ThreadLocalTest.class);
}
static ThreadLocal tl = new ThreadLocal() {
public Object initialValue() {
return one;
}
};
static InheritableThreadLocal itl =
new InheritableThreadLocal() {
protected Object initialValue() {
return zero;
}
protected Object childValue(Object parentValue) {
return new Integer(((Integer)parentValue).intValue() + 1);
}
};
// /**
// * remove causes next access to return initial value
// */
// public void testRemove() {
// assertEquals(tl.get(), one);
// tl.set(two);
// assertEquals(tl.get(), two);
// tl.remove();
// assertEquals(tl.get(), one);
// }
//
// /**
// * remove in InheritableThreadLocal causes next access to return
// * initial value
// */
// public void testRemoveITL() {
// assertEquals(itl.get(), zero);
// itl.set(two);
// assertEquals(itl.get(), two);
// itl.remove();
// assertEquals(itl.get(), zero);
// }
private class ITLThread extends Thread {
final int[] x;
ITLThread(int[] array) { x = array; }
public void run() {
Thread child = null;
if (((Integer)itl.get()).intValue() < x.length - 1) {
child = new ITLThread(x);
child.start();
}
Thread.currentThread().yield();
int threadId = ((Integer)itl.get()).intValue();
for (int j = 0; j < threadId; j++) {
x[threadId]++;
Thread.currentThread().yield();
}
if (child != null) { // Wait for child (if any)
try {
child.join();
} catch(InterruptedException e) {
threadUnexpectedException();
}
}
}
}
/**
* InheritableThreadLocal propagates generic values.
*/
public void testGenericITL() {
final int threadCount = 10;
final int x[] = new int[threadCount];
Thread progenitor = new ITLThread(x);
try {
progenitor.start();
progenitor.join();
for(int i = 0; i < threadCount; i++) {
assertEquals(i, x[i]);
}
} catch(InterruptedException e) {
unexpectedException();
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/ConcurrentSkipListSubMapTest.java 0000644 0017507 0003772 00000123660 10431777323 026674 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import junit.framework.*;
import java.util.Collection;
import java.util.Set;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.ArrayList;
import java.util.SortedMap;
import java.io.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
public class ConcurrentSkipListSubMapTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(ConcurrentSkipListSubMapTest.class);
}
/**
* Create a map from Integers 1-5 to Strings "A"-"E".
*/
private static ConcurrentNavigableMap map5() {
ConcurrentSkipListMap map = new ConcurrentSkipListMap();
assertTrue(map.isEmpty());
map.put(zero, "Z");
map.put(one, "A");
map.put(five, "E");
map.put(three, "C");
map.put(two, "B");
map.put(four, "D");
map.put(seven, "F");
assertFalse(map.isEmpty());
assertEquals(7, map.size());
return (ConcurrentNavigableMap)map.subMap(one, true, seven, false);
}
/**
* Create a map from Integers -5 to -1 to Strings "A"-"E".
*/
private static ConcurrentNavigableMap dmap5() {
ConcurrentSkipListMap map = new ConcurrentSkipListMap();
assertTrue(map.isEmpty());
map.put(m1, "A");
map.put(m5, "E");
map.put(m3, "C");
map.put(m2, "B");
map.put(m4, "D");
assertFalse(map.isEmpty());
assertEquals(5, map.size());
return (ConcurrentNavigableMap)map.descendingMap();
}
private static ConcurrentNavigableMap map0() {
ConcurrentSkipListMap map = new ConcurrentSkipListMap();
assertTrue(map.isEmpty());
return (ConcurrentNavigableMap)map.tailMap(one, true);
}
private static ConcurrentNavigableMap dmap0() {
ConcurrentSkipListMap map = new ConcurrentSkipListMap();
assertTrue(map.isEmpty());
return map;
}
/**
* clear removes all pairs
*/
public void testClear() {
ConcurrentNavigableMap map = map5();
map.clear();
assertEquals(map.size(), 0);
}
/**
* Maps with same contents are equal
*/
public void testEquals() {
ConcurrentNavigableMap map1 = map5();
ConcurrentNavigableMap map2 = map5();
assertEquals(map1, map2);
assertEquals(map2, map1);
map1.clear();
assertFalse(map1.equals(map2));
assertFalse(map2.equals(map1));
}
/**
* containsKey returns true for contained key
*/
public void testContainsKey() {
ConcurrentNavigableMap map = map5();
assertTrue(map.containsKey(one));
assertFalse(map.containsKey(zero));
}
/**
* containsValue returns true for held values
*/
public void testContainsValue() {
ConcurrentNavigableMap map = map5();
assertTrue(map.containsValue("A"));
assertFalse(map.containsValue("Z"));
}
/**
* get returns the correct element at the given key,
* or null if not present
*/
public void testGet() {
ConcurrentNavigableMap map = map5();
assertEquals("A", (String)map.get(one));
ConcurrentNavigableMap empty = map0();
assertNull(empty.get(one));
}
/**
* isEmpty is true of empty map and false for non-empty
*/
public void testIsEmpty() {
ConcurrentNavigableMap empty = map0();
ConcurrentNavigableMap map = map5();
assertTrue(empty.isEmpty());
assertFalse(map.isEmpty());
}
/**
* firstKey returns first key
*/
public void testFirstKey() {
ConcurrentNavigableMap map = map5();
assertEquals(one, map.firstKey());
}
/**
* lastKey returns last key
*/
public void testLastKey() {
ConcurrentNavigableMap map = map5();
assertEquals(five, map.lastKey());
}
/**
* keySet returns a Set containing all the keys
*/
public void testKeySet() {
ConcurrentNavigableMap map = map5();
Set s = map.keySet();
assertEquals(5, s.size());
assertTrue(s.contains(one));
assertTrue(s.contains(two));
assertTrue(s.contains(three));
assertTrue(s.contains(four));
assertTrue(s.contains(five));
}
/**
* keySet is ordered
*/
public void testKeySetOrder() {
ConcurrentNavigableMap map = map5();
Set s = map.keySet();
Iterator i = s.iterator();
Integer last = (Integer)i.next();
assertEquals(last, one);
while (i.hasNext()) {
Integer k = (Integer)i.next();
assertTrue(last.compareTo(k) < 0);
last = k;
}
}
/**
* values collection contains all values
*/
public void testValues() {
ConcurrentNavigableMap map = map5();
Collection s = map.values();
assertEquals(5, s.size());
assertTrue(s.contains("A"));
assertTrue(s.contains("B"));
assertTrue(s.contains("C"));
assertTrue(s.contains("D"));
assertTrue(s.contains("E"));
}
/**
* keySet.toArray returns contains all keys
*/
public void testKeySetToArray() {
ConcurrentNavigableMap map = map5();
Set s = map.keySet();
Object[] ar = s.toArray();
assertTrue(s.containsAll(Arrays.asList(ar)));
assertEquals(5, ar.length);
ar[0] = m10;
assertFalse(s.containsAll(Arrays.asList(ar)));
}
/**
* descendingkeySet.toArray returns contains all keys
*/
public void testDescendingKeySetToArray() {
ConcurrentNavigableMap map = map5();
Set s = map.descendingKeySet();
Object[] ar = s.toArray();
assertEquals(5, ar.length);
assertTrue(s.containsAll(Arrays.asList(ar)));
ar[0] = m10;
assertFalse(s.containsAll(Arrays.asList(ar)));
}
/**
* Values.toArray contains all values
*/
public void testValuesToArray() {
ConcurrentNavigableMap map = map5();
Collection v = map.values();
Object[] ar = v.toArray();
ArrayList s = new ArrayList(Arrays.asList(ar));
assertEquals(5, ar.length);
assertTrue(s.contains("A"));
assertTrue(s.contains("B"));
assertTrue(s.contains("C"));
assertTrue(s.contains("D"));
assertTrue(s.contains("E"));
}
/**
* entrySet contains all pairs
*/
public void testEntrySet() {
ConcurrentNavigableMap map = map5();
Set s = map.entrySet();
assertEquals(5, s.size());
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
assertTrue(
(e.getKey().equals(one) && e.getValue().equals("A")) ||
(e.getKey().equals(two) && e.getValue().equals("B")) ||
(e.getKey().equals(three) && e.getValue().equals("C")) ||
(e.getKey().equals(four) && e.getValue().equals("D")) ||
(e.getKey().equals(five) && e.getValue().equals("E")));
}
}
/**
* putAll adds all key-value pairs from the given map
*/
public void testPutAll() {
ConcurrentNavigableMap empty = map0();
ConcurrentNavigableMap map = map5();
empty.putAll(map);
assertEquals(5, empty.size());
assertTrue(empty.containsKey(one));
assertTrue(empty.containsKey(two));
assertTrue(empty.containsKey(three));
assertTrue(empty.containsKey(four));
assertTrue(empty.containsKey(five));
}
/**
* putIfAbsent works when the given key is not present
*/
public void testPutIfAbsent() {
ConcurrentNavigableMap map = map5();
map.putIfAbsent(six, "Z");
assertTrue(map.containsKey(six));
}
/**
* putIfAbsent does not add the pair if the key is already present
*/
public void testPutIfAbsent2() {
ConcurrentNavigableMap map = map5();
assertEquals("A", map.putIfAbsent(one, "Z"));
}
/**
* replace fails when the given key is not present
*/
public void testReplace() {
ConcurrentNavigableMap map = map5();
assertNull(map.replace(six, "Z"));
assertFalse(map.containsKey(six));
}
/**
* replace succeeds if the key is already present
*/
public void testReplace2() {
ConcurrentNavigableMap map = map5();
assertNotNull(map.replace(one, "Z"));
assertEquals("Z", map.get(one));
}
/**
* replace value fails when the given key not mapped to expected value
*/
public void testReplaceValue() {
ConcurrentNavigableMap map = map5();
assertEquals("A", map.get(one));
assertFalse(map.replace(one, "Z", "Z"));
assertEquals("A", map.get(one));
}
/**
* replace value succeeds when the given key mapped to expected value
*/
public void testReplaceValue2() {
ConcurrentNavigableMap map = map5();
assertEquals("A", map.get(one));
assertTrue(map.replace(one, "A", "Z"));
assertEquals("Z", map.get(one));
}
/**
* remove removes the correct key-value pair from the map
*/
public void testRemove() {
ConcurrentNavigableMap map = map5();
map.remove(five);
assertEquals(4, map.size());
assertFalse(map.containsKey(five));
}
/**
* remove(key,value) removes only if pair present
*/
public void testRemove2() {
ConcurrentNavigableMap map = map5();
assertTrue(map.containsKey(five));
assertEquals("E", map.get(five));
map.remove(five, "E");
assertEquals(4, map.size());
assertFalse(map.containsKey(five));
map.remove(four, "A");
assertEquals(4, map.size());
assertTrue(map.containsKey(four));
}
/**
* lowerEntry returns preceding entry.
*/
public void testLowerEntry() {
ConcurrentNavigableMap map = map5();
Map.Entry e1 = map.lowerEntry(three);
assertEquals(two, e1.getKey());
Map.Entry e2 = map.lowerEntry(six);
assertEquals(five, e2.getKey());
Map.Entry e3 = map.lowerEntry(one);
assertNull(e3);
Map.Entry e4 = map.lowerEntry(zero);
assertNull(e4);
}
/**
* higherEntry returns next entry.
*/
public void testHigherEntry() {
ConcurrentNavigableMap map = map5();
Map.Entry e1 = map.higherEntry(three);
assertEquals(four, e1.getKey());
Map.Entry e2 = map.higherEntry(zero);
assertEquals(one, e2.getKey());
Map.Entry e3 = map.higherEntry(five);
assertNull(e3);
Map.Entry e4 = map.higherEntry(six);
assertNull(e4);
}
/**
* floorEntry returns preceding entry.
*/
public void testFloorEntry() {
ConcurrentNavigableMap map = map5();
Map.Entry e1 = map.floorEntry(three);
assertEquals(three, e1.getKey());
Map.Entry e2 = map.floorEntry(six);
assertEquals(five, e2.getKey());
Map.Entry e3 = map.floorEntry(one);
assertEquals(one, e3.getKey());
Map.Entry e4 = map.floorEntry(zero);
assertNull(e4);
}
/**
* ceilingEntry returns next entry.
*/
public void testCeilingEntry() {
ConcurrentNavigableMap map = map5();
Map.Entry e1 = map.ceilingEntry(three);
assertEquals(three, e1.getKey());
Map.Entry e2 = map.ceilingEntry(zero);
assertEquals(one, e2.getKey());
Map.Entry e3 = map.ceilingEntry(five);
assertEquals(five, e3.getKey());
Map.Entry e4 = map.ceilingEntry(six);
assertNull(e4);
}
/**
* pollFirstEntry returns entries in order
*/
public void testPollFirstEntry() {
ConcurrentNavigableMap map = map5();
Map.Entry e = map.pollFirstEntry();
assertEquals(one, e.getKey());
assertEquals("A", e.getValue());
e = map.pollFirstEntry();
assertEquals(two, e.getKey());
map.put(one, "A");
e = map.pollFirstEntry();
assertEquals(one, e.getKey());
assertEquals("A", e.getValue());
e = map.pollFirstEntry();
assertEquals(three, e.getKey());
map.remove(four);
e = map.pollFirstEntry();
assertEquals(five, e.getKey());
try {
e.setValue("A");
shouldThrow();
} catch (Exception ok) {
}
e = map.pollFirstEntry();
assertNull(e);
}
/**
* pollLastEntry returns entries in order
*/
public void testPollLastEntry() {
ConcurrentNavigableMap map = map5();
Map.Entry e = map.pollLastEntry();
assertEquals(five, e.getKey());
assertEquals("E", e.getValue());
e = map.pollLastEntry();
assertEquals(four, e.getKey());
map.put(five, "E");
e = map.pollLastEntry();
assertEquals(five, e.getKey());
assertEquals("E", e.getValue());
e = map.pollLastEntry();
assertEquals(three, e.getKey());
map.remove(two);
e = map.pollLastEntry();
assertEquals(one, e.getKey());
try {
e.setValue("E");
shouldThrow();
} catch (Exception ok) {
}
e = map.pollLastEntry();
assertNull(e);
}
/**
* size returns the correct values
*/
public void testSize() {
ConcurrentNavigableMap map = map5();
ConcurrentNavigableMap empty = map0();
assertEquals(0, empty.size());
assertEquals(5, map.size());
}
/**
* toString contains toString of elements
*/
public void testToString() {
ConcurrentNavigableMap map = map5();
String s = map.toString();
for (int i = 1; i <= 5; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
// Exception tests
/**
* get(null) of nonempty map throws NPE
*/
public void testGet_NullPointerException() {
try {
ConcurrentNavigableMap c = map5();
c.get(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* containsKey(null) of nonempty map throws NPE
*/
public void testContainsKey_NullPointerException() {
try {
ConcurrentNavigableMap c = map5();
c.containsKey(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* containsValue(null) throws NPE
*/
public void testContainsValue_NullPointerException() {
try {
ConcurrentNavigableMap c = map0();
c.containsValue(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* put(null,x) throws NPE
*/
public void testPut1_NullPointerException() {
try {
ConcurrentNavigableMap c = map5();
c.put(null, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* putIfAbsent(null, x) throws NPE
*/
public void testPutIfAbsent1_NullPointerException() {
try {
ConcurrentNavigableMap c = map5();
c.putIfAbsent(null, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* replace(null, x) throws NPE
*/
public void testReplace_NullPointerException() {
try {
ConcurrentNavigableMap c = map5();
c.replace(null, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* replace(null, x, y) throws NPE
*/
public void testReplaceValue_NullPointerException() {
try {
ConcurrentNavigableMap c = map5();
c.replace(null, one, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* remove(null) throws NPE
*/
public void testRemove1_NullPointerException() {
try {
ConcurrentNavigableMap c = map5();
c.remove(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* remove(null, x) throws NPE
*/
public void testRemove2_NullPointerException() {
try {
ConcurrentNavigableMap c = map5();
c.remove(null, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* A deserialized map equals original
*/
public void testSerialization() {
ConcurrentNavigableMap q = map5();
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
ConcurrentNavigableMap r = (ConcurrentNavigableMap)in.readObject();
assertEquals(q.size(), r.size());
assertTrue(q.equals(r));
assertTrue(r.equals(q));
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* subMap returns map with keys in requested range
*/
public void testSubMapContents() {
ConcurrentNavigableMap map = map5();
SortedMap sm = map.subMap(two, four);
assertEquals(two, sm.firstKey());
assertEquals(three, sm.lastKey());
assertEquals(2, sm.size());
assertFalse(sm.containsKey(one));
assertTrue(sm.containsKey(two));
assertTrue(sm.containsKey(three));
assertFalse(sm.containsKey(four));
assertFalse(sm.containsKey(five));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
assertFalse(i.hasNext());
Iterator j = sm.keySet().iterator();
j.next();
j.remove();
assertFalse(map.containsKey(two));
assertEquals(4, map.size());
assertEquals(1, sm.size());
assertEquals(three, sm.firstKey());
assertEquals(three, sm.lastKey());
assertTrue(sm.remove(three) != null);
assertTrue(sm.isEmpty());
assertEquals(3, map.size());
}
public void testSubMapContents2() {
ConcurrentNavigableMap map = map5();
SortedMap sm = map.subMap(two, three);
assertEquals(1, sm.size());
assertEquals(two, sm.firstKey());
assertEquals(two, sm.lastKey());
assertFalse(sm.containsKey(one));
assertTrue(sm.containsKey(two));
assertFalse(sm.containsKey(three));
assertFalse(sm.containsKey(four));
assertFalse(sm.containsKey(five));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
assertFalse(i.hasNext());
Iterator j = sm.keySet().iterator();
j.next();
j.remove();
assertFalse(map.containsKey(two));
assertEquals(4, map.size());
assertEquals(0, sm.size());
assertTrue(sm.isEmpty());
assertTrue(sm.remove(three) == null);
assertEquals(4, map.size());
}
/**
* headMap returns map with keys in requested range
*/
public void testHeadMapContents() {
ConcurrentNavigableMap map = map5();
SortedMap sm = map.headMap(four);
assertTrue(sm.containsKey(one));
assertTrue(sm.containsKey(two));
assertTrue(sm.containsKey(three));
assertFalse(sm.containsKey(four));
assertFalse(sm.containsKey(five));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(one, k);
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
assertFalse(i.hasNext());
sm.clear();
assertTrue(sm.isEmpty());
assertEquals(2, map.size());
assertEquals(four, map.firstKey());
}
/**
* headMap returns map with keys in requested range
*/
public void testTailMapContents() {
ConcurrentNavigableMap map = map5();
SortedMap sm = map.tailMap(two);
assertFalse(sm.containsKey(one));
assertTrue(sm.containsKey(two));
assertTrue(sm.containsKey(three));
assertTrue(sm.containsKey(four));
assertTrue(sm.containsKey(five));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
k = (Integer)(i.next());
assertEquals(four, k);
k = (Integer)(i.next());
assertEquals(five, k);
assertFalse(i.hasNext());
Iterator ei = sm.entrySet().iterator();
Map.Entry e;
e = (Map.Entry)(ei.next());
assertEquals(two, e.getKey());
assertEquals("B", e.getValue());
e = (Map.Entry)(ei.next());
assertEquals(three, e.getKey());
assertEquals("C", e.getValue());
e = (Map.Entry)(ei.next());
assertEquals(four, e.getKey());
assertEquals("D", e.getValue());
e = (Map.Entry)(ei.next());
assertEquals(five, e.getKey());
assertEquals("E", e.getValue());
assertFalse(i.hasNext());
SortedMap ssm = sm.tailMap(four);
assertEquals(four, ssm.firstKey());
assertEquals(five, ssm.lastKey());
assertTrue(ssm.remove(four) != null);
assertEquals(1, ssm.size());
assertEquals(3, sm.size());
assertEquals(4, map.size());
}
/**
* clear removes all pairs
*/
public void testDescendingClear() {
ConcurrentNavigableMap map = dmap5();
map.clear();
assertEquals(map.size(), 0);
}
/**
* Maps with same contents are equal
*/
public void testDescendingEquals() {
ConcurrentNavigableMap map1 = dmap5();
ConcurrentNavigableMap map2 = dmap5();
assertEquals(map1, map2);
assertEquals(map2, map1);
map1.clear();
assertFalse(map1.equals(map2));
assertFalse(map2.equals(map1));
}
/**
* containsKey returns true for contained key
*/
public void testDescendingContainsKey() {
ConcurrentNavigableMap map = dmap5();
assertTrue(map.containsKey(m1));
assertFalse(map.containsKey(zero));
}
/**
* containsValue returns true for held values
*/
public void testDescendingContainsValue() {
ConcurrentNavigableMap map = dmap5();
assertTrue(map.containsValue("A"));
assertFalse(map.containsValue("Z"));
}
/**
* get returns the correct element at the given key,
* or null if not present
*/
public void testDescendingGet() {
ConcurrentNavigableMap map = dmap5();
assertEquals("A", (String)map.get(m1));
ConcurrentNavigableMap empty = dmap0();
assertNull(empty.get(m1));
}
/**
* isEmpty is true of empty map and false for non-empty
*/
public void testDescendingIsEmpty() {
ConcurrentNavigableMap empty = dmap0();
ConcurrentNavigableMap map = dmap5();
assertTrue(empty.isEmpty());
assertFalse(map.isEmpty());
}
/**
* firstKey returns first key
*/
public void testDescendingFirstKey() {
ConcurrentNavigableMap map = dmap5();
assertEquals(m1, map.firstKey());
}
/**
* lastKey returns last key
*/
public void testDescendingLastKey() {
ConcurrentNavigableMap map = dmap5();
assertEquals(m5, map.lastKey());
}
/**
* keySet returns a Set containing all the keys
*/
public void testDescendingKeySet() {
ConcurrentNavigableMap map = dmap5();
Set s = map.keySet();
assertEquals(5, s.size());
assertTrue(s.contains(m1));
assertTrue(s.contains(m2));
assertTrue(s.contains(m3));
assertTrue(s.contains(m4));
assertTrue(s.contains(m5));
}
/**
* keySet is ordered
*/
public void testDescendingKeySetOrder() {
ConcurrentNavigableMap map = dmap5();
Set s = map.keySet();
Iterator i = s.iterator();
Integer last = (Integer)i.next();
assertEquals(last, m1);
while (i.hasNext()) {
Integer k = (Integer)i.next();
assertTrue(last.compareTo(k) > 0);
last = k;
}
}
/**
* values collection contains all values
*/
public void testDescendingValues() {
ConcurrentNavigableMap map = dmap5();
Collection s = map.values();
assertEquals(5, s.size());
assertTrue(s.contains("A"));
assertTrue(s.contains("B"));
assertTrue(s.contains("C"));
assertTrue(s.contains("D"));
assertTrue(s.contains("E"));
}
/**
* keySet.toArray returns contains all keys
*/
public void testDescendingAscendingKeySetToArray() {
ConcurrentNavigableMap map = dmap5();
Set s = map.keySet();
Object[] ar = s.toArray();
assertTrue(s.containsAll(Arrays.asList(ar)));
assertEquals(5, ar.length);
ar[0] = m10;
assertFalse(s.containsAll(Arrays.asList(ar)));
}
/**
* descendingkeySet.toArray returns contains all keys
*/
public void testDescendingDescendingKeySetToArray() {
ConcurrentNavigableMap map = dmap5();
Set s = map.descendingKeySet();
Object[] ar = s.toArray();
assertEquals(5, ar.length);
assertTrue(s.containsAll(Arrays.asList(ar)));
ar[0] = m10;
assertFalse(s.containsAll(Arrays.asList(ar)));
}
/**
* Values.toArray contains all values
*/
public void testDescendingValuesToArray() {
ConcurrentNavigableMap map = dmap5();
Collection v = map.values();
Object[] ar = v.toArray();
ArrayList s = new ArrayList(Arrays.asList(ar));
assertEquals(5, ar.length);
assertTrue(s.contains("A"));
assertTrue(s.contains("B"));
assertTrue(s.contains("C"));
assertTrue(s.contains("D"));
assertTrue(s.contains("E"));
}
/**
* entrySet contains all pairs
*/
public void testDescendingEntrySet() {
ConcurrentNavigableMap map = dmap5();
Set s = map.entrySet();
assertEquals(5, s.size());
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
assertTrue(
(e.getKey().equals(m1) && e.getValue().equals("A")) ||
(e.getKey().equals(m2) && e.getValue().equals("B")) ||
(e.getKey().equals(m3) && e.getValue().equals("C")) ||
(e.getKey().equals(m4) && e.getValue().equals("D")) ||
(e.getKey().equals(m5) && e.getValue().equals("E")));
}
}
/**
* putAll adds all key-value pairs from the given map
*/
public void testDescendingPutAll() {
ConcurrentNavigableMap empty = dmap0();
ConcurrentNavigableMap map = dmap5();
empty.putAll(map);
assertEquals(5, empty.size());
assertTrue(empty.containsKey(m1));
assertTrue(empty.containsKey(m2));
assertTrue(empty.containsKey(m3));
assertTrue(empty.containsKey(m4));
assertTrue(empty.containsKey(m5));
}
/**
* putIfAbsent works when the given key is not present
*/
public void testDescendingPutIfAbsent() {
ConcurrentNavigableMap map = dmap5();
map.putIfAbsent(six, "Z");
assertTrue(map.containsKey(six));
}
/**
* putIfAbsent does not add the pair if the key is already present
*/
public void testDescendingPutIfAbsent2() {
ConcurrentNavigableMap map = dmap5();
assertEquals("A", map.putIfAbsent(m1, "Z"));
}
/**
* replace fails when the given key is not present
*/
public void testDescendingReplace() {
ConcurrentNavigableMap map = dmap5();
assertNull(map.replace(six, "Z"));
assertFalse(map.containsKey(six));
}
/**
* replace succeeds if the key is already present
*/
public void testDescendingReplace2() {
ConcurrentNavigableMap map = dmap5();
assertNotNull(map.replace(m1, "Z"));
assertEquals("Z", map.get(m1));
}
/**
* replace value fails when the given key not mapped to expected value
*/
public void testDescendingReplaceValue() {
ConcurrentNavigableMap map = dmap5();
assertEquals("A", map.get(m1));
assertFalse(map.replace(m1, "Z", "Z"));
assertEquals("A", map.get(m1));
}
/**
* replace value succeeds when the given key mapped to expected value
*/
public void testDescendingReplaceValue2() {
ConcurrentNavigableMap map = dmap5();
assertEquals("A", map.get(m1));
assertTrue(map.replace(m1, "A", "Z"));
assertEquals("Z", map.get(m1));
}
/**
* remove removes the correct key-value pair from the map
*/
public void testDescendingRemove() {
ConcurrentNavigableMap map = dmap5();
map.remove(m5);
assertEquals(4, map.size());
assertFalse(map.containsKey(m5));
}
/**
* remove(key,value) removes only if pair present
*/
public void testDescendingRemove2() {
ConcurrentNavigableMap map = dmap5();
assertTrue(map.containsKey(m5));
assertEquals("E", map.get(m5));
map.remove(m5, "E");
assertEquals(4, map.size());
assertFalse(map.containsKey(m5));
map.remove(m4, "A");
assertEquals(4, map.size());
assertTrue(map.containsKey(m4));
}
/**
* lowerEntry returns preceding entry.
*/
public void testDescendingLowerEntry() {
ConcurrentNavigableMap map = dmap5();
Map.Entry e1 = map.lowerEntry(m3);
assertEquals(m2, e1.getKey());
Map.Entry e2 = map.lowerEntry(m6);
assertEquals(m5, e2.getKey());
Map.Entry e3 = map.lowerEntry(m1);
assertNull(e3);
Map.Entry e4 = map.lowerEntry(zero);
assertNull(e4);
}
/**
* higherEntry returns next entry.
*/
public void testDescendingHigherEntry() {
ConcurrentNavigableMap map = dmap5();
Map.Entry e1 = map.higherEntry(m3);
assertEquals(m4, e1.getKey());
Map.Entry e2 = map.higherEntry(zero);
assertEquals(m1, e2.getKey());
Map.Entry e3 = map.higherEntry(m5);
assertNull(e3);
Map.Entry e4 = map.higherEntry(m6);
assertNull(e4);
}
/**
* floorEntry returns preceding entry.
*/
public void testDescendingFloorEntry() {
ConcurrentNavigableMap map = dmap5();
Map.Entry e1 = map.floorEntry(m3);
assertEquals(m3, e1.getKey());
Map.Entry e2 = map.floorEntry(m6);
assertEquals(m5, e2.getKey());
Map.Entry e3 = map.floorEntry(m1);
assertEquals(m1, e3.getKey());
Map.Entry e4 = map.floorEntry(zero);
assertNull(e4);
}
/**
* ceilingEntry returns next entry.
*/
public void testDescendingCeilingEntry() {
ConcurrentNavigableMap map = dmap5();
Map.Entry e1 = map.ceilingEntry(m3);
assertEquals(m3, e1.getKey());
Map.Entry e2 = map.ceilingEntry(zero);
assertEquals(m1, e2.getKey());
Map.Entry e3 = map.ceilingEntry(m5);
assertEquals(m5, e3.getKey());
Map.Entry e4 = map.ceilingEntry(m6);
assertNull(e4);
}
/**
* pollFirstEntry returns entries in order
*/
public void testDescendingPollFirstEntry() {
ConcurrentNavigableMap map = dmap5();
Map.Entry e = map.pollFirstEntry();
assertEquals(m1, e.getKey());
assertEquals("A", e.getValue());
e = map.pollFirstEntry();
assertEquals(m2, e.getKey());
map.put(m1, "A");
e = map.pollFirstEntry();
assertEquals(m1, e.getKey());
assertEquals("A", e.getValue());
e = map.pollFirstEntry();
assertEquals(m3, e.getKey());
map.remove(m4);
e = map.pollFirstEntry();
assertEquals(m5, e.getKey());
try {
e.setValue("A");
shouldThrow();
} catch (Exception ok) {
}
e = map.pollFirstEntry();
assertNull(e);
}
/**
* pollLastEntry returns entries in order
*/
public void testDescendingPollLastEntry() {
ConcurrentNavigableMap map = dmap5();
Map.Entry e = map.pollLastEntry();
assertEquals(m5, e.getKey());
assertEquals("E", e.getValue());
e = map.pollLastEntry();
assertEquals(m4, e.getKey());
map.put(m5, "E");
e = map.pollLastEntry();
assertEquals(m5, e.getKey());
assertEquals("E", e.getValue());
e = map.pollLastEntry();
assertEquals(m3, e.getKey());
map.remove(m2);
e = map.pollLastEntry();
assertEquals(m1, e.getKey());
try {
e.setValue("E");
shouldThrow();
} catch (Exception ok) {
}
e = map.pollLastEntry();
assertNull(e);
}
/**
* size returns the correct values
*/
public void testDescendingSize() {
ConcurrentNavigableMap map = dmap5();
ConcurrentNavigableMap empty = dmap0();
assertEquals(0, empty.size());
assertEquals(5, map.size());
}
/**
* toString contains toString of elements
*/
public void testDescendingToString() {
ConcurrentNavigableMap map = dmap5();
String s = map.toString();
for (int i = 1; i <= 5; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
// Exception testDescendings
/**
* get(null) of nm1mpty map throws NPE
*/
public void testDescendingGet_NullPointerException() {
try {
ConcurrentNavigableMap c = dmap5();
c.get(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* containsKey(null) of nm1mpty map throws NPE
*/
public void testDescendingContainsKey_NullPointerException() {
try {
ConcurrentNavigableMap c = dmap5();
c.containsKey(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* containsValue(null) throws NPE
*/
public void testDescendingContainsValue_NullPointerException() {
try {
ConcurrentNavigableMap c = dmap0();
c.containsValue(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* put(null,x) throws NPE
*/
public void testDescendingPut1_NullPointerException() {
try {
ConcurrentNavigableMap c = dmap5();
c.put(null, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* putIfAbsent(null, x) throws NPE
*/
public void testDescendingPutIfAbsent1_NullPointerException() {
try {
ConcurrentNavigableMap c = dmap5();
c.putIfAbsent(null, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* replace(null, x) throws NPE
*/
public void testDescendingReplace_NullPointerException() {
try {
ConcurrentNavigableMap c = dmap5();
c.replace(null, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* replace(null, x, y) throws NPE
*/
public void testDescendingReplaceValue_NullPointerException() {
try {
ConcurrentNavigableMap c = dmap5();
c.replace(null, m1, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* remove(null) throws NPE
*/
public void testDescendingRemove1_NullPointerException() {
try {
ConcurrentNavigableMap c = dmap5();
c.remove(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* remove(null, x) throws NPE
*/
public void testDescendingRemove2_NullPointerException() {
try {
ConcurrentNavigableMap c = dmap5();
c.remove(null, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* A deserialized map equals original
*/
public void testDescendingSerialization() {
ConcurrentNavigableMap q = dmap5();
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
ConcurrentNavigableMap r = (ConcurrentNavigableMap)in.readObject();
assertEquals(q.size(), r.size());
assertTrue(q.equals(r));
assertTrue(r.equals(q));
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* subMap returns map with keys in requested range
*/
public void testDescendingSubMapContents() {
ConcurrentNavigableMap map = dmap5();
SortedMap sm = map.subMap(m2, m4);
assertEquals(m2, sm.firstKey());
assertEquals(m3, sm.lastKey());
assertEquals(2, sm.size());
assertFalse(sm.containsKey(m1));
assertTrue(sm.containsKey(m2));
assertTrue(sm.containsKey(m3));
assertFalse(sm.containsKey(m4));
assertFalse(sm.containsKey(m5));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(m2, k);
k = (Integer)(i.next());
assertEquals(m3, k);
assertFalse(i.hasNext());
Iterator j = sm.keySet().iterator();
j.next();
j.remove();
assertFalse(map.containsKey(m2));
assertEquals(4, map.size());
assertEquals(1, sm.size());
assertEquals(m3, sm.firstKey());
assertEquals(m3, sm.lastKey());
assertTrue(sm.remove(m3) != null);
assertTrue(sm.isEmpty());
assertEquals(3, map.size());
}
public void testDescendingSubMapContents2() {
ConcurrentNavigableMap map = dmap5();
SortedMap sm = map.subMap(m2, m3);
assertEquals(1, sm.size());
assertEquals(m2, sm.firstKey());
assertEquals(m2, sm.lastKey());
assertFalse(sm.containsKey(m1));
assertTrue(sm.containsKey(m2));
assertFalse(sm.containsKey(m3));
assertFalse(sm.containsKey(m4));
assertFalse(sm.containsKey(m5));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(m2, k);
assertFalse(i.hasNext());
Iterator j = sm.keySet().iterator();
j.next();
j.remove();
assertFalse(map.containsKey(m2));
assertEquals(4, map.size());
assertEquals(0, sm.size());
assertTrue(sm.isEmpty());
assertTrue(sm.remove(m3) == null);
assertEquals(4, map.size());
}
/**
* headMap returns map with keys in requested range
*/
public void testDescendingHeadMapContents() {
ConcurrentNavigableMap map = dmap5();
SortedMap sm = map.headMap(m4);
assertTrue(sm.containsKey(m1));
assertTrue(sm.containsKey(m2));
assertTrue(sm.containsKey(m3));
assertFalse(sm.containsKey(m4));
assertFalse(sm.containsKey(m5));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(m1, k);
k = (Integer)(i.next());
assertEquals(m2, k);
k = (Integer)(i.next());
assertEquals(m3, k);
assertFalse(i.hasNext());
sm.clear();
assertTrue(sm.isEmpty());
assertEquals(2, map.size());
assertEquals(m4, map.firstKey());
}
/**
* headMap returns map with keys in requested range
*/
public void testDescendingTailMapContents() {
ConcurrentNavigableMap map = dmap5();
SortedMap sm = map.tailMap(m2);
assertFalse(sm.containsKey(m1));
assertTrue(sm.containsKey(m2));
assertTrue(sm.containsKey(m3));
assertTrue(sm.containsKey(m4));
assertTrue(sm.containsKey(m5));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(m2, k);
k = (Integer)(i.next());
assertEquals(m3, k);
k = (Integer)(i.next());
assertEquals(m4, k);
k = (Integer)(i.next());
assertEquals(m5, k);
assertFalse(i.hasNext());
Iterator ei = sm.entrySet().iterator();
Map.Entry e;
e = (Map.Entry)(ei.next());
assertEquals(m2, e.getKey());
assertEquals("B", e.getValue());
e = (Map.Entry)(ei.next());
assertEquals(m3, e.getKey());
assertEquals("C", e.getValue());
e = (Map.Entry)(ei.next());
assertEquals(m4, e.getKey());
assertEquals("D", e.getValue());
e = (Map.Entry)(ei.next());
assertEquals(m5, e.getKey());
assertEquals("E", e.getValue());
assertFalse(i.hasNext());
SortedMap ssm = sm.tailMap(m4);
assertEquals(m4, ssm.firstKey());
assertEquals(m5, ssm.lastKey());
assertTrue(ssm.remove(m4) != null);
assertEquals(1, ssm.size());
assertEquals(3, sm.size());
assertEquals(4, map.size());
}
}
backport-util-concurrent-3.1-src/test/tck/src/ConcurrentLinkedQueueTest.java 0000644 0017507 0003772 00000035774 10431260156 026234 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import java.util.Collection;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Iterator;
import java.util.ConcurrentModificationException;
import java.io.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
public class ConcurrentLinkedQueueTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(ConcurrentLinkedQueueTest.class);
}
/**
* Create a queue of given size containing consecutive
* Integers 0 ... n.
*/
private ConcurrentLinkedQueue populatedQueue(int n) {
ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
assertTrue(q.isEmpty());
for(int i = 0; i < n; ++i)
assertTrue(q.offer(new Integer(i)));
assertFalse(q.isEmpty());
assertEquals(n, q.size());
return q;
}
/**
* new queue is empty
*/
public void testConstructor1() {
assertEquals(0, new ConcurrentLinkedQueue().size());
}
/**
* Initializing from null Collection throws NPE
*/
public void testConstructor3() {
try {
ConcurrentLinkedQueue q = new ConcurrentLinkedQueue((Collection)null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from Collection of null elements throws NPE
*/
public void testConstructor4() {
try {
Integer[] ints = new Integer[SIZE];
ConcurrentLinkedQueue q = new ConcurrentLinkedQueue(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from Collection with some null elements throws NPE
*/
public void testConstructor5() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
ConcurrentLinkedQueue q = new ConcurrentLinkedQueue(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Queue contains all elements of collection used to initialize
*/
public void testConstructor6() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
ConcurrentLinkedQueue q = new ConcurrentLinkedQueue(Arrays.asList(ints));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* isEmpty is true before add, false after
*/
public void testEmpty() {
ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
assertTrue(q.isEmpty());
q.add(one);
assertFalse(q.isEmpty());
q.add(two);
q.remove();
q.remove();
assertTrue(q.isEmpty());
}
/**
* size changes when elements added and removed
*/
public void testSize() {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i, q.size());
q.remove();
}
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
q.add(new Integer(i));
}
}
/**
* offer(null) throws NPE
*/
public void testOfferNull() {
try {
ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
q.offer(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* add(null) throws NPE
*/
public void testAddNull() {
try {
ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
q.add(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* Offer returns true
*/
public void testOffer() {
ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
assertTrue(q.offer(zero));
assertTrue(q.offer(one));
}
/**
* add returns true
*/
public void testAdd() {
ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
assertTrue(q.add(new Integer(i)));
}
}
/**
* addAll(null) throws NPE
*/
public void testAddAll1() {
try {
ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
q.addAll(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll(this) throws IAE
*/
public void testAddAllSelf() {
try {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
q.addAll(q);
shouldThrow();
}
catch (IllegalArgumentException success) {}
}
/**
* addAll of a collection with null elements throws NPE
*/
public void testAddAll2() {
try {
ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
Integer[] ints = new Integer[SIZE];
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with any null elements throws NPE after
* possibly adding some elements
*/
public void testAddAll3() {
try {
ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Queue contains all elements, in traversal order, of successful addAll
*/
public void testAddAll5() {
try {
Integer[] empty = new Integer[0];
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
assertFalse(q.addAll(Arrays.asList(empty)));
assertTrue(q.addAll(Arrays.asList(ints)));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* poll succeeds unless empty
*/
public void testPoll() {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.poll()).intValue());
}
assertNull(q.poll());
}
/**
* peek returns next element, or null if empty
*/
public void testPeek() {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.peek()).intValue());
q.poll();
assertTrue(q.peek() == null ||
i != ((Integer)q.peek()).intValue());
}
assertNull(q.peek());
}
/**
* element returns next element, or throws NSEE if empty
*/
public void testElement() {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.element()).intValue());
q.poll();
}
try {
q.element();
shouldThrow();
}
catch (NoSuchElementException success) {}
}
/**
* remove removes next element, or throws NSEE if empty
*/
public void testRemove() {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.remove()).intValue());
}
try {
q.remove();
shouldThrow();
} catch (NoSuchElementException success){
}
}
/**
* remove(x) removes x and returns true if present
*/
public void testRemoveElement() {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
assertFalse(q.remove(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* contains(x) reports true when elements added but not yet removed
*/
public void testContains() {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.contains(new Integer(i)));
q.poll();
assertFalse(q.contains(new Integer(i)));
}
}
/**
* clear removes all elements
*/
public void testClear() {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
q.clear();
assertTrue(q.isEmpty());
assertEquals(0, q.size());
q.add(one);
assertFalse(q.isEmpty());
q.clear();
assertTrue(q.isEmpty());
}
/**
* containsAll(c) is true when c contains a subset of elements
*/
public void testContainsAll() {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
ConcurrentLinkedQueue p = new ConcurrentLinkedQueue();
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.containsAll(p));
assertFalse(p.containsAll(q));
p.add(new Integer(i));
}
assertTrue(p.containsAll(q));
}
/**
* retainAll(c) retains only those elements of c and reports true if change
*/
public void testRetainAll() {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
ConcurrentLinkedQueue p = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
boolean changed = q.retainAll(p);
if (i == 0)
assertFalse(changed);
else
assertTrue(changed);
assertTrue(q.containsAll(p));
assertEquals(SIZE-i, q.size());
p.remove();
}
}
/**
* removeAll(c) removes only those elements of c and reports true if changed
*/
public void testRemoveAll() {
for (int i = 1; i < SIZE; ++i) {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
ConcurrentLinkedQueue p = populatedQueue(i);
assertTrue(q.removeAll(p));
assertEquals(SIZE-i, q.size());
for (int j = 0; j < i; ++j) {
Integer I = (Integer)(p.remove());
assertFalse(q.contains(I));
}
}
}
/**
* toArray contains all elements
*/
public void testToArray() {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
Object[] o = q.toArray();
Arrays.sort(o);
for(int i = 0; i < o.length; i++)
assertEquals(o[i], q.poll());
}
/**
* toArray(a) contains all elements
*/
public void testToArray2() {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
Integer[] ints = new Integer[SIZE];
ints = (Integer[])q.toArray(ints);
Arrays.sort(ints);
for(int i = 0; i < ints.length; i++)
assertEquals(ints[i], q.poll());
}
/**
* toArray(null) throws NPE
*/
public void testToArray_BadArg() {
try {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
Object o[] = q.toArray(null);
shouldThrow();
} catch(NullPointerException success){}
}
/**
* toArray with incompatible array type throws CCE
*/
public void testToArray1_BadArg() {
try {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
Object o[] = q.toArray(new String[10] );
shouldThrow();
} catch(ArrayStoreException success){}
}
/**
* iterator iterates through all elements
*/
public void testIterator() {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, SIZE);
}
/**
* iterator ordering is FIFO
*/
public void testIteratorOrdering() {
final ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
q.add(one);
q.add(two);
q.add(three);
int k = 0;
for (Iterator it = q.iterator(); it.hasNext();) {
int i = ((Integer)(it.next())).intValue();
assertEquals(++k, i);
}
assertEquals(3, k);
}
/**
* Modifications do not cause iterators to fail
*/
public void testWeaklyConsistentIteration () {
final ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
q.add(one);
q.add(two);
q.add(three);
try {
for (Iterator it = q.iterator(); it.hasNext();) {
q.remove();
it.next();
}
}
catch (ConcurrentModificationException e) {
shouldThrow();
}
assertEquals("queue should be empty again", 0, q.size());
}
/**
* iterator.remove removes current element
*/
public void testIteratorRemove () {
final ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
q.add(one);
q.add(two);
q.add(three);
Iterator it = q.iterator();
it.next();
it.remove();
it = q.iterator();
assertEquals(it.next(), two);
assertEquals(it.next(), three);
assertFalse(it.hasNext());
}
/**
* toString contains toStrings of elements
*/
public void testToString() {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
String s = q.toString();
for (int i = 0; i < SIZE; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
/**
* A deserialized serialized queue has same elements in same order
*/
public void testSerialization() {
ConcurrentLinkedQueue q = populatedQueue(SIZE);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
ConcurrentLinkedQueue r = (ConcurrentLinkedQueue)in.readObject();
assertEquals(q.size(), r.size());
while (!q.isEmpty())
assertEquals(q.remove(), r.remove());
} catch(Exception e){
unexpectedException();
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/ConcurrentSkipListSetTest.java 0000644 0017507 0003772 00000074655 10431777323 026251 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import junit.framework.*;
import java.util.Comparator;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.SortedSet;
import java.io.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.util.Random;
import java.util.BitSet;
import java.util.NoSuchElementException;
public class ConcurrentSkipListSetTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(ConcurrentSkipListSetTest.class);
}
static class MyReverseComparator implements Comparator {
public int compare(Object x, Object y) {
int i = ((Integer)x).intValue();
int j = ((Integer)y).intValue();
if (i < j) return 1;
if (i > j) return -1;
return 0;
}
}
/**
* Create a set of given size containing consecutive
* Integers 0 ... n.
*/
private ConcurrentSkipListSet populatedSet(int n) {
ConcurrentSkipListSet q = new ConcurrentSkipListSet();
assertTrue(q.isEmpty());
for(int i = n-1; i >= 0; i-=2)
assertTrue(q.add(new Integer(i)));
for(int i = (n & 1); i < n; i+=2)
assertTrue(q.add(new Integer(i)));
assertFalse(q.isEmpty());
assertEquals(n, q.size());
return q;
}
/**
* Create set of first 5 ints
*/
private ConcurrentSkipListSet set5() {
ConcurrentSkipListSet q = new ConcurrentSkipListSet();
assertTrue(q.isEmpty());
q.add(one);
q.add(two);
q.add(three);
q.add(four);
q.add(five);
assertEquals(5, q.size());
return q;
}
/**
* A new set has unbounded capacity
*/
public void testConstructor1() {
assertEquals(0, new ConcurrentSkipListSet().size());
}
/**
* Initializing from null Collection throws NPE
*/
public void testConstructor3() {
try {
ConcurrentSkipListSet q = new ConcurrentSkipListSet((Collection)null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from Collection of null elements throws NPE
*/
public void testConstructor4() {
try {
Integer[] ints = new Integer[SIZE];
ConcurrentSkipListSet q = new ConcurrentSkipListSet(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from Collection with some null elements throws NPE
*/
public void testConstructor5() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
ConcurrentSkipListSet q = new ConcurrentSkipListSet(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Set contains all elements of collection used to initialize
*/
public void testConstructor6() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
ConcurrentSkipListSet q = new ConcurrentSkipListSet(Arrays.asList(ints));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.pollFirst());
}
finally {}
}
/**
* The comparator used in constructor is used
*/
public void testConstructor7() {
try {
MyReverseComparator cmp = new MyReverseComparator();
ConcurrentSkipListSet q = new ConcurrentSkipListSet(cmp);
assertEquals(cmp, q.comparator());
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
for (int i = SIZE-1; i >= 0; --i)
assertEquals(ints[i], q.pollFirst());
}
finally {}
}
/**
* isEmpty is true before add, false after
*/
public void testEmpty() {
ConcurrentSkipListSet q = new ConcurrentSkipListSet();
assertTrue(q.isEmpty());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.add(new Integer(2));
q.pollFirst();
q.pollFirst();
assertTrue(q.isEmpty());
}
/**
* size changes when elements added and removed
*/
public void testSize() {
ConcurrentSkipListSet q = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i, q.size());
q.pollFirst();
}
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
q.add(new Integer(i));
}
}
/**
* add(null) throws NPE
*/
public void testAddNull() {
try {
ConcurrentSkipListSet q = new ConcurrentSkipListSet();
q.add(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* Add of comparable element succeeds
*/
public void testAdd() {
ConcurrentSkipListSet q = new ConcurrentSkipListSet();
assertTrue(q.add(zero));
assertTrue(q.add(one));
}
/**
* Add of duplicate element fails
*/
public void testAddDup() {
ConcurrentSkipListSet q = new ConcurrentSkipListSet();
assertTrue(q.add(zero));
assertFalse(q.add(zero));
}
/**
* Add of non-Comparable throws CCE
*/
public void testAddNonComparable() {
try {
ConcurrentSkipListSet q = new ConcurrentSkipListSet();
q.add(new Object());
q.add(new Object());
q.add(new Object());
shouldThrow();
}
catch(ClassCastException success) {}
}
/**
* addAll(null) throws NPE
*/
public void testAddAll1() {
try {
ConcurrentSkipListSet q = new ConcurrentSkipListSet();
q.addAll(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with null elements throws NPE
*/
public void testAddAll2() {
try {
ConcurrentSkipListSet q = new ConcurrentSkipListSet();
Integer[] ints = new Integer[SIZE];
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with any null elements throws NPE after
* possibly adding some elements
*/
public void testAddAll3() {
try {
ConcurrentSkipListSet q = new ConcurrentSkipListSet();
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Set contains all elements of successful addAll
*/
public void testAddAll5() {
try {
Integer[] empty = new Integer[0];
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(SIZE-1-i);
ConcurrentSkipListSet q = new ConcurrentSkipListSet();
assertFalse(q.addAll(Arrays.asList(empty)));
assertTrue(q.addAll(Arrays.asList(ints)));
for (int i = 0; i < SIZE; ++i)
assertEquals(new Integer(i), q.pollFirst());
}
finally {}
}
/**
* pollFirst succeeds unless empty
*/
public void testPollFirst() {
ConcurrentSkipListSet q = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.pollFirst()).intValue());
}
assertNull(q.pollFirst());
}
/**
* pollLast succeeds unless empty
*/
public void testPollLast() {
ConcurrentSkipListSet q = populatedSet(SIZE);
for (int i = SIZE-1; i >= 0; --i) {
assertEquals(i, ((Integer)q.pollLast()).intValue());
}
assertNull(q.pollFirst());
}
/**
* remove(x) removes x and returns true if present
*/
public void testRemoveElement() {
ConcurrentSkipListSet q = populatedSet(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
assertFalse(q.remove(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* contains(x) reports true when elements added but not yet removed
*/
public void testContains() {
ConcurrentSkipListSet q = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.contains(new Integer(i)));
q.pollFirst();
assertFalse(q.contains(new Integer(i)));
}
}
/**
* clear removes all elements
*/
public void testClear() {
ConcurrentSkipListSet q = populatedSet(SIZE);
q.clear();
assertTrue(q.isEmpty());
assertEquals(0, q.size());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.clear();
assertTrue(q.isEmpty());
}
/**
* containsAll(c) is true when c contains a subset of elements
*/
public void testContainsAll() {
ConcurrentSkipListSet q = populatedSet(SIZE);
ConcurrentSkipListSet p = new ConcurrentSkipListSet();
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.containsAll(p));
assertFalse(p.containsAll(q));
p.add(new Integer(i));
}
assertTrue(p.containsAll(q));
}
/**
* retainAll(c) retains only those elements of c and reports true if changed
*/
public void testRetainAll() {
ConcurrentSkipListSet q = populatedSet(SIZE);
ConcurrentSkipListSet p = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
boolean changed = q.retainAll(p);
if (i == 0)
assertFalse(changed);
else
assertTrue(changed);
assertTrue(q.containsAll(p));
assertEquals(SIZE-i, q.size());
p.pollFirst();
}
}
/**
* removeAll(c) removes only those elements of c and reports true if changed
*/
public void testRemoveAll() {
for (int i = 1; i < SIZE; ++i) {
ConcurrentSkipListSet q = populatedSet(SIZE);
ConcurrentSkipListSet p = populatedSet(i);
assertTrue(q.removeAll(p));
assertEquals(SIZE-i, q.size());
for (int j = 0; j < i; ++j) {
Integer I = (Integer)(p.pollFirst());
assertFalse(q.contains(I));
}
}
}
/**
* lower returns preceding element
*/
public void testLower() {
ConcurrentSkipListSet q = set5();
Object e1 = q.lower(three);
assertEquals(two, e1);
Object e2 = q.lower(six);
assertEquals(five, e2);
Object e3 = q.lower(one);
assertNull(e3);
Object e4 = q.lower(zero);
assertNull(e4);
}
/**
* higher returns next element
*/
public void testHigher() {
ConcurrentSkipListSet q = set5();
Object e1 = q.higher(three);
assertEquals(four, e1);
Object e2 = q.higher(zero);
assertEquals(one, e2);
Object e3 = q.higher(five);
assertNull(e3);
Object e4 = q.higher(six);
assertNull(e4);
}
/**
* floor returns preceding element
*/
public void testFloor() {
ConcurrentSkipListSet q = set5();
Object e1 = q.floor(three);
assertEquals(three, e1);
Object e2 = q.floor(six);
assertEquals(five, e2);
Object e3 = q.floor(one);
assertEquals(one, e3);
Object e4 = q.floor(zero);
assertNull(e4);
}
/**
* ceiling returns next element
*/
public void testCeiling() {
ConcurrentSkipListSet q = set5();
Object e1 = q.ceiling(three);
assertEquals(three, e1);
Object e2 = q.ceiling(zero);
assertEquals(one, e2);
Object e3 = q.ceiling(five);
assertEquals(five, e3);
Object e4 = q.ceiling(six);
assertNull(e4);
}
/**
* toArray contains all elements
*/
public void testToArray() {
ConcurrentSkipListSet q = populatedSet(SIZE);
Object[] o = q.toArray();
Arrays.sort(o);
for(int i = 0; i < o.length; i++)
assertEquals(o[i], q.pollFirst());
}
/**
* toArray(a) contains all elements
*/
public void testToArray2() {
ConcurrentSkipListSet q = populatedSet(SIZE);
Integer[] ints = new Integer[SIZE];
ints = (Integer[])q.toArray(ints);
Arrays.sort(ints);
for(int i = 0; i < ints.length; i++)
assertEquals(ints[i], q.pollFirst());
}
/**
* iterator iterates through all elements
*/
public void testIterator() {
ConcurrentSkipListSet q = populatedSet(SIZE);
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, SIZE);
}
/**
* iterator of empty set has no elements
*/
public void testEmptyIterator() {
ConcurrentSkipListSet q = new ConcurrentSkipListSet();
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, 0);
}
/**
* iterator.remove removes current element
*/
public void testIteratorRemove () {
final ConcurrentSkipListSet q = new ConcurrentSkipListSet();
q.add(new Integer(2));
q.add(new Integer(1));
q.add(new Integer(3));
Iterator it = q.iterator();
it.next();
it.remove();
it = q.iterator();
assertEquals(it.next(), new Integer(2));
assertEquals(it.next(), new Integer(3));
assertFalse(it.hasNext());
}
/**
* toString contains toStrings of elements
*/
public void testToString() {
ConcurrentSkipListSet q = populatedSet(SIZE);
String s = q.toString();
for (int i = 0; i < SIZE; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
/**
* A deserialized serialized set has same elements
*/
public void testSerialization() {
ConcurrentSkipListSet q = populatedSet(SIZE);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
ConcurrentSkipListSet r = (ConcurrentSkipListSet)in.readObject();
assertEquals(q.size(), r.size());
while (!q.isEmpty())
assertEquals(q.pollFirst(), r.pollFirst());
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* subSet returns set with keys in requested range
*/
public void testSubSetContents() {
ConcurrentSkipListSet set = set5();
SortedSet sm = set.subSet(two, four);
assertEquals(two, sm.first());
assertEquals(three, sm.last());
assertEquals(2, sm.size());
assertFalse(sm.contains(one));
assertTrue(sm.contains(two));
assertTrue(sm.contains(three));
assertFalse(sm.contains(four));
assertFalse(sm.contains(five));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
assertFalse(i.hasNext());
Iterator j = sm.iterator();
j.next();
j.remove();
assertFalse(set.contains(two));
assertEquals(4, set.size());
assertEquals(1, sm.size());
assertEquals(three, sm.first());
assertEquals(three, sm.last());
assertTrue(sm.remove(three));
assertTrue(sm.isEmpty());
assertEquals(3, set.size());
}
public void testSubSetContents2() {
ConcurrentSkipListSet set = set5();
SortedSet sm = set.subSet(two, three);
assertEquals(1, sm.size());
assertEquals(two, sm.first());
assertEquals(two, sm.last());
assertFalse(sm.contains(one));
assertTrue(sm.contains(two));
assertFalse(sm.contains(three));
assertFalse(sm.contains(four));
assertFalse(sm.contains(five));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
assertFalse(i.hasNext());
Iterator j = sm.iterator();
j.next();
j.remove();
assertFalse(set.contains(two));
assertEquals(4, set.size());
assertEquals(0, sm.size());
assertTrue(sm.isEmpty());
assertFalse(sm.remove(three));
assertEquals(4, set.size());
}
/**
* headSet returns set with keys in requested range
*/
public void testHeadSetContents() {
ConcurrentSkipListSet set = set5();
SortedSet sm = set.headSet(four);
assertTrue(sm.contains(one));
assertTrue(sm.contains(two));
assertTrue(sm.contains(three));
assertFalse(sm.contains(four));
assertFalse(sm.contains(five));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(one, k);
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
assertFalse(i.hasNext());
sm.clear();
assertTrue(sm.isEmpty());
assertEquals(2, set.size());
assertEquals(four, set.first());
}
/**
* tailSet returns set with keys in requested range
*/
public void testTailSetContents() {
ConcurrentSkipListSet set = set5();
SortedSet sm = set.tailSet(two);
assertFalse(sm.contains(one));
assertTrue(sm.contains(two));
assertTrue(sm.contains(three));
assertTrue(sm.contains(four));
assertTrue(sm.contains(five));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
k = (Integer)(i.next());
assertEquals(four, k);
k = (Integer)(i.next());
assertEquals(five, k);
assertFalse(i.hasNext());
SortedSet ssm = sm.tailSet(four);
assertEquals(four, ssm.first());
assertEquals(five, ssm.last());
assertTrue(ssm.remove(four));
assertEquals(1, ssm.size());
assertEquals(3, sm.size());
assertEquals(4, set.size());
}
Random rnd = new Random(666);
BitSet bs;
/**
* Subsets of subsets subdivide correctly
*/
public void testRecursiveSubSets() {
int setSize = 1000;
Class cl = ConcurrentSkipListSet.class;
NavigableSet set = newSet(cl);
bs = new BitSet(setSize);
populate(set, setSize);
check(set, 0, setSize - 1, true);
check(set.descendingSet(), 0, setSize - 1, false);
mutateSet(set, 0, setSize - 1);
check(set, 0, setSize - 1, true);
check(set.descendingSet(), 0, setSize - 1, false);
bashSubSet(set.subSet(new Integer(0), true, new Integer(setSize), false),
0, setSize - 1, true);
}
static NavigableSet newSet(Class cl) {
NavigableSet result = null;
try {
result = (NavigableSet) cl.newInstance();
} catch(Exception e) {
fail();
}
assertEquals(result.size(), 0);
assertFalse(result.iterator().hasNext());
return result;
}
void populate(NavigableSet set, int limit) {
for (int i = 0, n = 2 * limit / 3; i < n; i++) {
int element = rnd.nextInt(limit);
put(set, element);
}
}
void mutateSet(NavigableSet set, int min, int max) {
int size = set.size();
int rangeSize = max - min + 1;
// Remove a bunch of entries directly
for (int i = 0, n = rangeSize / 2; i < n; i++) {
remove(set, min - 5 + rnd.nextInt(rangeSize + 10));
}
// Remove a bunch of entries with iterator
for(Iterator it = set.iterator(); it.hasNext(); ) {
if (rnd.nextBoolean()) {
bs.clear(((Integer)it.next()).intValue());
it.remove();
}
}
// Add entries till we're back to original size
while (set.size() < size) {
int element = min + rnd.nextInt(rangeSize);
assertTrue(element >= min && element<= max);
put(set, element);
}
}
void mutateSubSet(NavigableSet set, int min, int max) {
int size = set.size();
int rangeSize = max - min + 1;
// Remove a bunch of entries directly
for (int i = 0, n = rangeSize / 2; i < n; i++) {
remove(set, min - 5 + rnd.nextInt(rangeSize + 10));
}
// Remove a bunch of entries with iterator
for(Iterator it = set.iterator(); it.hasNext(); ) {
if (rnd.nextBoolean()) {
bs.clear(((Integer)it.next()).intValue());
it.remove();
}
}
// Add entries till we're back to original size
while (set.size() < size) {
int element = min - 5 + rnd.nextInt(rangeSize + 10);
if (element >= min && element<= max) {
put(set, element);
} else {
try {
set.add(new Integer(element));
fail();
} catch(IllegalArgumentException e) {
// expected
}
}
}
}
void put(NavigableSet set, int element) {
if (set.add(new Integer(element)))
bs.set(element);
}
void remove(NavigableSet set, int element) {
if (set.remove(new Integer(element)))
bs.clear(element);
}
void bashSubSet(NavigableSet set,
int min, int max, boolean ascending) {
check(set, min, max, ascending);
check(set.descendingSet(), min, max, !ascending);
mutateSubSet(set, min, max);
check(set, min, max, ascending);
check(set.descendingSet(), min, max, !ascending);
// Recurse
if (max - min < 2)
return;
int midPoint = (min + max) / 2;
// headSet - pick direction and endpoint inclusion randomly
boolean incl = rnd.nextBoolean();
NavigableSet hm = set.headSet(new Integer(midPoint), incl);
if (ascending) {
if (rnd.nextBoolean())
bashSubSet(hm, min, midPoint - (incl ? 0 : 1), true);
else
bashSubSet(hm.descendingSet(), min, midPoint - (incl ? 0 : 1),
false);
} else {
if (rnd.nextBoolean())
bashSubSet(hm, midPoint + (incl ? 0 : 1), max, false);
else
bashSubSet(hm.descendingSet(), midPoint + (incl ? 0 : 1), max,
true);
}
// tailSet - pick direction and endpoint inclusion randomly
incl = rnd.nextBoolean();
NavigableSet tm = set.tailSet(new Integer(midPoint),incl);
if (ascending) {
if (rnd.nextBoolean())
bashSubSet(tm, midPoint + (incl ? 0 : 1), max, true);
else
bashSubSet(tm.descendingSet(), midPoint + (incl ? 0 : 1), max,
false);
} else {
if (rnd.nextBoolean()) {
bashSubSet(tm, min, midPoint - (incl ? 0 : 1), false);
} else {
bashSubSet(tm.descendingSet(), min, midPoint - (incl ? 0 : 1),
true);
}
}
// subSet - pick direction and endpoint inclusion randomly
int rangeSize = max - min + 1;
int[] endpoints = new int[2];
endpoints[0] = min + rnd.nextInt(rangeSize);
endpoints[1] = min + rnd.nextInt(rangeSize);
Arrays.sort(endpoints);
boolean lowIncl = rnd.nextBoolean();
boolean highIncl = rnd.nextBoolean();
if (ascending) {
NavigableSet sm = set.subSet(
new Integer(endpoints[0]), lowIncl, new Integer(endpoints[1]), highIncl);
if (rnd.nextBoolean())
bashSubSet(sm, endpoints[0] + (lowIncl ? 0 : 1),
endpoints[1] - (highIncl ? 0 : 1), true);
else
bashSubSet(sm.descendingSet(), endpoints[0] + (lowIncl ? 0 : 1),
endpoints[1] - (highIncl ? 0 : 1), false);
} else {
NavigableSet sm = set.subSet(
new Integer(endpoints[1]), highIncl, new Integer(endpoints[0]), lowIncl);
if (rnd.nextBoolean())
bashSubSet(sm, endpoints[0] + (lowIncl ? 0 : 1),
endpoints[1] - (highIncl ? 0 : 1), false);
else
bashSubSet(sm.descendingSet(), endpoints[0] + (lowIncl ? 0 : 1),
endpoints[1] - (highIncl ? 0 : 1), true);
}
}
/**
* min and max are both inclusive. If max < min, interval is empty.
*/
void check(NavigableSet set,
final int min, final int max, final boolean ascending) {
class ReferenceSet {
int lower(int element) {
return ascending ?
lowerAscending(element) : higherAscending(element);
}
int floor(int element) {
return ascending ?
floorAscending(element) : ceilingAscending(element);
}
int ceiling(int element) {
return ascending ?
ceilingAscending(element) : floorAscending(element);
}
int higher(int element) {
return ascending ?
higherAscending(element) : lowerAscending(element);
}
int first() {
return ascending ? firstAscending() : lastAscending();
}
int last() {
return ascending ? lastAscending() : firstAscending();
}
int lowerAscending(int element) {
return floorAscending(element - 1);
}
int floorAscending(int element) {
if (element < min)
return -1;
else if (element > max)
element = max;
// BitSet should support this! Test would run much faster
while (element >= min) {
if (bs.get(element))
return(element);
element--;
}
return -1;
}
int ceilingAscending(int element) {
if (element < min)
element = min;
else if (element > max)
return -1;
int result = bs.nextSetBit(element);
return result > max ? -1 : result;
}
int higherAscending(int element) {
return ceilingAscending(element + 1);
}
private int firstAscending() {
int result = ceilingAscending(min);
return result > max ? -1 : result;
}
private int lastAscending() {
int result = floorAscending(max);
return result < min ? -1 : result;
}
}
ReferenceSet rs = new ReferenceSet();
// Test contents using containsElement
int size = 0;
for (int i = min; i <= max; i++) {
boolean bsContainsI = bs.get(i);
assertEquals(bsContainsI, set.contains(new Integer(i)));
if (bsContainsI)
size++;
}
assertEquals(set.size(), size);
// Test contents using contains elementSet iterator
int size2 = 0;
int previousElement = -1;
for (Iterator itr = set.iterator(); itr.hasNext();) {
int element = ((Integer)itr.next()).intValue();
assertTrue(bs.get(element));
size2++;
assertTrue(previousElement < 0 || (ascending ?
element - previousElement > 0 : element - previousElement < 0));
previousElement = element;
}
assertEquals(size2, size);
// Test navigation ops
for (int element = min - 1; element <= max + 1; element++) {
assertEq((Integer)set.lower(new Integer(element)), rs.lower(element));
assertEq((Integer)set.floor(new Integer(element)), rs.floor(element));
assertEq((Integer)set.higher(new Integer(element)), rs.higher(element));
assertEq((Integer)set.ceiling(new Integer(element)), rs.ceiling(element));
}
// Test extrema
if (set.size() != 0) {
assertEq((Integer)set.first(), rs.first());
assertEq((Integer)set.last(), rs.last());
} else {
assertEq(new Integer(rs.first()), -1);
assertEq(new Integer(rs.last()), -1);
try {
set.first();
fail();
} catch(NoSuchElementException e) {
// expected
}
try {
set.last();
fail();
} catch(NoSuchElementException e) {
// expected
}
}
}
static void assertEq(Integer i, int j) {
if (i == null)
assertEquals(j, -1);
else
assertEquals(i.intValue(), j);
}
static boolean eq(Integer i, int j) {
return i == null ? j == -1 : i.intValue() == j;
}
}
backport-util-concurrent-3.1-src/test/tck/src/AtomicIntegerFieldUpdaterTest.java 0000644 0017507 0003772 00000021745 10253674160 027000 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
public class AtomicIntegerFieldUpdaterTest extends JSR166TestCase {
// volatile int x = 0;
// int w;
// long z;
// public static void main(String[] args){
// junit.textui.TestRunner.run(suite());
// }
// public static Test suite() {
// return new TestSuite(AtomicIntegerFieldUpdaterTest.class);
// }
//
// /**
// * Construction with non-existent field throws RuntimeException
// */
// public void testConstructor() {
// try{
// AtomicIntegerFieldUpdater
// a = AtomicIntegerFieldUpdater.newUpdater
// (AtomicIntegerFieldUpdaterTest.class, "y");
// shouldThrow();
// }
// catch (RuntimeException rt) {}
// }
//
// /**
// * construction with field not of given type throws RuntimeException
// */
// public void testConstructor2() {
// try{
// AtomicIntegerFieldUpdater
// a = AtomicIntegerFieldUpdater.newUpdater
// (AtomicIntegerFieldUpdaterTest.class, "z");
// shouldThrow();
// }
// catch (RuntimeException rt) {}
// }
//
// /**
// * construction with non-volatile field throws RuntimeException
// */
// public void testConstructor3() {
// try{
// AtomicIntegerFieldUpdater
// a = AtomicIntegerFieldUpdater.newUpdater
// (AtomicIntegerFieldUpdaterTest.class, "w");
// shouldThrow();
// }
// catch (RuntimeException rt) {}
// }
//
// /**
// * get returns the last value set or assigned
// */
// public void testGetSet() {
// AtomicIntegerFieldUpdater a;
// try {
// a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertEquals(1,a.get(this));
// a.set(this,2);
// assertEquals(2,a.get(this));
// a.set(this,-3);
// assertEquals(-3,a.get(this));
//
// }
//
// /**
// * get returns the last value lazySet by same thread
// */
// public void testGetLazySet() {
// AtomicIntegerFieldUpdater a;
// try {
// a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertEquals(1,a.get(this));
// a.lazySet(this,2);
// assertEquals(2,a.get(this));
// a.lazySet(this,-3);
// assertEquals(-3,a.get(this));
//
// }
//
// /**
// * compareAndSet succeeds in changing value if equal to expected else fails
// */
// public void testCompareAndSet() {
// AtomicIntegerFieldUpdater a;
// try {
// a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertTrue(a.compareAndSet(this,1,2));
// assertTrue(a.compareAndSet(this,2,-4));
// assertEquals(-4,a.get(this));
// assertFalse(a.compareAndSet(this,-5,7));
// assertFalse((7 == a.get(this)));
// assertTrue(a.compareAndSet(this,-4,7));
// assertEquals(7,a.get(this));
// }
//
//
// /**
// * compareAndSet in one thread enables another waiting for value
// * to succeed
// */
// public void testCompareAndSetInMultipleThreads() {
// x = 1;
// final AtomicIntegerFieldUpdater a;
// try {
// a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
//
// Thread t = new Thread(new Runnable() {
// public void run() {
// while(!a.compareAndSet(AtomicIntegerFieldUpdaterTest.this, 2, 3)) Thread.yield();
// }});
// try {
// t.start();
// assertTrue(a.compareAndSet(this, 1, 2));
// t.join(LONG_DELAY_MS);
// assertFalse(t.isAlive());
// assertEquals(a.get(this), 3);
// }
// catch(Exception e) {
// unexpectedException();
// }
// }
//
// /**
// * repeated weakCompareAndSet succeeds in changing value when equal
// * to expected
// */
// public void testWeakCompareAndSet() {
// AtomicIntegerFieldUpdater a;
// try {
// a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// while(!a.weakCompareAndSet(this,1,2));
// while(!a.weakCompareAndSet(this,2,-4));
// assertEquals(-4,a.get(this));
// while(!a.weakCompareAndSet(this,-4,7));
// assertEquals(7,a.get(this));
// }
//
// /**
// * getAndSet returns previous value and sets to given value
// */
// public void testGetAndSet() {
// AtomicIntegerFieldUpdater a;
// try {
// a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertEquals(1,a.getAndSet(this, 0));
// assertEquals(0,a.getAndSet(this,-10));
// assertEquals(-10,a.getAndSet(this,1));
// }
//
// /**
// * getAndAdd returns previous value and adds given value
// */
// public void testGetAndAdd() {
// AtomicIntegerFieldUpdater a;
// try {
// a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertEquals(1,a.getAndAdd(this,2));
// assertEquals(3,a.get(this));
// assertEquals(3,a.getAndAdd(this,-4));
// assertEquals(-1,a.get(this));
// }
//
// /**
// * getAndDecrement returns previous value and decrements
// */
// public void testGetAndDecrement() {
// AtomicIntegerFieldUpdater a;
// try {
// a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertEquals(1,a.getAndDecrement(this));
// assertEquals(0,a.getAndDecrement(this));
// assertEquals(-1,a.getAndDecrement(this));
// }
//
// /**
// * getAndIncrement returns previous value and increments
// */
// public void testGetAndIncrement() {
// AtomicIntegerFieldUpdater a;
// try {
// a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertEquals(1,a.getAndIncrement(this));
// assertEquals(2,a.get(this));
// a.set(this,-2);
// assertEquals(-2,a.getAndIncrement(this));
// assertEquals(-1,a.getAndIncrement(this));
// assertEquals(0,a.getAndIncrement(this));
// assertEquals(1,a.get(this));
// }
//
// /**
// * addAndGet adds given value to current, and returns current value
// */
// public void testAddAndGet() {
// AtomicIntegerFieldUpdater a;
// try {
// a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertEquals(3,a.addAndGet(this,2));
// assertEquals(3,a.get(this));
// assertEquals(-1,a.addAndGet(this,-4));
// assertEquals(-1,a.get(this));
// }
//
// /**
// * decrementAndGet decrements and returns current value
// */
// public void testDecrementAndGet() {
// AtomicIntegerFieldUpdater a;
// try {
// a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertEquals(0,a.decrementAndGet(this));
// assertEquals(-1,a.decrementAndGet(this));
// assertEquals(-2,a.decrementAndGet(this));
// assertEquals(-2,a.get(this));
// }
//
// /**
// * incrementAndGet increments and returns current value
// */
// public void testIncrementAndGet() {
// AtomicIntegerFieldUpdater a;
// try {
// a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertEquals(2,a.incrementAndGet(this));
// assertEquals(2,a.get(this));
// a.set(this,-2);
// assertEquals(-1,a.incrementAndGet(this));
// assertEquals(0,a.incrementAndGet(this));
// assertEquals(1,a.incrementAndGet(this));
// assertEquals(1,a.get(this));
// }
//
}
backport-util-concurrent-3.1-src/test/tck/src/SystemTest.java 0000644 0017507 0003772 00000004712 10253735611 023233 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.helpers.*;
public class SystemTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static Test suite() {
return new TestSuite(SystemTest.class);
}
/**
* Worst case rounding for millisecs; set for 60 cycle millis clock.
* This value might need to be changed os JVMs with coarser
* System.currentTimeMillis clocks.
*/
static final long MILLIS_ROUND = 17;
/**
* Nanos between readings of millis is no longer than millis (plus
* possible rounding).
* This shows only that nano timing not (much) worse than milli.
*/
public void testNanoTime1() {
try {
long m1 = System.currentTimeMillis();
Thread.sleep(1);
long n1 = Utils.nanoTime();
Thread.sleep(SHORT_DELAY_MS);
long n2 = Utils.nanoTime();
Thread.sleep(1);
long m2 = System.currentTimeMillis();
long millis = m2 - m1;
long nanos = n2 - n1;
assertTrue(nanos >= 0);
long nanosAsMillis = nanos / 1000000;
assertTrue(nanosAsMillis <= millis + MILLIS_ROUND);
}
catch(InterruptedException ie) {
unexpectedException();
}
}
/**
* Millis between readings of nanos is less than nanos, adjusting
* for rounding.
* This shows only that nano timing not (much) worse than milli.
*/
public void testNanoTime2() {
try {
long n1 = Utils.nanoTime();
Thread.sleep(1);
long m1 = System.currentTimeMillis();
Thread.sleep(SHORT_DELAY_MS);
long m2 = System.currentTimeMillis();
Thread.sleep(1);
long n2 = Utils.nanoTime();
long millis = m2 - m1;
long nanos = n2 - n1;
assertTrue(nanos >= 0);
long nanosAsMillis = nanos / 1000000;
assertTrue(millis <= nanosAsMillis + MILLIS_ROUND);
}
catch(InterruptedException ie) {
unexpectedException();
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/ConcurrentHashMapTest.java 0000644 0017507 0003772 00000041550 10365510635 025335 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.io.*;
import java.util.Enumeration;
import java.util.Set;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Map;
import java.util.Iterator;
public class ConcurrentHashMapTest extends JSR166TestCase{
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(ConcurrentHashMapTest.class);
}
/**
* Create a map from Integers 1-5 to Strings "A"-"E".
*/
private static ConcurrentHashMap map5() {
ConcurrentHashMap map = new ConcurrentHashMap(5);
assertTrue(map.isEmpty());
map.put(one, "A");
map.put(two, "B");
map.put(three, "C");
map.put(four, "D");
map.put(five, "E");
assertFalse(map.isEmpty());
assertEquals(5, map.size());
return map;
}
/**
* clear removes all pairs
*/
public void testClear() {
ConcurrentHashMap map = map5();
map.clear();
assertEquals(map.size(), 0);
}
/**
* Maps with same contents are equal
*/
public void testEquals() {
ConcurrentHashMap map1 = map5();
ConcurrentHashMap map2 = map5();
assertEquals(map1, map2);
assertEquals(map2, map1);
map1.clear();
assertFalse(map1.equals(map2));
assertFalse(map2.equals(map1));
}
/**
* contains returns true for contained value
*/
public void testContains() {
ConcurrentHashMap map = map5();
assertTrue(map.contains("A"));
assertFalse(map.contains("Z"));
}
/**
* containsKey returns true for contained key
*/
public void testContainsKey() {
ConcurrentHashMap map = map5();
assertTrue(map.containsKey(one));
assertFalse(map.containsKey(zero));
}
/**
* containsValue returns true for held values
*/
public void testContainsValue() {
ConcurrentHashMap map = map5();
assertTrue(map.containsValue("A"));
assertFalse(map.containsValue("Z"));
}
/**
* enumeration returns an enumeration containing the correct
* elements
*/
public void testEnumeration() {
ConcurrentHashMap map = map5();
Enumeration e = map.elements();
int count = 0;
while(e.hasMoreElements()){
count++;
e.nextElement();
}
assertEquals(5, count);
}
/**
* get returns the correct element at the given key,
* or null if not present
*/
public void testGet() {
ConcurrentHashMap map = map5();
assertEquals("A", (String)map.get(one));
ConcurrentHashMap empty = new ConcurrentHashMap();
assertNull(map.get("anything"));
}
/**
* isEmpty is true of empty map and false for non-empty
*/
public void testIsEmpty() {
ConcurrentHashMap empty = new ConcurrentHashMap();
ConcurrentHashMap map = map5();
assertTrue(empty.isEmpty());
assertFalse(map.isEmpty());
}
/**
* keys returns an enumeration containing all the keys from the map
*/
public void testKeys() {
ConcurrentHashMap map = map5();
Enumeration e = map.keys();
int count = 0;
while(e.hasMoreElements()){
count++;
e.nextElement();
}
assertEquals(5, count);
}
/**
* keySet returns a Set containing all the keys
*/
public void testKeySet() {
ConcurrentHashMap map = map5();
Set s = map.keySet();
assertEquals(5, s.size());
assertTrue(s.contains(one));
assertTrue(s.contains(two));
assertTrue(s.contains(three));
assertTrue(s.contains(four));
assertTrue(s.contains(five));
}
/**
* keySet.toArray returns contains all keys
*/
public void testKeySetToArray() {
ConcurrentHashMap map = map5();
Set s = map.keySet();
Object[] ar = s.toArray();
assertTrue(s.containsAll(Arrays.asList(ar)));
assertEquals(5, ar.length);
ar[0] = m10;
assertFalse(s.containsAll(Arrays.asList(ar)));
}
/**
* Values.toArray contains all values
*/
public void testValuesToArray() {
ConcurrentHashMap map = map5();
Collection v = map.values();
Object[] ar = v.toArray();
ArrayList s = new ArrayList(Arrays.asList(ar));
assertEquals(5, ar.length);
assertTrue(s.contains("A"));
assertTrue(s.contains("B"));
assertTrue(s.contains("C"));
assertTrue(s.contains("D"));
assertTrue(s.contains("E"));
}
/**
* entrySet.toArray contains all entries
*/
public void testEntrySetToArray() {
ConcurrentHashMap map = map5();
Set s = map.entrySet();
Object[] ar = s.toArray();
assertEquals(5, ar.length);
for (int i = 0; i < 5; ++i) {
assertTrue(map.containsKey(((Map.Entry)(ar[i])).getKey()));
assertTrue(map.containsValue(((Map.Entry)(ar[i])).getValue()));
}
}
/**
* values collection contains all values
*/
public void testValues() {
ConcurrentHashMap map = map5();
Collection s = map.values();
assertEquals(5, s.size());
assertTrue(s.contains("A"));
assertTrue(s.contains("B"));
assertTrue(s.contains("C"));
assertTrue(s.contains("D"));
assertTrue(s.contains("E"));
}
/**
* entrySet contains all pairs
*/
public void testEntrySet() {
ConcurrentHashMap map = map5();
Set s = map.entrySet();
assertEquals(5, s.size());
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
assertTrue(
(e.getKey().equals(one) && e.getValue().equals("A")) ||
(e.getKey().equals(two) && e.getValue().equals("B")) ||
(e.getKey().equals(three) && e.getValue().equals("C")) ||
(e.getKey().equals(four) && e.getValue().equals("D")) ||
(e.getKey().equals(five) && e.getValue().equals("E")));
}
}
/**
* putAll adds all key-value pairs from the given map
*/
public void testPutAll() {
ConcurrentHashMap empty = new ConcurrentHashMap();
ConcurrentHashMap map = map5();
empty.putAll(map);
assertEquals(5, empty.size());
assertTrue(empty.containsKey(one));
assertTrue(empty.containsKey(two));
assertTrue(empty.containsKey(three));
assertTrue(empty.containsKey(four));
assertTrue(empty.containsKey(five));
}
/**
* putIfAbsent works when the given key is not present
*/
public void testPutIfAbsent() {
ConcurrentHashMap map = map5();
map.putIfAbsent(six, "Z");
assertTrue(map.containsKey(six));
}
/**
* putIfAbsent does not add the pair if the key is already present
*/
public void testPutIfAbsent2() {
ConcurrentHashMap map = map5();
assertEquals("A", map.putIfAbsent(one, "Z"));
}
/**
* replace fails when the given key is not present
*/
public void testReplace() {
ConcurrentHashMap map = map5();
assertNull(map.replace(six, "Z"));
assertFalse(map.containsKey(six));
}
/**
* replace succeeds if the key is already present
*/
public void testReplace2() {
ConcurrentHashMap map = map5();
assertNotNull(map.replace(one, "Z"));
assertEquals("Z", map.get(one));
}
/**
* replace value fails when the given key not mapped to expected value
*/
public void testReplaceValue() {
ConcurrentHashMap map = map5();
assertEquals("A", map.get(one));
assertFalse(map.replace(one, "Z", "Z"));
assertEquals("A", map.get(one));
}
/**
* replace value succeeds when the given key mapped to expected value
*/
public void testReplaceValue2() {
ConcurrentHashMap map = map5();
assertEquals("A", map.get(one));
assertTrue(map.replace(one, "A", "Z"));
assertEquals("Z", map.get(one));
}
/**
* remove removes the correct key-value pair from the map
*/
public void testRemove() {
ConcurrentHashMap map = map5();
map.remove(five);
assertEquals(4, map.size());
assertFalse(map.containsKey(five));
}
/**
* remove(key,value) removes only if pair present
*/
public void testRemove2() {
ConcurrentHashMap map = map5();
map.remove(five, "E");
assertEquals(4, map.size());
assertFalse(map.containsKey(five));
map.remove(four, "A");
assertEquals(4, map.size());
assertTrue(map.containsKey(four));
}
/**
* size returns the correct values
*/
public void testSize() {
ConcurrentHashMap map = map5();
ConcurrentHashMap empty = new ConcurrentHashMap();
assertEquals(0, empty.size());
assertEquals(5, map.size());
}
/**
* toString contains toString of elements
*/
public void testToString() {
ConcurrentHashMap map = map5();
String s = map.toString();
for (int i = 1; i <= 5; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
// Exception tests
/**
* Cannot create with negative capacity
*/
public void testConstructor1() {
try {
new ConcurrentHashMap(-1,0,1);
shouldThrow();
} catch(IllegalArgumentException e){}
}
/**
* Cannot create with negative concurrency level
*/
public void testConstructor2() {
try {
new ConcurrentHashMap(1,0,-1);
shouldThrow();
} catch(IllegalArgumentException e){}
}
/**
* Cannot create with only negative capacity
*/
public void testConstructor3() {
try {
new ConcurrentHashMap(-1);
shouldThrow();
} catch(IllegalArgumentException e){}
}
/**
* get(null) throws NPE
*/
public void testGet_NullPointerException() {
try {
ConcurrentHashMap c = new ConcurrentHashMap(5);
c.get(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* containsKey(null) throws NPE
*/
public void testContainsKey_NullPointerException() {
try {
ConcurrentHashMap c = new ConcurrentHashMap(5);
c.containsKey(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* containsValue(null) throws NPE
*/
public void testContainsValue_NullPointerException() {
try {
ConcurrentHashMap c = new ConcurrentHashMap(5);
c.containsValue(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* contains(null) throws NPE
*/
public void testContains_NullPointerException() {
try {
ConcurrentHashMap c = new ConcurrentHashMap(5);
c.contains(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* put(null,x) throws NPE
*/
public void testPut1_NullPointerException() {
try {
ConcurrentHashMap c = new ConcurrentHashMap(5);
c.put(null, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* put(x, null) throws NPE
*/
public void testPut2_NullPointerException() {
try {
ConcurrentHashMap c = new ConcurrentHashMap(5);
c.put("whatever", null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* putIfAbsent(null, x) throws NPE
*/
public void testPutIfAbsent1_NullPointerException() {
try {
ConcurrentHashMap c = new ConcurrentHashMap(5);
c.putIfAbsent(null, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* replace(null, x) throws NPE
*/
public void testReplace_NullPointerException() {
try {
ConcurrentHashMap c = new ConcurrentHashMap(5);
c.replace(null, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* replace(null, x, y) throws NPE
*/
public void testReplaceValue_NullPointerException() {
try {
ConcurrentHashMap c = new ConcurrentHashMap(5);
c.replace(null, one, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* putIfAbsent(x, null) throws NPE
*/
public void testPutIfAbsent2_NullPointerException() {
try {
ConcurrentHashMap c = new ConcurrentHashMap(5);
c.putIfAbsent("whatever", null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* replace(x, null) throws NPE
*/
public void testReplace2_NullPointerException() {
try {
ConcurrentHashMap c = new ConcurrentHashMap(5);
c.replace("whatever", null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* replace(x, null, y) throws NPE
*/
public void testReplaceValue2_NullPointerException() {
try {
ConcurrentHashMap c = new ConcurrentHashMap(5);
c.replace("whatever", null, "A");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* replace(x, y, null) throws NPE
*/
public void testReplaceValue3_NullPointerException() {
try {
ConcurrentHashMap c = new ConcurrentHashMap(5);
c.replace("whatever", one, null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* remove(null) throws NPE
*/
public void testRemove1_NullPointerException() {
try {
ConcurrentHashMap c = new ConcurrentHashMap(5);
c.put("sadsdf", "asdads");
c.remove(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* remove(null, x) throws NPE
*/
public void testRemove2_NullPointerException() {
try {
ConcurrentHashMap c = new ConcurrentHashMap(5);
c.put("sadsdf", "asdads");
c.remove(null, "whatever");
shouldThrow();
} catch(NullPointerException e){}
}
/**
* remove(x, null) returns false
*/
public void testRemove3() {
try {
ConcurrentHashMap c = new ConcurrentHashMap(5);
c.put("sadsdf", "asdads");
assertFalse(c.remove("sadsdf", null));
} catch(NullPointerException e){
fail();
}
}
/**
* A deserialized map equals original
*/
public void testSerialization() {
ConcurrentHashMap q = map5();
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
ConcurrentHashMap r = (ConcurrentHashMap)in.readObject();
assertEquals(q.size(), r.size());
assertTrue(q.equals(r));
assertTrue(r.equals(q));
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* SetValue of an EntrySet entry sets value in the map.
*/
public void testSetValueWriteThrough() {
// Adapted from a bug report by Eric Zoerner
ConcurrentHashMap map = new ConcurrentHashMap(2, 5.0f, 1);
assertTrue(map.isEmpty());
for (int i = 0; i < 20; i++)
map.put(new Integer(i), new Integer(i));
assertFalse(map.isEmpty());
Map.Entry entry1 = (Map.Entry)map.entrySet().iterator().next();
// assert that entry1 is not 16
assertTrue("entry is 16, test not valid",
!entry1.getKey().equals(new Integer(16)));
// remove 16 (a different key) from map
// which just happens to cause entry1 to be cloned in map
map.remove(new Integer(16));
entry1.setValue("XYZ");
assertTrue(map.containsValue("XYZ")); // fails
}
}
backport-util-concurrent-3.1-src/test/tck/src/TreeSubSetTest.java 0000644 0017507 0003772 00000075167 10431777323 024014 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.SortedSet;
public class TreeSubSetTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(TreeSubSetTest.class);
}
static class MyReverseComparator implements Comparator {
public int compare(Object x, Object y) {
int i = ((Integer)x).intValue();
int j = ((Integer)y).intValue();
if (i < j) return 1;
if (i > j) return -1;
return 0;
}
}
/**
* Create a set of given size containing consecutive
* Integers 0 ... n.
*/
private NavigableSet populatedSet(int n) {
TreeSet q = new TreeSet();
assertTrue(q.isEmpty());
for(int i = n-1; i >= 0; i-=2)
assertTrue(q.add(new Integer(i)));
for(int i = (n & 1); i < n; i+=2)
assertTrue(q.add(new Integer(i)));
assertTrue(q.add(new Integer(-n)));
assertTrue(q.add(new Integer(n)));
NavigableSet s = q.subSet(new Integer(0), true, new Integer(n), false);
assertFalse(s.isEmpty());
assertEquals(n, s.size());
return s;
}
/**
* Create set of first 5 ints
*/
private NavigableSet set5() {
TreeSet q = new TreeSet();
assertTrue(q.isEmpty());
q.add(one);
q.add(two);
q.add(three);
q.add(four);
q.add(five);
q.add(zero);
q.add(seven);
NavigableSet s = q.subSet(one, true, seven, false);
assertEquals(5, s.size());
return s;
}
private NavigableSet dset5() {
TreeSet q = new TreeSet();
assertTrue(q.isEmpty());
q.add(m1);
q.add(m2);
q.add(m3);
q.add(m4);
q.add(m5);
NavigableSet s = q.descendingSet();
assertEquals(5, s.size());
return s;
}
private static NavigableSet set0() {
TreeSet set = new TreeSet();
assertTrue(set.isEmpty());
return set.tailSet(m1, false);
}
private static NavigableSet dset0() {
TreeSet set = new TreeSet();
assertTrue(set.isEmpty());
return set;
}
/**
* A new set has unbounded capacity
*/
public void testConstructor1() {
assertEquals(0, set0().size());
}
/**
* isEmpty is true before add, false after
*/
public void testEmpty() {
NavigableSet q = set0();
assertTrue(q.isEmpty());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.add(new Integer(2));
q.pollFirst();
q.pollFirst();
assertTrue(q.isEmpty());
}
/**
* size changes when elements added and removed
*/
public void testSize() {
NavigableSet q = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i, q.size());
q.pollFirst();
}
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
q.add(new Integer(i));
}
}
/**
* add(null) throws NPE
*/
public void testAddNull() {
try {
NavigableSet q = set0();
q.add(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* Add of comparable element succeeds
*/
public void testAdd() {
NavigableSet q = set0();
assertTrue(q.add(six));
}
/**
* Add of duplicate element fails
*/
public void testAddDup() {
NavigableSet q = set0();
assertTrue(q.add(six));
assertFalse(q.add(six));
}
/**
* Add of non-Comparable throws CCE
*/
public void testAddNonComparable() {
try {
NavigableSet q = set0();
q.add(new Object());
q.add(new Object());
q.add(new Object());
shouldThrow();
}
catch(ClassCastException success) {}
}
/**
* addAll(null) throws NPE
*/
public void testAddAll1() {
try {
NavigableSet q = set0();
q.addAll(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with null elements throws NPE
*/
public void testAddAll2() {
try {
NavigableSet q = set0();
Integer[] ints = new Integer[SIZE];
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with any null elements throws NPE after
* possibly adding some elements
*/
public void testAddAll3() {
try {
NavigableSet q = set0();
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i+SIZE);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Set contains all elements of successful addAll
*/
public void testAddAll5() {
try {
Integer[] empty = new Integer[0];
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(SIZE-1- i);
NavigableSet q = set0();
assertFalse(q.addAll(Arrays.asList(empty)));
assertTrue(q.addAll(Arrays.asList(ints)));
for (int i = 0; i < SIZE; ++i)
assertEquals(new Integer(i), q.pollFirst());
}
finally {}
}
/**
* poll succeeds unless empty
*/
public void testPoll() {
NavigableSet q = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.pollFirst()).intValue());
}
assertNull(q.pollFirst());
}
/**
* remove(x) removes x and returns true if present
*/
public void testRemoveElement() {
NavigableSet q = populatedSet(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
assertFalse(q.remove(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* contains(x) reports true when elements added but not yet removed
*/
public void testContains() {
NavigableSet q = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.contains(new Integer(i)));
q.pollFirst();
assertFalse(q.contains(new Integer(i)));
}
}
/**
* clear removes all elements
*/
public void testClear() {
NavigableSet q = populatedSet(SIZE);
q.clear();
assertTrue(q.isEmpty());
assertEquals(0, q.size());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.clear();
assertTrue(q.isEmpty());
}
/**
* containsAll(c) is true when c contains a subset of elements
*/
public void testContainsAll() {
NavigableSet q = populatedSet(SIZE);
NavigableSet p = set0();
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.containsAll(p));
assertFalse(p.containsAll(q));
p.add(new Integer(i));
}
assertTrue(p.containsAll(q));
}
/**
* retainAll(c) retains only those elements of c and reports true if changed
*/
public void testRetainAll() {
NavigableSet q = populatedSet(SIZE);
NavigableSet p = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
boolean changed = q.retainAll(p);
if (i == 0)
assertFalse(changed);
else
assertTrue(changed);
assertTrue(q.containsAll(p));
assertEquals(SIZE-i, q.size());
p.pollFirst();
}
}
/**
* removeAll(c) removes only those elements of c and reports true if changed
*/
public void testRemoveAll() {
for (int i = 1; i < SIZE; ++i) {
NavigableSet q = populatedSet(SIZE);
NavigableSet p = populatedSet(i);
assertTrue(q.removeAll(p));
assertEquals(SIZE-i, q.size());
for (int j = 0; j < i; ++j) {
Integer I = (Integer)(p.pollFirst());
assertFalse(q.contains(I));
}
}
}
/**
* lower returns preceding element
*/
public void testLower() {
NavigableSet q = set5();
Object e1 = q.lower(three);
assertEquals(two, e1);
Object e2 = q.lower(six);
assertEquals(five, e2);
Object e3 = q.lower(one);
assertNull(e3);
Object e4 = q.lower(zero);
assertNull(e4);
}
/**
* higher returns next element
*/
public void testHigher() {
NavigableSet q = set5();
Object e1 = q.higher(three);
assertEquals(four, e1);
Object e2 = q.higher(zero);
assertEquals(one, e2);
Object e3 = q.higher(five);
assertNull(e3);
Object e4 = q.higher(six);
assertNull(e4);
}
/**
* floor returns preceding element
*/
public void testFloor() {
NavigableSet q = set5();
Object e1 = q.floor(three);
assertEquals(three, e1);
Object e2 = q.floor(six);
assertEquals(five, e2);
Object e3 = q.floor(one);
assertEquals(one, e3);
Object e4 = q.floor(zero);
assertNull(e4);
}
/**
* ceiling returns next element
*/
public void testCeiling() {
NavigableSet q = set5();
Object e1 = q.ceiling(three);
assertEquals(three, e1);
Object e2 = q.ceiling(zero);
assertEquals(one, e2);
Object e3 = q.ceiling(five);
assertEquals(five, e3);
Object e4 = q.ceiling(six);
assertNull(e4);
}
/**
* toArray contains all elements
*/
public void testToArray() {
NavigableSet q = populatedSet(SIZE);
Object[] o = q.toArray();
Arrays.sort(o);
for(int i = 0; i < o.length; i++)
assertEquals(o[i], q.pollFirst());
}
/**
* toArray(a) contains all elements
*/
public void testToArray2() {
NavigableSet q = populatedSet(SIZE);
Integer[] ints = new Integer[SIZE];
ints = (Integer[])q.toArray(ints);
Arrays.sort(ints);
for(int i = 0; i < ints.length; i++)
assertEquals(ints[i], q.pollFirst());
}
/**
* iterator iterates through all elements
*/
public void testIterator() {
NavigableSet q = populatedSet(SIZE);
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, SIZE);
}
/**
* iterator of empty set has no elements
*/
public void testEmptyIterator() {
NavigableSet q = set0();
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, 0);
}
/**
* iterator.remove removes current element
*/
public void testIteratorRemove () {
final NavigableSet q = set0();
q.add(new Integer(2));
q.add(new Integer(1));
q.add(new Integer(3));
Iterator it = q.iterator();
it.next();
it.remove();
it = q.iterator();
assertEquals(it.next(), new Integer(2));
assertEquals(it.next(), new Integer(3));
assertFalse(it.hasNext());
}
/**
* toString contains toStrings of elements
*/
public void testToString() {
NavigableSet q = populatedSet(SIZE);
String s = q.toString();
for (int i = 0; i < SIZE; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
/**
* A deserialized serialized set has same elements
*/
public void testSerialization() {
NavigableSet q = populatedSet(SIZE);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
NavigableSet r = (NavigableSet)in.readObject();
assertEquals(q.size(), r.size());
while (!q.isEmpty())
assertEquals(q.pollFirst(), r.pollFirst());
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* subSet returns set with keys in requested range
*/
public void testSubSetContents() {
NavigableSet set = set5();
SortedSet sm = set.subSet(two, four);
assertEquals(two, sm.first());
assertEquals(three, sm.last());
assertEquals(2, sm.size());
assertFalse(sm.contains(one));
assertTrue(sm.contains(two));
assertTrue(sm.contains(three));
assertFalse(sm.contains(four));
assertFalse(sm.contains(five));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
assertFalse(i.hasNext());
Iterator j = sm.iterator();
j.next();
j.remove();
assertFalse(set.contains(two));
assertEquals(4, set.size());
assertEquals(1, sm.size());
assertEquals(three, sm.first());
assertEquals(three, sm.last());
assertTrue(sm.remove(three));
assertTrue(sm.isEmpty());
assertEquals(3, set.size());
}
public void testSubSetContents2() {
NavigableSet set = set5();
SortedSet sm = set.subSet(two, three);
assertEquals(1, sm.size());
assertEquals(two, sm.first());
assertEquals(two, sm.last());
assertFalse(sm.contains(one));
assertTrue(sm.contains(two));
assertFalse(sm.contains(three));
assertFalse(sm.contains(four));
assertFalse(sm.contains(five));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
assertFalse(i.hasNext());
Iterator j = sm.iterator();
j.next();
j.remove();
assertFalse(set.contains(two));
assertEquals(4, set.size());
assertEquals(0, sm.size());
assertTrue(sm.isEmpty());
assertFalse(sm.remove(three));
assertEquals(4, set.size());
}
/**
* headSet returns set with keys in requested range
*/
public void testHeadSetContents() {
NavigableSet set = set5();
SortedSet sm = set.headSet(four);
assertTrue(sm.contains(one));
assertTrue(sm.contains(two));
assertTrue(sm.contains(three));
assertFalse(sm.contains(four));
assertFalse(sm.contains(five));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(one, k);
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
assertFalse(i.hasNext());
sm.clear();
assertTrue(sm.isEmpty());
assertEquals(2, set.size());
assertEquals(four, set.first());
}
/**
* tailSet returns set with keys in requested range
*/
public void testTailSetContents() {
NavigableSet set = set5();
SortedSet sm = set.tailSet(two);
assertFalse(sm.contains(one));
assertTrue(sm.contains(two));
assertTrue(sm.contains(three));
assertTrue(sm.contains(four));
assertTrue(sm.contains(five));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
k = (Integer)(i.next());
assertEquals(four, k);
k = (Integer)(i.next());
assertEquals(five, k);
assertFalse(i.hasNext());
SortedSet ssm = sm.tailSet(four);
assertEquals(four, ssm.first());
assertEquals(five, ssm.last());
assertTrue(ssm.remove(four));
assertEquals(1, ssm.size());
assertEquals(3, sm.size());
assertEquals(4, set.size());
}
/**
* size changes when elements added and removed
*/
public void testDescendingSize() {
NavigableSet q = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i, q.size());
q.pollFirst();
}
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
q.add(new Integer(i));
}
}
/**
* Add of comparable element succeeds
*/
public void testDescendingAdd() {
NavigableSet q = dset0();
assertTrue(q.add(m6));
}
/**
* Add of duplicate element fails
*/
public void testDescendingAddDup() {
NavigableSet q = dset0();
assertTrue(q.add(m6));
assertFalse(q.add(m6));
}
/**
* Add of non-Comparable throws CCE
*/
public void testDescendingAddNonComparable() {
try {
NavigableSet q = dset0();
q.add(new Object());
q.add(new Object());
q.add(new Object());
shouldThrow();
}
catch(ClassCastException success) {}
}
/**
* addAll(null) throws NPE
*/
public void testDescendingAddAll1() {
try {
NavigableSet q = dset0();
q.addAll(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with null elements throws NPE
*/
public void testDescendingAddAll2() {
try {
NavigableSet q = dset0();
Integer[] ints = new Integer[SIZE];
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with any null elements throws NPE after
* possibly adding some elements
*/
public void testDescendingAddAll3() {
try {
NavigableSet q = dset0();
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i+SIZE);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Set contains all elements of successful addAll
*/
public void testDescendingAddAll5() {
try {
Integer[] empty = new Integer[0];
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(SIZE-1- i);
NavigableSet q = dset0();
assertFalse(q.addAll(Arrays.asList(empty)));
assertTrue(q.addAll(Arrays.asList(ints)));
for (int i = 0; i < SIZE; ++i)
assertEquals(new Integer(i), q.pollFirst());
}
finally {}
}
/**
* poll succeeds unless empty
*/
public void testDescendingPoll() {
NavigableSet q = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.pollFirst()).intValue());
}
assertNull(q.pollFirst());
}
/**
* remove(x) removes x and returns true if present
*/
public void testDescendingRemoveElement() {
NavigableSet q = populatedSet(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
assertFalse(q.remove(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* contains(x) reports true when elements added but not yet removed
*/
public void testDescendingContains() {
NavigableSet q = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.contains(new Integer(i)));
q.pollFirst();
assertFalse(q.contains(new Integer(i)));
}
}
/**
* clear removes all elements
*/
public void testDescendingClear() {
NavigableSet q = populatedSet(SIZE);
q.clear();
assertTrue(q.isEmpty());
assertEquals(0, q.size());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.clear();
assertTrue(q.isEmpty());
}
/**
* containsAll(c) is true when c contains a subset of elements
*/
public void testDescendingContainsAll() {
NavigableSet q = populatedSet(SIZE);
NavigableSet p = dset0();
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.containsAll(p));
assertFalse(p.containsAll(q));
p.add(new Integer(i));
}
assertTrue(p.containsAll(q));
}
/**
* retainAll(c) retains only those elements of c and reports true if changed
*/
public void testDescendingRetainAll() {
NavigableSet q = populatedSet(SIZE);
NavigableSet p = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
boolean changed = q.retainAll(p);
if (i == 0)
assertFalse(changed);
else
assertTrue(changed);
assertTrue(q.containsAll(p));
assertEquals(SIZE-i, q.size());
p.pollFirst();
}
}
/**
* removeAll(c) removes only those elements of c and reports true if changed
*/
public void testDescendingRemoveAll() {
for (int i = 1; i < SIZE; ++i) {
NavigableSet q = populatedSet(SIZE);
NavigableSet p = populatedSet(i);
assertTrue(q.removeAll(p));
assertEquals(SIZE-i, q.size());
for (int j = 0; j < i; ++j) {
Integer I = (Integer)(p.pollFirst());
assertFalse(q.contains(I));
}
}
}
/**
* lower returns preceding element
*/
public void testDescendingLower() {
NavigableSet q = dset5();
Object e1 = q.lower(m3);
assertEquals(m2, e1);
Object e2 = q.lower(m6);
assertEquals(m5, e2);
Object e3 = q.lower(m1);
assertNull(e3);
Object e4 = q.lower(zero);
assertNull(e4);
}
/**
* higher returns next element
*/
public void testDescendingHigher() {
NavigableSet q = dset5();
Object e1 = q.higher(m3);
assertEquals(m4, e1);
Object e2 = q.higher(zero);
assertEquals(m1, e2);
Object e3 = q.higher(m5);
assertNull(e3);
Object e4 = q.higher(m6);
assertNull(e4);
}
/**
* floor returns preceding element
*/
public void testDescendingFloor() {
NavigableSet q = dset5();
Object e1 = q.floor(m3);
assertEquals(m3, e1);
Object e2 = q.floor(m6);
assertEquals(m5, e2);
Object e3 = q.floor(m1);
assertEquals(m1, e3);
Object e4 = q.floor(zero);
assertNull(e4);
}
/**
* ceiling returns next element
*/
public void testDescendingCeiling() {
NavigableSet q = dset5();
Object e1 = q.ceiling(m3);
assertEquals(m3, e1);
Object e2 = q.ceiling(zero);
assertEquals(m1, e2);
Object e3 = q.ceiling(m5);
assertEquals(m5, e3);
Object e4 = q.ceiling(m6);
assertNull(e4);
}
/**
* toArray contains all elements
*/
public void testDescendingToArray() {
NavigableSet q = populatedSet(SIZE);
Object[] o = q.toArray();
Arrays.sort(o);
for(int i = 0; i < o.length; i++)
assertEquals(o[i], q.pollFirst());
}
/**
* toArray(a) contains all elements
*/
public void testDescendingToArray2() {
NavigableSet q = populatedSet(SIZE);
Integer[] ints = new Integer[SIZE];
ints = (Integer[])q.toArray(ints);
Arrays.sort(ints);
for(int i = 0; i < ints.length; i++)
assertEquals(ints[i], q.pollFirst());
}
/**
* iterator iterates through all elements
*/
public void testDescendingIterator() {
NavigableSet q = populatedSet(SIZE);
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, SIZE);
}
/**
* iterator of empty set has no elements
*/
public void testDescendingEmptyIterator() {
NavigableSet q = dset0();
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, 0);
}
/**
* iterator.remove removes current element
*/
public void testDescendingIteratorRemove () {
final NavigableSet q = dset0();
q.add(new Integer(2));
q.add(new Integer(1));
q.add(new Integer(3));
Iterator it = q.iterator();
it.next();
it.remove();
it = q.iterator();
assertEquals(it.next(), new Integer(2));
assertEquals(it.next(), new Integer(3));
assertFalse(it.hasNext());
}
/**
* toString contains toStrings of elements
*/
public void testDescendingToString() {
NavigableSet q = populatedSet(SIZE);
String s = q.toString();
for (int i = 0; i < SIZE; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
/**
* A deserialized serialized set has same elements
*/
public void testDescendingSerialization() {
NavigableSet q = populatedSet(SIZE);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
NavigableSet r = (NavigableSet)in.readObject();
assertEquals(q.size(), r.size());
while (!q.isEmpty())
assertEquals(q.pollFirst(), r.pollFirst());
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* subSet returns set with keys in requested range
*/
public void testDescendingSubSetContents() {
NavigableSet set = dset5();
SortedSet sm = set.subSet(m2, m4);
assertEquals(m2, sm.first());
assertEquals(m3, sm.last());
assertEquals(2, sm.size());
assertFalse(sm.contains(m1));
assertTrue(sm.contains(m2));
assertTrue(sm.contains(m3));
assertFalse(sm.contains(m4));
assertFalse(sm.contains(m5));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(m2, k);
k = (Integer)(i.next());
assertEquals(m3, k);
assertFalse(i.hasNext());
Iterator j = sm.iterator();
j.next();
j.remove();
assertFalse(set.contains(m2));
assertEquals(4, set.size());
assertEquals(1, sm.size());
assertEquals(m3, sm.first());
assertEquals(m3, sm.last());
assertTrue(sm.remove(m3));
assertTrue(sm.isEmpty());
assertEquals(3, set.size());
}
public void testDescendingSubSetContents2() {
NavigableSet set = dset5();
SortedSet sm = set.subSet(m2, m3);
assertEquals(1, sm.size());
assertEquals(m2, sm.first());
assertEquals(m2, sm.last());
assertFalse(sm.contains(m1));
assertTrue(sm.contains(m2));
assertFalse(sm.contains(m3));
assertFalse(sm.contains(m4));
assertFalse(sm.contains(m5));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(m2, k);
assertFalse(i.hasNext());
Iterator j = sm.iterator();
j.next();
j.remove();
assertFalse(set.contains(m2));
assertEquals(4, set.size());
assertEquals(0, sm.size());
assertTrue(sm.isEmpty());
assertFalse(sm.remove(m3));
assertEquals(4, set.size());
}
/**
* headSet returns set with keys in requested range
*/
public void testDescendingHeadSetContents() {
NavigableSet set = dset5();
SortedSet sm = set.headSet(m4);
assertTrue(sm.contains(m1));
assertTrue(sm.contains(m2));
assertTrue(sm.contains(m3));
assertFalse(sm.contains(m4));
assertFalse(sm.contains(m5));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(m1, k);
k = (Integer)(i.next());
assertEquals(m2, k);
k = (Integer)(i.next());
assertEquals(m3, k);
assertFalse(i.hasNext());
sm.clear();
assertTrue(sm.isEmpty());
assertEquals(2, set.size());
assertEquals(m4, set.first());
}
/**
* tailSet returns set with keys in requested range
*/
public void testDescendingTailSetContents() {
NavigableSet set = dset5();
SortedSet sm = set.tailSet(m2);
assertFalse(sm.contains(m1));
assertTrue(sm.contains(m2));
assertTrue(sm.contains(m3));
assertTrue(sm.contains(m4));
assertTrue(sm.contains(m5));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(m2, k);
k = (Integer)(i.next());
assertEquals(m3, k);
k = (Integer)(i.next());
assertEquals(m4, k);
k = (Integer)(i.next());
assertEquals(m5, k);
assertFalse(i.hasNext());
SortedSet ssm = sm.tailSet(m4);
assertEquals(m4, ssm.first());
assertEquals(m5, ssm.last());
assertTrue(ssm.remove(m4));
assertEquals(1, ssm.size());
assertEquals(3, sm.size());
assertEquals(4, set.size());
}
}
backport-util-concurrent-3.1-src/test/tck/src/JSR166TestCase.java 0000644 0017507 0003772 00000045203 10431777323 023442 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.io.*;
import java.security.*;
import junit.textui.*;
/**
* Base class for JSR166 Junit TCK tests. Defines some constants,
* utility methods and classes, as well as a simple framework for
* helping to make sure that assertions failing in generated threads
* cause the associated test that generated them to itself fail (which
* JUnit does not otherwise arrange). The rules for creating such
* tests are:
*
*
*
*
All assertions in code running in generated threads must use
* the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
* #threadAssertEquals}, or {@link #threadAssertNull}, (not
* fail, assertTrue, etc.) It is OK (but not
* particularly recommended) for other code to use these forms too.
* Only the most typically used JUnit assertion methods are defined
* this way, but enough to live with.
*
*
If you override {@link #setUp} or {@link #tearDown}, make sure
* to invoke super.setUp and super.tearDown within
* them. These methods are used to clear and check for thread
* assertion failures.
*
*
All delays and timeouts must use one of the constants
* SHORT_DELAY_MS, SMALL_DELAY_MS, MEDIUM_DELAY_MS,
* LONG_DELAY_MS. The idea here is that a SHORT is always
* discriminable from zero time, and always allows enough time for the
* small amounts of computation (creating a thread, calling a few
* methods, etc) needed to reach a timeout point. Similarly, a SMALL
* is always discriminable as larger than SHORT and smaller than
* MEDIUM. And so on. These constants are set to conservative values,
* but even so, if there is ever any doubt, they can all be increased
* in one spot to rerun tests on slower platforms.
*
*
All threads generated must be joined inside each test case
* method (or fail to do so) before returning from the
* method. The joinPool method can be used to do this when
* using Executors.
*
*
*
*
Other notes
*
*
*
Usually, there is one testcase method per JSR166 method
* covering "normal" operation, and then as many exception-testing
* methods as there are exceptions the method can throw. Sometimes
* there are multiple tests per JSR166 method when the different
* "normal" behaviors differ significantly. And sometimes testcases
* cover multiple methods when they cannot be tested in
* isolation.
*
*
The documentation style for testcases is to provide as javadoc
* a simple sentence or two describing the property that the testcase
* method purports to test. The javadocs do not say anything about how
* the property is tested. To find out, read the code.
*
*
These tests are "conformance tests", and do not attempt to
* test throughput, latency, scalability or other performance factors
* (see the separate "jtreg" tests for a set intended to check these
* for the most central aspects of functionality.) So, most tests use
* the smallest sensible numbers of threads, collection sizes, etc
* needed to check basic conformance.
*
*
The test classes currently do not declare inclusion in
* any particular package to simplify things for people integrating
* them in TCK test suites.
*
*
As a convenience, the main of this class (JSR166TestCase)
* runs all JSR166 unit tests.
*
*
*/
public class JSR166TestCase extends TestCase {
/**
* Runs all JSR166 unit tests using junit.textui.TestRunner
*/
public static void main (String[] args) {
int iters = 1;
if (args.length > 0)
iters = Integer.parseInt(args[0]);
Test s = suite();
for (int i = 0; i < iters; ++i) {
TestRunner.run(s);
System.gc();
System.runFinalization();
}
System.exit(0);
}
// private static class Printer extends ResultPrinter {
// Printer() {
// super(System.out);
// }
// public void startTest(Test test) {
// getWriter().println(test.getClass().getName());
// new Exception("Stack trace").printStackTrace(getWriter());
// }
// }
//
/**
* Collects all JSR166 unit tests as one suite
*/
public static Test suite ( ) {
TestSuite suite = new TestSuite("JSR166 Unit Tests");
suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
// suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
suite.addTest(new TestSuite(AbstractQueueTest.class));
// suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
suite.addTest(new TestSuite(ArrayDequeTest.class));
suite.addTest(new TestSuite(AtomicBooleanTest.class));
suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
// suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
suite.addTest(new TestSuite(AtomicIntegerTest.class));
suite.addTest(new TestSuite(AtomicLongArrayTest.class));
// suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
suite.addTest(new TestSuite(AtomicLongTest.class));
suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
// suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
suite.addTest(new TestSuite(AtomicReferenceTest.class));
suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
suite.addTest(new TestSuite(CountDownLatchTest.class));
suite.addTest(new TestSuite(CyclicBarrierTest.class));
suite.addTest(new TestSuite(DelayQueueTest.class));
suite.addTest(new TestSuite(EntryTest.class));
suite.addTest(new TestSuite(ExchangerTest.class));
suite.addTest(new TestSuite(ExecutorsTest.class));
suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
suite.addTest(new TestSuite(FutureTaskTest.class));
suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
suite.addTest(new TestSuite(LinkedListTest.class));
// suite.addTest(new TestSuite(LockSupportTest.class));
suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
suite.addTest(new TestSuite(PriorityQueueTest.class));
suite.addTest(new TestSuite(ReentrantLockTest.class));
suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
suite.addTest(new TestSuite(ScheduledExecutorTest.class));
suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
suite.addTest(new TestSuite(SemaphoreTest.class));
suite.addTest(new TestSuite(SynchronousQueueTest.class));
suite.addTest(new TestSuite(SystemTest.class));
suite.addTest(new TestSuite(ThreadLocalTest.class));
suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
// suite.addTest(new TestSuite(ThreadTest.class));
suite.addTest(new TestSuite(TimeUnitTest.class));
suite.addTest(new TestSuite(TreeMapTest.class));
suite.addTest(new TestSuite(TreeSubMapTest.class));
suite.addTest(new TestSuite(TreeSetTest.class));
suite.addTest(new TestSuite(TreeSubSetTest.class));
return suite;
}
public static long SHORT_DELAY_MS;
public static long SMALL_DELAY_MS;
public static long MEDIUM_DELAY_MS;
public static long LONG_DELAY_MS;
/**
* Returns the shortest timed delay.
*/
protected long getShortDelay() {
return Long.getLong("tck.shortDelay", 300).longValue();
}
/**
* Sets delays as multiples of SHORT_DELAY.
*/
protected void setDelays() {
SHORT_DELAY_MS = getShortDelay();
SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
LONG_DELAY_MS = SHORT_DELAY_MS * 50;
}
/**
* Flag set true if any threadAssert methods fail
*/
volatile boolean threadFailed;
/**
* Initializes test to indicate that no thread assertions have failed
*/
public void setUp() {
setDelays();
threadFailed = false;
}
/**
* Triggers test case failure if any thread assertions have failed
*/
public void tearDown() {
assertFalse(threadFailed);
}
/**
* Fail, also setting status to indicate current testcase should fail
*/
public void threadFail(String reason) {
threadFailed = true;
fail(reason);
}
/**
* If expression not true, set status to indicate current testcase
* should fail
*/
public void threadAssertTrue(boolean b) {
if (!b) {
threadFailed = true;
assertTrue(b);
}
}
/**
* If expression not false, set status to indicate current testcase
* should fail
*/
public void threadAssertFalse(boolean b) {
if (b) {
threadFailed = true;
assertFalse(b);
}
}
/**
* If argument not null, set status to indicate current testcase
* should fail
*/
public void threadAssertNull(Object x) {
if (x != null) {
threadFailed = true;
assertNull(x);
}
}
/**
* If arguments not equal, set status to indicate current testcase
* should fail
*/
public void threadAssertEquals(long x, long y) {
if (x != y) {
threadFailed = true;
assertEquals(x, y);
}
}
/**
* If arguments not equal, set status to indicate current testcase
* should fail
*/
public void threadAssertEquals(Object x, Object y) {
if (x != y && (x == null || !x.equals(y))) {
threadFailed = true;
assertEquals(x, y);
}
}
/**
* threadFail with message "should throw exception"
*/
public void threadShouldThrow() {
threadFailed = true;
fail("should throw exception");
}
/**
* threadFail with message "Unexpected exception"
*/
public void threadUnexpectedException() {
threadFailed = true;
fail("Unexpected exception");
}
/**
* Wait out termination of a thread pool or fail doing so
*/
public void joinPool(ExecutorService exec) {
try {
exec.shutdown();
assertTrue(exec.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
} catch(SecurityException ok) {
// Allowed in case test doesn't have privs
} catch(InterruptedException ie) {
fail("Unexpected exception");
}
}
/**
* fail with message "should throw exception"
*/
public void shouldThrow() {
fail("Should throw exception");
}
/**
* fail with message "Unexpected exception"
*/
public void unexpectedException() {
fail("Unexpected exception");
}
/**
* The number of elements to place in collections, arrays, etc.
*/
static final int SIZE = 20;
// Some convenient Integer constants
static final Integer zero = new Integer(0);
static final Integer one = new Integer(1);
static final Integer two = new Integer(2);
static final Integer three = new Integer(3);
static final Integer four = new Integer(4);
static final Integer five = new Integer(5);
static final Integer six = new Integer(6);
static final Integer seven = new Integer(7);
static final Integer eight = new Integer(8);
static final Integer nine = new Integer(9);
static final Integer m1 = new Integer(-1);
static final Integer m2 = new Integer(-2);
static final Integer m3 = new Integer(-3);
static final Integer m4 = new Integer(-4);
static final Integer m5 = new Integer(-5);
static final Integer m6 = new Integer(-6);
static final Integer m10 = new Integer(-10);
/**
* A security policy where new permissions can be dynamically added
* or all cleared.
*/
static class AdjustablePolicy extends java.security.Policy {
Permissions perms = new Permissions();
AdjustablePolicy() { }
void addPermission(Permission perm) { perms.add(perm); }
void clearPermissions() { perms = new Permissions(); }
public PermissionCollection getPermissions(CodeSource cs) {
return perms;
}
public PermissionCollection getPermissions(ProtectionDomain pd) {
return perms;
}
public boolean implies(ProtectionDomain pd, Permission p) {
return perms.implies(p);
}
public void refresh() {}
}
// Some convenient Runnable classes
static class NoOpRunnable implements Runnable {
public void run() {}
}
static class NoOpCallable implements Callable {
public Object call() { return Boolean.TRUE; }
}
static final String TEST_STRING = "a test string";
static class StringTask implements Callable {
public Object call() { return TEST_STRING; }
}
static class NPETask implements Callable {
public Object call() { throw new NullPointerException(); }
}
static class CallableOne implements Callable {
public Object call() { return one; }
}
class ShortRunnable implements Runnable {
public void run() {
try {
Thread.sleep(SHORT_DELAY_MS);
}
catch(Exception e) {
threadUnexpectedException();
}
}
}
class ShortInterruptedRunnable implements Runnable {
public void run() {
try {
Thread.sleep(SHORT_DELAY_MS);
threadShouldThrow();
}
catch(InterruptedException success) {
}
}
}
class SmallRunnable implements Runnable {
public void run() {
try {
Thread.sleep(SMALL_DELAY_MS);
}
catch(Exception e) {
threadUnexpectedException();
}
}
}
class SmallPossiblyInterruptedRunnable implements Runnable {
public void run() {
try {
Thread.sleep(SMALL_DELAY_MS);
}
catch(Exception e) {
}
}
}
class SmallCallable implements Callable {
public Object call() {
try {
Thread.sleep(SMALL_DELAY_MS);
}
catch(Exception e) {
threadUnexpectedException();
}
return Boolean.TRUE;
}
}
class SmallInterruptedRunnable implements Runnable {
public void run() {
try {
Thread.sleep(SMALL_DELAY_MS);
threadShouldThrow();
}
catch(InterruptedException success) {
}
}
}
class MediumRunnable implements Runnable {
public void run() {
try {
Thread.sleep(MEDIUM_DELAY_MS);
}
catch(Exception e) {
threadUnexpectedException();
}
}
}
class MediumInterruptedRunnable implements Runnable {
public void run() {
try {
Thread.sleep(MEDIUM_DELAY_MS);
threadShouldThrow();
}
catch(InterruptedException success) {
}
}
}
class MediumPossiblyInterruptedRunnable implements Runnable {
public void run() {
try {
Thread.sleep(MEDIUM_DELAY_MS);
}
catch(InterruptedException success) {
}
}
}
class LongPossiblyInterruptedRunnable implements Runnable {
public void run() {
try {
Thread.sleep(LONG_DELAY_MS);
}
catch(InterruptedException success) {
}
}
}
/**
* For use as ThreadFactory in constructors
*/
static class SimpleThreadFactory implements ThreadFactory{
public Thread newThread(Runnable r){
return new Thread(r);
}
}
static class TrackedShortRunnable implements Runnable {
volatile boolean done = false;
public void run() {
try {
Thread.sleep(SMALL_DELAY_MS);
done = true;
} catch(Exception e){
}
}
}
static class TrackedMediumRunnable implements Runnable {
volatile boolean done = false;
public void run() {
try {
Thread.sleep(MEDIUM_DELAY_MS);
done = true;
} catch(Exception e){
}
}
}
static class TrackedLongRunnable implements Runnable {
volatile boolean done = false;
public void run() {
try {
Thread.sleep(LONG_DELAY_MS);
done = true;
} catch(Exception e){
}
}
}
static class TrackedNoOpRunnable implements Runnable {
volatile boolean done = false;
public void run() {
done = true;
}
}
static class TrackedCallable implements Callable {
volatile boolean done = false;
public Object call() {
try {
Thread.sleep(SMALL_DELAY_MS);
done = true;
} catch(Exception e){
}
return Boolean.TRUE;
}
}
/**
* For use as RejectedExecutionHandler in constructors
*/
static class NoOpREHandler implements RejectedExecutionHandler{
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor){}
}
}
backport-util-concurrent-3.1-src/test/tck/src/AtomicIntegerTest.java 0000644 0017507 0003772 00000016437 10253674160 024511 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import java.io.*;
public class AtomicIntegerTest extends JSR166TestCase {
public static void main (String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(AtomicIntegerTest.class);
}
/**
* constructor initializes to given value
*/
public void testConstructor(){
AtomicInteger ai = new AtomicInteger(1);
assertEquals(1,ai.get());
}
/**
* default constructed initializes to zero
*/
public void testConstructor2(){
AtomicInteger ai = new AtomicInteger();
assertEquals(0,ai.get());
}
/**
* get returns the last value set
*/
public void testGetSet(){
AtomicInteger ai = new AtomicInteger(1);
assertEquals(1,ai.get());
ai.set(2);
assertEquals(2,ai.get());
ai.set(-3);
assertEquals(-3,ai.get());
}
/**
* get returns the last value lazySet in same thread
*/
public void testGetLazySet(){
AtomicInteger ai = new AtomicInteger(1);
assertEquals(1,ai.get());
ai.lazySet(2);
assertEquals(2,ai.get());
ai.lazySet(-3);
assertEquals(-3,ai.get());
}
/**
* compareAndSet succeeds in changing value if equal to expected else fails
*/
public void testCompareAndSet(){
AtomicInteger ai = new AtomicInteger(1);
assertTrue(ai.compareAndSet(1,2));
assertTrue(ai.compareAndSet(2,-4));
assertEquals(-4,ai.get());
assertFalse(ai.compareAndSet(-5,7));
assertFalse((7 == ai.get()));
assertTrue(ai.compareAndSet(-4,7));
assertEquals(7,ai.get());
}
/**
* compareAndSet in one thread enables another waiting for value
* to succeed
*/
public void testCompareAndSetInMultipleThreads() {
final AtomicInteger ai = new AtomicInteger(1);
Thread t = new Thread(new Runnable() {
public void run() {
while(!ai.compareAndSet(2, 3)) Thread.yield();
}});
try {
t.start();
assertTrue(ai.compareAndSet(1, 2));
t.join(LONG_DELAY_MS);
assertFalse(t.isAlive());
assertEquals(ai.get(), 3);
}
catch(Exception e) {
unexpectedException();
}
}
/**
* repeated weakCompareAndSet succeeds in changing value when equal
* to expected
*/
public void testWeakCompareAndSet(){
AtomicInteger ai = new AtomicInteger(1);
while(!ai.weakCompareAndSet(1,2));
while(!ai.weakCompareAndSet(2,-4));
assertEquals(-4,ai.get());
while(!ai.weakCompareAndSet(-4,7));
assertEquals(7,ai.get());
}
/**
* getAndSet returns previous value and sets to given value
*/
public void testGetAndSet(){
AtomicInteger ai = new AtomicInteger(1);
assertEquals(1,ai.getAndSet(0));
assertEquals(0,ai.getAndSet(-10));
assertEquals(-10,ai.getAndSet(1));
}
/**
* getAndAdd returns previous value and adds given value
*/
public void testGetAndAdd(){
AtomicInteger ai = new AtomicInteger(1);
assertEquals(1,ai.getAndAdd(2));
assertEquals(3,ai.get());
assertEquals(3,ai.getAndAdd(-4));
assertEquals(-1,ai.get());
}
/**
* getAndDecrement returns previous value and decrements
*/
public void testGetAndDecrement(){
AtomicInteger ai = new AtomicInteger(1);
assertEquals(1,ai.getAndDecrement());
assertEquals(0,ai.getAndDecrement());
assertEquals(-1,ai.getAndDecrement());
}
/**
* getAndIncrement returns previous value and increments
*/
public void testGetAndIncrement(){
AtomicInteger ai = new AtomicInteger(1);
assertEquals(1,ai.getAndIncrement());
assertEquals(2,ai.get());
ai.set(-2);
assertEquals(-2,ai.getAndIncrement());
assertEquals(-1,ai.getAndIncrement());
assertEquals(0,ai.getAndIncrement());
assertEquals(1,ai.get());
}
/**
* addAndGet adds given value to current, and returns current value
*/
public void testAddAndGet(){
AtomicInteger ai = new AtomicInteger(1);
assertEquals(3,ai.addAndGet(2));
assertEquals(3,ai.get());
assertEquals(-1,ai.addAndGet(-4));
assertEquals(-1,ai.get());
}
/**
* decrementAndGet decrements and returns current value
*/
public void testDecrementAndGet(){
AtomicInteger ai = new AtomicInteger(1);
assertEquals(0,ai.decrementAndGet());
assertEquals(-1,ai.decrementAndGet());
assertEquals(-2,ai.decrementAndGet());
assertEquals(-2,ai.get());
}
/**
* incrementAndGet increments and returns current value
*/
public void testIncrementAndGet(){
AtomicInteger ai = new AtomicInteger(1);
assertEquals(2,ai.incrementAndGet());
assertEquals(2,ai.get());
ai.set(-2);
assertEquals(-1,ai.incrementAndGet());
assertEquals(0,ai.incrementAndGet());
assertEquals(1,ai.incrementAndGet());
assertEquals(1,ai.get());
}
/**
* a deserialized serialized atomic holds same value
*/
public void testSerialization() {
AtomicInteger l = new AtomicInteger();
try {
l.set(22);
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(l);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
AtomicInteger r = (AtomicInteger) in.readObject();
assertEquals(l.get(), r.get());
} catch(Exception e){
unexpectedException();
}
}
/**
* toString returns current value.
*/
public void testToString() {
AtomicInteger ai = new AtomicInteger();
for (int i = -12; i < 6; ++i) {
ai.set(i);
assertEquals(ai.toString(), Integer.toString(i));
}
}
/**
* intValue returns current value.
*/
public void testIntValue() {
AtomicInteger ai = new AtomicInteger();
for (int i = -12; i < 6; ++i) {
ai.set(i);
assertEquals(i, ai.intValue());
}
}
/**
* longValue returns current value.
*/
public void testLongValue() {
AtomicInteger ai = new AtomicInteger();
for (int i = -12; i < 6; ++i) {
ai.set(i);
assertEquals((long)i, ai.longValue());
}
}
/**
* floatValue returns current value.
*/
public void testFloatValue() {
AtomicInteger ai = new AtomicInteger();
for (int i = -12; i < 6; ++i) {
ai.set(i);
assertEquals((float)i, ai.floatValue(), 0.0f);
}
}
/**
* doubleValue returns current value.
*/
public void testDoubleValue() {
AtomicInteger ai = new AtomicInteger();
for (int i = -12; i < 6; ++i) {
ai.set(i);
assertEquals((double)i, ai.doubleValue(), 0.0);
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/AbstractQueuedSynchronizerTest.java 0000644 0017507 0003772 00000117644 10253674160 027313 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import java.io.*;
public class AbstractQueuedSynchronizerTest extends JSR166TestCase {
// public static void main(String[] args) {
// junit.textui.TestRunner.run (suite());
// }
// public static Test suite() {
// return new TestSuite(AbstractQueuedSynchronizerTest.class);
// }
//
// /**
// * A simple mutex class, adapted from the
// * AbstractQueuedSynchronizer javadoc. Exclusive acquire tests
// * exercise this as a sample user extension. Other
// * methods/features of AbstractQueuedSynchronizerTest are tested
// * via other test classes, including those for ReentrantLock,
// * ReentrantReadWriteLock, and Semaphore
// */
// static class Mutex extends AbstractQueuedSynchronizer {
// public boolean isHeldExclusively() { return getState() == 1; }
//
// public boolean tryAcquire(int acquires) {
// assertTrue(acquires == 1);
// return compareAndSetState(0, 1);
// }
//
// public boolean tryRelease(int releases) {
// if (getState() == 0) throw new IllegalMonitorStateException();
// setState(0);
// return true;
// }
//
// public AbstractQueuedSynchronizer.ConditionObject newCondition() { return new AbstractQueuedSynchronizer.ConditionObject(); }
//
// }
//
//
// /**
// * A simple latch class, to test shared mode.
// */
// static class BooleanLatch extends AbstractQueuedSynchronizer {
// public boolean isSignalled() { return getState() != 0; }
//
// public int tryAcquireShared(int ignore) {
// return isSignalled()? 1 : -1;
// }
//
// public boolean tryReleaseShared(int ignore) {
// setState(1);
// return true;
// }
// }
//
// /**
// * A runnable calling acquireInterruptibly
// */
// class InterruptibleSyncRunnable implements Runnable {
// final Mutex sync;
// InterruptibleSyncRunnable(Mutex l) { sync = l; }
// public void run() {
// try {
// sync.acquireInterruptibly(1);
// } catch(InterruptedException success){}
// }
// }
//
//
// /**
// * A runnable calling acquireInterruptibly that expects to be
// * interrupted
// */
// class InterruptedSyncRunnable implements Runnable {
// final Mutex sync;
// InterruptedSyncRunnable(Mutex l) { sync = l; }
// public void run() {
// try {
// sync.acquireInterruptibly(1);
// threadShouldThrow();
// } catch(InterruptedException success){}
// }
// }
//
// /**
// * isHeldExclusively is false upon construction
// */
// public void testIsHeldExclusively() {
// Mutex rl = new Mutex();
// assertFalse(rl.isHeldExclusively());
// }
//
// /**
// * acquiring released sync succeeds
// */
// public void testAcquire() {
// Mutex rl = new Mutex();
// rl.acquire(1);
// assertTrue(rl.isHeldExclusively());
// rl.release(1);
// assertFalse(rl.isHeldExclusively());
// }
//
// /**
// * tryAcquire on an released sync succeeds
// */
// public void testTryAcquire() {
// Mutex rl = new Mutex();
// assertTrue(rl.tryAcquire(1));
// assertTrue(rl.isHeldExclusively());
// rl.release(1);
// }
//
// /**
// * hasQueuedThreads reports whether there are waiting threads
// */
// public void testhasQueuedThreads() {
// final Mutex sync = new Mutex();
// Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
// Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
// try {
// assertFalse(sync.hasQueuedThreads());
// sync.acquire(1);
// t1.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.hasQueuedThreads());
// t2.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.hasQueuedThreads());
// t1.interrupt();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.hasQueuedThreads());
// sync.release(1);
// Thread.sleep(SHORT_DELAY_MS);
// assertFalse(sync.hasQueuedThreads());
// t1.join();
// t2.join();
// } catch(Exception e){
// unexpectedException();
// }
// }
//
// /**
// * isQueued(null) throws NPE
// */
// public void testIsQueuedNPE() {
// final Mutex sync = new Mutex();
// try {
// sync.isQueued(null);
// shouldThrow();
// } catch (NullPointerException success) {
// }
// }
//
// /**
// * isQueued reports whether a thread is queued.
// */
// public void testIsQueued() {
// final Mutex sync = new Mutex();
// Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
// Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
// try {
// assertFalse(sync.isQueued(t1));
// assertFalse(sync.isQueued(t2));
// sync.acquire(1);
// t1.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.isQueued(t1));
// t2.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.isQueued(t1));
// assertTrue(sync.isQueued(t2));
// t1.interrupt();
// Thread.sleep(SHORT_DELAY_MS);
// assertFalse(sync.isQueued(t1));
// assertTrue(sync.isQueued(t2));
// sync.release(1);
// Thread.sleep(SHORT_DELAY_MS);
// assertFalse(sync.isQueued(t1));
// Thread.sleep(SHORT_DELAY_MS);
// assertFalse(sync.isQueued(t2));
// t1.join();
// t2.join();
// } catch(Exception e){
// unexpectedException();
// }
// }
//
// /**
// * getFirstQueuedThread returns first waiting thread or null if none
// */
// public void testGetFirstQueuedThread() {
// final Mutex sync = new Mutex();
// Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
// Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
// try {
// assertNull(sync.getFirstQueuedThread());
// sync.acquire(1);
// t1.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertEquals(t1, sync.getFirstQueuedThread());
// t2.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertEquals(t1, sync.getFirstQueuedThread());
// t1.interrupt();
// Thread.sleep(SHORT_DELAY_MS);
// Thread.sleep(SHORT_DELAY_MS);
// assertEquals(t2, sync.getFirstQueuedThread());
// sync.release(1);
// Thread.sleep(SHORT_DELAY_MS);
// assertNull(sync.getFirstQueuedThread());
// t1.join();
// t2.join();
// } catch(Exception e){
// unexpectedException();
// }
// }
//
//
// /**
// * hasContended reports false if no thread has ever blocked, else true
// */
// public void testHasContended() {
// final Mutex sync = new Mutex();
// Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
// Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
// try {
// assertFalse(sync.hasContended());
// sync.acquire(1);
// t1.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.hasContended());
// t2.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.hasContended());
// t1.interrupt();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.hasContended());
// sync.release(1);
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.hasContended());
// t1.join();
// t2.join();
// } catch(Exception e){
// unexpectedException();
// }
// }
//
// /**
// * getQueuedThreads includes waiting threads
// */
// public void testGetQueuedThreads() {
// final Mutex sync = new Mutex();
// Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
// Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
// try {
// assertTrue(sync.getQueuedThreads().isEmpty());
// sync.acquire(1);
// assertTrue(sync.getQueuedThreads().isEmpty());
// t1.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.getQueuedThreads().contains(t1));
// t2.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.getQueuedThreads().contains(t1));
// assertTrue(sync.getQueuedThreads().contains(t2));
// t1.interrupt();
// Thread.sleep(SHORT_DELAY_MS);
// assertFalse(sync.getQueuedThreads().contains(t1));
// assertTrue(sync.getQueuedThreads().contains(t2));
// sync.release(1);
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.getQueuedThreads().isEmpty());
// t1.join();
// t2.join();
// } catch(Exception e){
// unexpectedException();
// }
// }
//
// /**
// * getExclusiveQueuedThreads includes waiting threads
// */
// public void testGetExclusiveQueuedThreads() {
// final Mutex sync = new Mutex();
// Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
// Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
// try {
// assertTrue(sync.getExclusiveQueuedThreads().isEmpty());
// sync.acquire(1);
// assertTrue(sync.getExclusiveQueuedThreads().isEmpty());
// t1.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.getExclusiveQueuedThreads().contains(t1));
// t2.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.getExclusiveQueuedThreads().contains(t1));
// assertTrue(sync.getExclusiveQueuedThreads().contains(t2));
// t1.interrupt();
// Thread.sleep(SHORT_DELAY_MS);
// assertFalse(sync.getExclusiveQueuedThreads().contains(t1));
// assertTrue(sync.getExclusiveQueuedThreads().contains(t2));
// sync.release(1);
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.getExclusiveQueuedThreads().isEmpty());
// t1.join();
// t2.join();
// } catch(Exception e){
// unexpectedException();
// }
// }
//
// /**
// * getSharedQueuedThreads does not include exclusively waiting threads
// */
// public void testGetSharedQueuedThreads() {
// final Mutex sync = new Mutex();
// Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
// Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
// try {
// assertTrue(sync.getSharedQueuedThreads().isEmpty());
// sync.acquire(1);
// assertTrue(sync.getSharedQueuedThreads().isEmpty());
// t1.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.getSharedQueuedThreads().isEmpty());
// t2.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.getSharedQueuedThreads().isEmpty());
// t1.interrupt();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.getSharedQueuedThreads().isEmpty());
// sync.release(1);
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.getSharedQueuedThreads().isEmpty());
// t1.join();
// t2.join();
// } catch(Exception e){
// unexpectedException();
// }
// }
//
// /**
// * tryAcquireNanos is interruptible.
// */
// public void testInterruptedException2() {
// final Mutex sync = new Mutex();
// sync.acquire(1);
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// sync.tryAcquireNanos(1, MEDIUM_DELAY_MS * 1000 * 1000);
// threadShouldThrow();
// } catch(InterruptedException success){}
// }
// });
// try {
// t.start();
// t.interrupt();
// } catch(Exception e){
// unexpectedException();
// }
// }
//
//
// /**
// * TryAcquire on exclusively held sync fails
// */
// public void testTryAcquireWhenSynced() {
// final Mutex sync = new Mutex();
// sync.acquire(1);
// Thread t = new Thread(new Runnable() {
// public void run() {
// threadAssertFalse(sync.tryAcquire(1));
// }
// });
// try {
// t.start();
// t.join();
// sync.release(1);
// } catch(Exception e){
// unexpectedException();
// }
// }
//
// /**
// * tryAcquireNanos on an exclusively held sync times out
// */
// public void testAcquireNanos_Timeout() {
// final Mutex sync = new Mutex();
// sync.acquire(1);
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// threadAssertFalse(sync.tryAcquireNanos(1, 1000 * 1000));
// } catch (Exception ex) {
// threadUnexpectedException();
// }
// }
// });
// try {
// t.start();
// t.join();
// sync.release(1);
// } catch(Exception e){
// unexpectedException();
// }
// }
//
//
// /**
// * getState is true when acquired and false when not
// */
// public void testGetState() {
// final Mutex sync = new Mutex();
// sync.acquire(1);
// assertTrue(sync.isHeldExclusively());
// sync.release(1);
// assertFalse(sync.isHeldExclusively());
// Thread t = new Thread(new Runnable() {
// public void run() {
// sync.acquire(1);
// try {
// Thread.sleep(SMALL_DELAY_MS);
// }
// catch(Exception e) {
// threadUnexpectedException();
// }
// sync.release(1);
// }
// });
// try {
// t.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.isHeldExclusively());
// t.join();
// assertFalse(sync.isHeldExclusively());
// } catch(Exception e){
// unexpectedException();
// }
// }
//
//
// /**
// * acquireInterruptibly is interruptible.
// */
// public void testAcquireInterruptibly1() {
// final Mutex sync = new Mutex();
// sync.acquire(1);
// Thread t = new Thread(new InterruptedSyncRunnable(sync));
// try {
// t.start();
// t.interrupt();
// sync.release(1);
// t.join();
// } catch(Exception e){
// unexpectedException();
// }
// }
//
// /**
// * acquireInterruptibly succeeds when released, else is interruptible
// */
// public void testAcquireInterruptibly2() {
// final Mutex sync = new Mutex();
// try {
// sync.acquireInterruptibly(1);
// } catch(Exception e) {
// unexpectedException();
// }
// Thread t = new Thread(new InterruptedSyncRunnable(sync));
// try {
// t.start();
// t.interrupt();
// assertTrue(sync.isHeldExclusively());
// t.join();
// } catch(Exception e){
// unexpectedException();
// }
// }
//
// /**
// * owns is true for a condition created by sync else false
// */
// public void testOwns() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
// final Mutex sync2 = new Mutex();
// assertTrue(sync.owns(c));
// assertFalse(sync2.owns(c));
// }
//
// /**
// * Calling await without holding sync throws IllegalMonitorStateException
// */
// public void testAwait_IllegalMonitor() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
// try {
// c.await();
// shouldThrow();
// }
// catch (IllegalMonitorStateException success) {
// }
// catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * Calling signal without holding sync throws IllegalMonitorStateException
// */
// public void testSignal_IllegalMonitor() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
// try {
// c.signal();
// shouldThrow();
// }
// catch (IllegalMonitorStateException success) {
// }
// catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * awaitNanos without a signal times out
// */
// public void testAwaitNanos_Timeout() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
// try {
// sync.acquire(1);
// long t = c.awaitNanos(100);
// assertTrue(t <= 0);
// sync.release(1);
// }
// catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * Timed await without a signal times out
// */
// public void testAwait_Timeout() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
// try {
// sync.acquire(1);
// assertFalse(c.await(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
// sync.release(1);
// }
// catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * awaitUntil without a signal times out
// */
// public void testAwaitUntil_Timeout() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
// try {
// sync.acquire(1);
// edu.emory.mathcs.backport.java.util.Date d = new edu.emory.mathcs.backport.java.util.Date();
// assertFalse(c.awaitUntil(new edu.emory.mathcs.backport.java.util.Date(d.getTime() + 10)));
// sync.release(1);
// }
// catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * await returns when signalled
// */
// public void testAwait() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// sync.acquire(1);
// c.await();
// sync.release(1);
// }
// catch(InterruptedException e) {
// threadUnexpectedException();
// }
// }
// });
//
// try {
// t.start();
// Thread.sleep(SHORT_DELAY_MS);
// sync.acquire(1);
// c.signal();
// sync.release(1);
// t.join(SHORT_DELAY_MS);
// assertFalse(t.isAlive());
// }
// catch (Exception ex) {
// unexpectedException();
// }
// }
//
//
//
// /**
// * hasWaiters throws NPE if null
// */
// public void testHasWaitersNPE() {
// final Mutex sync = new Mutex();
// try {
// sync.hasWaiters(null);
// shouldThrow();
// } catch (NullPointerException success) {
// } catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * getWaitQueueLength throws NPE if null
// */
// public void testGetWaitQueueLengthNPE() {
// final Mutex sync = new Mutex();
// try {
// sync.getWaitQueueLength(null);
// shouldThrow();
// } catch (NullPointerException success) {
// } catch (Exception ex) {
// unexpectedException();
// }
// }
//
//
// /**
// * getWaitingThreads throws NPE if null
// */
// public void testGetWaitingThreadsNPE() {
// final Mutex sync = new Mutex();
// try {
// sync.getWaitingThreads(null);
// shouldThrow();
// } catch (NullPointerException success) {
// } catch (Exception ex) {
// unexpectedException();
// }
// }
//
//
// /**
// * hasWaiters throws IAE if not owned
// */
// public void testHasWaitersIAE() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = (sync.newCondition());
// final Mutex sync2 = new Mutex();
// try {
// sync2.hasWaiters(c);
// shouldThrow();
// } catch (IllegalArgumentException success) {
// } catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * hasWaiters throws IMSE if not synced
// */
// public void testHasWaitersIMSE() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = (sync.newCondition());
// try {
// sync.hasWaiters(c);
// shouldThrow();
// } catch (IllegalMonitorStateException success) {
// } catch (Exception ex) {
// unexpectedException();
// }
// }
//
//
// /**
// * getWaitQueueLength throws IAE if not owned
// */
// public void testGetWaitQueueLengthIAE() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = (sync.newCondition());
// final Mutex sync2 = new Mutex();
// try {
// sync2.getWaitQueueLength(c);
// shouldThrow();
// } catch (IllegalArgumentException success) {
// } catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * getWaitQueueLength throws IMSE if not synced
// */
// public void testGetWaitQueueLengthIMSE() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = (sync.newCondition());
// try {
// sync.getWaitQueueLength(c);
// shouldThrow();
// } catch (IllegalMonitorStateException success) {
// } catch (Exception ex) {
// unexpectedException();
// }
// }
//
//
// /**
// * getWaitingThreads throws IAE if not owned
// */
// public void testGetWaitingThreadsIAE() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = (sync.newCondition());
// final Mutex sync2 = new Mutex();
// try {
// sync2.getWaitingThreads(c);
// shouldThrow();
// } catch (IllegalArgumentException success) {
// } catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * getWaitingThreads throws IMSE if not synced
// */
// public void testGetWaitingThreadsIMSE() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = (sync.newCondition());
// try {
// sync.getWaitingThreads(c);
// shouldThrow();
// } catch (IllegalMonitorStateException success) {
// } catch (Exception ex) {
// unexpectedException();
// }
// }
//
//
//
// /**
// * hasWaiters returns true when a thread is waiting, else false
// */
// public void testHasWaiters() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// sync.acquire(1);
// threadAssertFalse(sync.hasWaiters(c));
// threadAssertEquals(0, sync.getWaitQueueLength(c));
// c.await();
// sync.release(1);
// }
// catch(InterruptedException e) {
// threadUnexpectedException();
// }
// }
// });
//
// try {
// t.start();
// Thread.sleep(SHORT_DELAY_MS);
// sync.acquire(1);
// assertTrue(sync.hasWaiters(c));
// assertEquals(1, sync.getWaitQueueLength(c));
// c.signal();
// sync.release(1);
// Thread.sleep(SHORT_DELAY_MS);
// sync.acquire(1);
// assertFalse(sync.hasWaiters(c));
// assertEquals(0, sync.getWaitQueueLength(c));
// sync.release(1);
// t.join(SHORT_DELAY_MS);
// assertFalse(t.isAlive());
// }
// catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * getWaitQueueLength returns number of waiting threads
// */
// public void testGetWaitQueueLength() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
// Thread t1 = new Thread(new Runnable() {
// public void run() {
// try {
// sync.acquire(1);
// threadAssertFalse(sync.hasWaiters(c));
// threadAssertEquals(0, sync.getWaitQueueLength(c));
// c.await();
// sync.release(1);
// }
// catch(InterruptedException e) {
// threadUnexpectedException();
// }
// }
// });
//
// Thread t2 = new Thread(new Runnable() {
// public void run() {
// try {
// sync.acquire(1);
// threadAssertTrue(sync.hasWaiters(c));
// threadAssertEquals(1, sync.getWaitQueueLength(c));
// c.await();
// sync.release(1);
// }
// catch(InterruptedException e) {
// threadUnexpectedException();
// }
// }
// });
//
// try {
// t1.start();
// Thread.sleep(SHORT_DELAY_MS);
// t2.start();
// Thread.sleep(SHORT_DELAY_MS);
// sync.acquire(1);
// assertTrue(sync.hasWaiters(c));
// assertEquals(2, sync.getWaitQueueLength(c));
// c.signalAll();
// sync.release(1);
// Thread.sleep(SHORT_DELAY_MS);
// sync.acquire(1);
// assertFalse(sync.hasWaiters(c));
// assertEquals(0, sync.getWaitQueueLength(c));
// sync.release(1);
// t1.join(SHORT_DELAY_MS);
// t2.join(SHORT_DELAY_MS);
// assertFalse(t1.isAlive());
// assertFalse(t2.isAlive());
// }
// catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * getWaitingThreads returns only and all waiting threads
// */
// public void testGetWaitingThreads() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
// Thread t1 = new Thread(new Runnable() {
// public void run() {
// try {
// sync.acquire(1);
// threadAssertTrue(sync.getWaitingThreads(c).isEmpty());
// c.await();
// sync.release(1);
// }
// catch(InterruptedException e) {
// threadUnexpectedException();
// }
// }
// });
//
// Thread t2 = new Thread(new Runnable() {
// public void run() {
// try {
// sync.acquire(1);
// threadAssertFalse(sync.getWaitingThreads(c).isEmpty());
// c.await();
// sync.release(1);
// }
// catch(InterruptedException e) {
// threadUnexpectedException();
// }
// }
// });
//
// try {
// sync.acquire(1);
// assertTrue(sync.getWaitingThreads(c).isEmpty());
// sync.release(1);
// t1.start();
// Thread.sleep(SHORT_DELAY_MS);
// t2.start();
// Thread.sleep(SHORT_DELAY_MS);
// sync.acquire(1);
// assertTrue(sync.hasWaiters(c));
// assertTrue(sync.getWaitingThreads(c).contains(t1));
// assertTrue(sync.getWaitingThreads(c).contains(t2));
// c.signalAll();
// sync.release(1);
// Thread.sleep(SHORT_DELAY_MS);
// sync.acquire(1);
// assertFalse(sync.hasWaiters(c));
// assertTrue(sync.getWaitingThreads(c).isEmpty());
// sync.release(1);
// t1.join(SHORT_DELAY_MS);
// t2.join(SHORT_DELAY_MS);
// assertFalse(t1.isAlive());
// assertFalse(t2.isAlive());
// }
// catch (Exception ex) {
// unexpectedException();
// }
// }
//
//
//
// /**
// * awaitUninterruptibly doesn't abort on interrupt
// */
// public void testAwaitUninterruptibly() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
// Thread t = new Thread(new Runnable() {
// public void run() {
// sync.acquire(1);
// c.awaitUninterruptibly();
// sync.release(1);
// }
// });
//
// try {
// t.start();
// Thread.sleep(SHORT_DELAY_MS);
// t.interrupt();
// sync.acquire(1);
// c.signal();
// sync.release(1);
// t.join(SHORT_DELAY_MS);
// assertFalse(t.isAlive());
// }
// catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * await is interruptible
// */
// public void testAwait_Interrupt() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// sync.acquire(1);
// c.await();
// sync.release(1);
// threadShouldThrow();
// }
// catch(InterruptedException success) {
// }
// }
// });
//
// try {
// t.start();
// Thread.sleep(SHORT_DELAY_MS);
// t.interrupt();
// t.join(SHORT_DELAY_MS);
// assertFalse(t.isAlive());
// }
// catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * awaitNanos is interruptible
// */
// public void testAwaitNanos_Interrupt() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// sync.acquire(1);
// c.awaitNanos(1000 * 1000 * 1000); // 1 sec
// sync.release(1);
// threadShouldThrow();
// }
// catch(InterruptedException success) {
// }
// }
// });
//
// try {
// t.start();
// Thread.sleep(SHORT_DELAY_MS);
// t.interrupt();
// t.join(SHORT_DELAY_MS);
// assertFalse(t.isAlive());
// }
// catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * awaitUntil is interruptible
// */
// public void testAwaitUntil_Interrupt() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// sync.acquire(1);
// edu.emory.mathcs.backport.java.util.Date d = new edu.emory.mathcs.backport.java.util.Date();
// c.awaitUntil(new edu.emory.mathcs.backport.java.util.Date(d.getTime() + 10000));
// sync.release(1);
// threadShouldThrow();
// }
// catch(InterruptedException success) {
// }
// }
// });
//
// try {
// t.start();
// Thread.sleep(SHORT_DELAY_MS);
// t.interrupt();
// t.join(SHORT_DELAY_MS);
// assertFalse(t.isAlive());
// }
// catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * signalAll wakes up all threads
// */
// public void testSignalAll() {
// final Mutex sync = new Mutex();
// final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
// Thread t1 = new Thread(new Runnable() {
// public void run() {
// try {
// sync.acquire(1);
// c.await();
// sync.release(1);
// }
// catch(InterruptedException e) {
// threadUnexpectedException();
// }
// }
// });
//
// Thread t2 = new Thread(new Runnable() {
// public void run() {
// try {
// sync.acquire(1);
// c.await();
// sync.release(1);
// }
// catch(InterruptedException e) {
// threadUnexpectedException();
// }
// }
// });
//
// try {
// t1.start();
// t2.start();
// Thread.sleep(SHORT_DELAY_MS);
// sync.acquire(1);
// c.signalAll();
// sync.release(1);
// t1.join(SHORT_DELAY_MS);
// t2.join(SHORT_DELAY_MS);
// assertFalse(t1.isAlive());
// assertFalse(t2.isAlive());
// }
// catch (Exception ex) {
// unexpectedException();
// }
// }
//
//
// /**
// * toString indicates current state
// */
// public void testToString() {
// Mutex sync = new Mutex();
// String us = sync.toString();
// assertTrue(us.indexOf("State = 0") >= 0);
// sync.acquire(1);
// String ls = sync.toString();
// assertTrue(ls.indexOf("State = 1") >= 0);
// }
//
// /**
// * A serialized AQS deserializes with current state
// */
// public void testSerialization() {
// Mutex l = new Mutex();
// l.acquire(1);
// assertTrue(l.isHeldExclusively());
//
// try {
// ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
// ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
// out.writeObject(l);
// out.close();
//
// ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
// ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
// Mutex r = (Mutex) in.readObject();
// assertTrue(r.isHeldExclusively());
// } catch(Exception e){
// e.printStackTrace();
// unexpectedException();
// }
// }
//
//
// /**
// * tryReleaseShared setting state changes getState
// */
// public void testGetStateWithReleaseShared() {
// final BooleanLatch l = new BooleanLatch();
// assertFalse(l.isSignalled());
// l.releaseShared(0);
// assertTrue(l.isSignalled());
// }
//
// /**
// * releaseShared has no effect when already signalled
// */
// public void testReleaseShared() {
// final BooleanLatch l = new BooleanLatch();
// assertFalse(l.isSignalled());
// l.releaseShared(0);
// assertTrue(l.isSignalled());
// l.releaseShared(0);
// assertTrue(l.isSignalled());
// }
//
// /**
// * acquireSharedInterruptibly returns after release, but not before
// */
// public void testAcquireSharedInterruptibly() {
// final BooleanLatch l = new BooleanLatch();
//
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// threadAssertFalse(l.isSignalled());
// l.acquireSharedInterruptibly(0);
// threadAssertTrue(l.isSignalled());
// } catch(InterruptedException e){
// threadUnexpectedException();
// }
// }
// });
// try {
// t.start();
// assertFalse(l.isSignalled());
// Thread.sleep(SHORT_DELAY_MS);
// l.releaseShared(0);
// assertTrue(l.isSignalled());
// t.join();
// } catch (InterruptedException e){
// unexpectedException();
// }
// }
//
//
// /**
// * acquireSharedTimed returns after release
// */
// public void testAsquireSharedTimed() {
// final BooleanLatch l = new BooleanLatch();
//
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// threadAssertFalse(l.isSignalled());
// threadAssertTrue(l.tryAcquireSharedNanos(0, MEDIUM_DELAY_MS* 1000 * 1000));
// threadAssertTrue(l.isSignalled());
//
// } catch(InterruptedException e){
// threadUnexpectedException();
// }
// }
// });
// try {
// t.start();
// assertFalse(l.isSignalled());
// Thread.sleep(SHORT_DELAY_MS);
// l.releaseShared(0);
// assertTrue(l.isSignalled());
// t.join();
// } catch (InterruptedException e){
// unexpectedException();
// }
// }
//
// /**
// * acquireSharedInterruptibly throws IE if interrupted before released
// */
// public void testAcquireSharedInterruptibly_InterruptedException() {
// final BooleanLatch l = new BooleanLatch();
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// threadAssertFalse(l.isSignalled());
// l.acquireSharedInterruptibly(0);
// threadShouldThrow();
// } catch(InterruptedException success){}
// }
// });
// t.start();
// try {
// assertFalse(l.isSignalled());
// t.interrupt();
// t.join();
// } catch (InterruptedException e){
// unexpectedException();
// }
// }
//
// /**
// * acquireSharedTimed throws IE if interrupted before released
// */
// public void testAcquireSharedNanos_InterruptedException() {
// final BooleanLatch l = new BooleanLatch();
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// threadAssertFalse(l.isSignalled());
// l.tryAcquireSharedNanos(0, SMALL_DELAY_MS* 1000 * 1000);
// threadShouldThrow();
// } catch(InterruptedException success){}
// }
// });
// t.start();
// try {
// Thread.sleep(SHORT_DELAY_MS);
// assertFalse(l.isSignalled());
// t.interrupt();
// t.join();
// } catch (InterruptedException e){
// unexpectedException();
// }
// }
//
// /**
// * acquireSharedTimed times out if not released before timeout
// */
// public void testAcquireSharedNanos_Timeout() {
// final BooleanLatch l = new BooleanLatch();
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// threadAssertFalse(l.isSignalled());
// threadAssertFalse(l.tryAcquireSharedNanos(0, SMALL_DELAY_MS* 1000 * 1000));
// } catch(InterruptedException ie){
// threadUnexpectedException();
// }
// }
// });
// t.start();
// try {
// Thread.sleep(SHORT_DELAY_MS);
// assertFalse(l.isSignalled());
// t.join();
// } catch (InterruptedException e){
// unexpectedException();
// }
// }
//
//
}
backport-util-concurrent-3.1-src/test/tck/src/ThreadPoolExecutorSubclassTest.java 0000755 0017507 0003772 00000156463 10431260156 027240 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import junit.framework.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import edu.emory.mathcs.backport.java.util.concurrent.helpers.*;
public class ThreadPoolExecutorSubclassTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(ThreadPoolExecutorTest.class);
}
static class CustomTask implements RunnableFuture {
final Callable callable;
final ReentrantLock lock = new ReentrantLock();
final Condition cond = lock.newCondition();
boolean done;
boolean cancelled;
Object result;
Thread thread;
Exception exception;
CustomTask(Callable c) { callable = c; }
CustomTask(final Runnable r, final Object res) { callable = new Callable() {
public Object call() throws Exception { r.run(); return res; }};
}
public boolean isDone() {
lock.lock(); try { return done; } finally { lock.unlock() ; }
}
public boolean isCancelled() {
lock.lock(); try { return cancelled; } finally { lock.unlock() ; }
}
public boolean cancel(boolean mayInterrupt) {
lock.lock();
try {
if (!done) {
cancelled = true;
done = true;
if (mayInterrupt && thread != null)
thread.interrupt();
return true;
}
return false;
}
finally { lock.unlock() ; }
}
public void run() {
boolean runme;
lock.lock();
try {
runme = !done;
if (!runme)
thread = Thread.currentThread();
}
finally { lock.unlock() ; }
if (!runme) return;
Object v = null;
Exception e = null;
try {
v = callable.call();
}
catch(Exception ex) {
e = ex;
}
lock.lock();
try {
result = v;
exception = e;
done = true;
thread = null;
cond.signalAll();
}
finally { lock.unlock(); }
}
public Object get() throws InterruptedException, ExecutionException {
lock.lock();
try {
while (!done)
cond.await();
if (exception != null)
throw new ExecutionException(exception);
return result;
}
finally { lock.unlock(); }
}
public Object get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException{
long nanos = unit.toNanos(timeout);
lock.lock();
try {
long deadline = Utils.nanoTime() + nanos;
for (;;) {
if (done) break;
if (nanos < 0)
throw new TimeoutException();
cond.await(nanos, TimeUnit.NANOSECONDS);
nanos = deadline - Utils.nanoTime();
}
if (exception != null)
throw new ExecutionException(exception);
return result;
}
finally { lock.unlock(); }
}
}
static class CustomTPE extends ThreadPoolExecutor {
protected RunnableFuture newTaskFor(Callable c) {
return new CustomTask(c);
}
protected RunnableFuture newTaskFor(Runnable r, Object v) {
return new CustomTask(r, v);
}
CustomTPE(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit,
workQueue);
}
CustomTPE(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory);
}
CustomTPE(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
handler);
}
CustomTPE(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit,
workQueue, threadFactory, handler);
}
volatile boolean beforeCalled = false;
volatile boolean afterCalled = false;
volatile boolean terminatedCalled = false;
public CustomTPE() {
super(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new SynchronousQueue());
}
protected void beforeExecute(Thread t, Runnable r) {
beforeCalled = true;
}
protected void afterExecute(Runnable r, Throwable t) {
afterCalled = true;
}
protected void terminated() {
terminatedCalled = true;
}
}
static class FailingThreadFactory implements ThreadFactory{
int calls = 0;
public Thread newThread(Runnable r){
if (++calls > 1) return null;
return new Thread(r);
}
}
/**
* execute successfully executes a runnable
*/
public void testExecute() {
ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
p1.execute(new Runnable() {
public void run() {
try {
Thread.sleep(SHORT_DELAY_MS);
} catch(InterruptedException e){
threadUnexpectedException();
}
}
});
Thread.sleep(SMALL_DELAY_MS);
} catch(InterruptedException e){
unexpectedException();
}
joinPool(p1);
}
/**
* getActiveCount increases but doesn't overestimate, when a
* thread becomes active
*/
public void testGetActiveCount() {
ThreadPoolExecutor p2 = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertEquals(0, p2.getActiveCount());
p2.execute(new MediumRunnable());
try {
Thread.sleep(SHORT_DELAY_MS);
} catch(Exception e){
unexpectedException();
}
assertEquals(1, p2.getActiveCount());
joinPool(p2);
}
/**
* prestartCoreThread starts a thread if under corePoolSize, else doesn't
*/
public void testPrestartCoreThread() {
ThreadPoolExecutor p2 = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertEquals(0, p2.getPoolSize());
assertTrue(p2.prestartCoreThread());
assertEquals(1, p2.getPoolSize());
assertTrue(p2.prestartCoreThread());
assertEquals(2, p2.getPoolSize());
assertFalse(p2.prestartCoreThread());
assertEquals(2, p2.getPoolSize());
joinPool(p2);
}
/**
* prestartAllCoreThreads starts all corePoolSize threads
*/
public void testPrestartAllCoreThreads() {
ThreadPoolExecutor p2 = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertEquals(0, p2.getPoolSize());
p2.prestartAllCoreThreads();
assertEquals(2, p2.getPoolSize());
p2.prestartAllCoreThreads();
assertEquals(2, p2.getPoolSize());
joinPool(p2);
}
/**
* getCompletedTaskCount increases, but doesn't overestimate,
* when tasks complete
*/
public void testGetCompletedTaskCount() {
ThreadPoolExecutor p2 = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertEquals(0, p2.getCompletedTaskCount());
p2.execute(new ShortRunnable());
try {
Thread.sleep(SMALL_DELAY_MS);
} catch(Exception e){
unexpectedException();
}
assertEquals(1, p2.getCompletedTaskCount());
try { p2.shutdown(); } catch(SecurityException ok) { return; }
joinPool(p2);
}
/**
* getCorePoolSize returns size given in constructor if not otherwise set
*/
public void testGetCorePoolSize() {
ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertEquals(1, p1.getCorePoolSize());
joinPool(p1);
}
/**
* getKeepAliveTime returns value given in constructor if not otherwise set
*/
public void testGetKeepAliveTime() {
ThreadPoolExecutor p2 = new CustomTPE(2, 2, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertEquals(1, p2.getKeepAliveTime(TimeUnit.SECONDS));
joinPool(p2);
}
/**
* getThreadFactory returns factory in constructor if not set
*/
public void testGetThreadFactory() {
ThreadFactory tf = new SimpleThreadFactory();
ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10), tf, new NoOpREHandler());
assertSame(tf, p.getThreadFactory());
joinPool(p);
}
/**
* setThreadFactory sets the thread factory returned by getThreadFactory
*/
public void testSetThreadFactory() {
ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
ThreadFactory tf = new SimpleThreadFactory();
p.setThreadFactory(tf);
assertSame(tf, p.getThreadFactory());
joinPool(p);
}
/**
* setThreadFactory(null) throws NPE
*/
public void testSetThreadFactoryNull() {
ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
p.setThreadFactory(null);
shouldThrow();
} catch (NullPointerException success) {
} finally {
joinPool(p);
}
}
/**
* getRejectedExecutionHandler returns handler in constructor if not set
*/
public void testGetRejectedExecutionHandler() {
RejectedExecutionHandler h = new NoOpREHandler();
ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10), h);
assertSame(h, p.getRejectedExecutionHandler());
joinPool(p);
}
/**
* setRejectedExecutionHandler sets the handler returned by
* getRejectedExecutionHandler
*/
public void testSetRejectedExecutionHandler() {
ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
RejectedExecutionHandler h = new NoOpREHandler();
p.setRejectedExecutionHandler(h);
assertSame(h, p.getRejectedExecutionHandler());
joinPool(p);
}
/**
* setRejectedExecutionHandler(null) throws NPE
*/
public void testSetRejectedExecutionHandlerNull() {
ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
p.setRejectedExecutionHandler(null);
shouldThrow();
} catch (NullPointerException success) {
} finally {
joinPool(p);
}
}
/**
* getLargestPoolSize increases, but doesn't overestimate, when
* multiple threads active
*/
public void testGetLargestPoolSize() {
ThreadPoolExecutor p2 = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
assertEquals(0, p2.getLargestPoolSize());
p2.execute(new MediumRunnable());
p2.execute(new MediumRunnable());
Thread.sleep(SHORT_DELAY_MS);
assertEquals(2, p2.getLargestPoolSize());
} catch(Exception e){
unexpectedException();
}
joinPool(p2);
}
/**
* getMaximumPoolSize returns value given in constructor if not
* otherwise set
*/
public void testGetMaximumPoolSize() {
ThreadPoolExecutor p2 = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertEquals(2, p2.getMaximumPoolSize());
joinPool(p2);
}
/**
* getPoolSize increases, but doesn't overestimate, when threads
* become active
*/
public void testGetPoolSize() {
ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertEquals(0, p1.getPoolSize());
p1.execute(new MediumRunnable());
assertEquals(1, p1.getPoolSize());
joinPool(p1);
}
/**
* getTaskCount increases, but doesn't overestimate, when tasks submitted
*/
public void testGetTaskCount() {
ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
assertEquals(0, p1.getTaskCount());
p1.execute(new MediumRunnable());
Thread.sleep(SHORT_DELAY_MS);
assertEquals(1, p1.getTaskCount());
} catch(Exception e){
unexpectedException();
}
joinPool(p1);
}
/**
* isShutDown is false before shutdown, true after
*/
public void testIsShutdown() {
ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertFalse(p1.isShutdown());
try { p1.shutdown(); } catch(SecurityException ok) { return; }
assertTrue(p1.isShutdown());
joinPool(p1);
}
/**
* isTerminated is false before termination, true after
*/
public void testIsTerminated() {
ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertFalse(p1.isTerminated());
try {
p1.execute(new MediumRunnable());
} finally {
try { p1.shutdown(); } catch(SecurityException ok) { return; }
}
try {
assertTrue(p1.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
assertTrue(p1.isTerminated());
} catch(Exception e){
unexpectedException();
}
}
/**
* isTerminating is not true when running or when terminated
*/
public void testIsTerminating() {
ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertFalse(p1.isTerminating());
try {
p1.execute(new SmallRunnable());
assertFalse(p1.isTerminating());
} finally {
try { p1.shutdown(); } catch(SecurityException ok) { return; }
}
try {
assertTrue(p1.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
assertTrue(p1.isTerminated());
assertFalse(p1.isTerminating());
} catch(Exception e){
unexpectedException();
}
}
/**
* getQueue returns the work queue, which contains queued tasks
*/
public void testGetQueue() {
BlockingQueue q = new ArrayBlockingQueue(10);
ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, q);
FutureTask[] tasks = new FutureTask[5];
for(int i = 0; i < 5; i++){
tasks[i] = new FutureTask(new MediumPossiblyInterruptedRunnable(), Boolean.TRUE);
p1.execute(tasks[i]);
}
try {
Thread.sleep(SHORT_DELAY_MS);
BlockingQueue wq = p1.getQueue();
assertSame(q, wq);
assertFalse(wq.contains(tasks[0]));
assertTrue(wq.contains(tasks[4]));
for (int i = 1; i < 5; ++i)
tasks[i].cancel(true);
p1.shutdownNow();
} catch(Exception e) {
unexpectedException();
} finally {
joinPool(p1);
}
}
/**
* remove(task) removes queued task, and fails to remove active task
*/
public void testRemove() {
BlockingQueue q = new ArrayBlockingQueue(10);
ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, q);
FutureTask[] tasks = new FutureTask[5];
for(int i = 0; i < 5; i++){
tasks[i] = new FutureTask(new MediumPossiblyInterruptedRunnable(), Boolean.TRUE);
p1.execute(tasks[i]);
}
try {
Thread.sleep(SHORT_DELAY_MS);
assertFalse(p1.remove(tasks[0]));
assertTrue(q.contains(tasks[4]));
assertTrue(q.contains(tasks[3]));
assertTrue(p1.remove(tasks[4]));
assertFalse(p1.remove(tasks[4]));
assertFalse(q.contains(tasks[4]));
assertTrue(q.contains(tasks[3]));
assertTrue(p1.remove(tasks[3]));
assertFalse(q.contains(tasks[3]));
} catch(Exception e) {
unexpectedException();
} finally {
joinPool(p1);
}
}
/**
* purge removes cancelled tasks from the queue
*/
public void testPurge() {
ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
FutureTask[] tasks = new FutureTask[5];
for(int i = 0; i < 5; i++){
tasks[i] = new FutureTask(new MediumPossiblyInterruptedRunnable(), Boolean.TRUE);
p1.execute(tasks[i]);
}
tasks[4].cancel(true);
tasks[3].cancel(true);
p1.purge();
long count = p1.getTaskCount();
assertTrue(count >= 2 && count < 5);
joinPool(p1);
}
/**
* shutDownNow returns a list containing tasks that were not run
*/
public void testShutDownNow() {
ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
List l;
try {
for(int i = 0; i < 5; i++)
p1.execute(new MediumPossiblyInterruptedRunnable());
}
finally {
try {
l = p1.shutdownNow();
} catch (SecurityException ok) { return; }
}
assertTrue(p1.isShutdown());
assertTrue(l.size() <= 4);
}
// Exception Tests
/**
* Constructor throws if corePoolSize argument is less than zero
*/
public void testConstructor1() {
try {
new CustomTPE(-1,1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if maximumPoolSize is less than zero
*/
public void testConstructor2() {
try {
new CustomTPE(1,-1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if maximumPoolSize is equal to zero
*/
public void testConstructor3() {
try {
new CustomTPE(1,0,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if keepAliveTime is less than zero
*/
public void testConstructor4() {
try {
new CustomTPE(1,2,-1L,TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if corePoolSize is greater than the maximumPoolSize
*/
public void testConstructor5() {
try {
new CustomTPE(2,1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if workQueue is set to null
*/
public void testConstructorNullPointerException() {
try {
new CustomTPE(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,null);
shouldThrow();
}
catch (NullPointerException success){}
}
/**
* Constructor throws if corePoolSize argument is less than zero
*/
public void testConstructor6() {
try {
new CustomTPE(-1,1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory());
shouldThrow();
} catch (IllegalArgumentException success){}
}
/**
* Constructor throws if maximumPoolSize is less than zero
*/
public void testConstructor7() {
try {
new CustomTPE(1,-1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if maximumPoolSize is equal to zero
*/
public void testConstructor8() {
try {
new CustomTPE(1,0,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if keepAliveTime is less than zero
*/
public void testConstructor9() {
try {
new CustomTPE(1,2,-1L,TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if corePoolSize is greater than the maximumPoolSize
*/
public void testConstructor10() {
try {
new CustomTPE(2,1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if workQueue is set to null
*/
public void testConstructorNullPointerException2() {
try {
new CustomTPE(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,null,new SimpleThreadFactory());
shouldThrow();
}
catch (NullPointerException success){}
}
/**
* Constructor throws if threadFactory is set to null
*/
public void testConstructorNullPointerException3() {
try {
ThreadFactory f = null;
new CustomTPE(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(10),f);
shouldThrow();
}
catch (NullPointerException success){}
}
/**
* Constructor throws if corePoolSize argument is less than zero
*/
public void testConstructor11() {
try {
new CustomTPE(-1,1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if maximumPoolSize is less than zero
*/
public void testConstructor12() {
try {
new CustomTPE(1,-1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if maximumPoolSize is equal to zero
*/
public void testConstructor13() {
try {
new CustomTPE(1,0,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if keepAliveTime is less than zero
*/
public void testConstructor14() {
try {
new CustomTPE(1,2,-1L,TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if corePoolSize is greater than the maximumPoolSize
*/
public void testConstructor15() {
try {
new CustomTPE(2,1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if workQueue is set to null
*/
public void testConstructorNullPointerException4() {
try {
new CustomTPE(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,null,new NoOpREHandler());
shouldThrow();
}
catch (NullPointerException success){}
}
/**
* Constructor throws if handler is set to null
*/
public void testConstructorNullPointerException5() {
try {
RejectedExecutionHandler r = null;
new CustomTPE(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(10),r);
shouldThrow();
}
catch (NullPointerException success){}
}
/**
* Constructor throws if corePoolSize argument is less than zero
*/
public void testConstructor16() {
try {
new CustomTPE(-1,1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if maximumPoolSize is less than zero
*/
public void testConstructor17() {
try {
new CustomTPE(1,-1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if maximumPoolSize is equal to zero
*/
public void testConstructor18() {
try {
new CustomTPE(1,0,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if keepAliveTime is less than zero
*/
public void testConstructor19() {
try {
new CustomTPE(1,2,-1L,TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if corePoolSize is greater than the maximumPoolSize
*/
public void testConstructor20() {
try {
new CustomTPE(2,1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if workQueue is set to null
*/
public void testConstructorNullPointerException6() {
try {
new CustomTPE(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,null,new SimpleThreadFactory(),new NoOpREHandler());
shouldThrow();
}
catch (NullPointerException success){}
}
/**
* Constructor throws if handler is set to null
*/
public void testConstructorNullPointerException7() {
try {
RejectedExecutionHandler r = null;
new CustomTPE(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(10),new SimpleThreadFactory(),r);
shouldThrow();
}
catch (NullPointerException success){}
}
/**
* Constructor throws if ThreadFactory is set top null
*/
public void testConstructorNullPointerException8() {
try {
ThreadFactory f = null;
new CustomTPE(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(10),f,new NoOpREHandler());
shouldThrow();
}
catch (NullPointerException successdn8){}
}
/**
* execute throws RejectedExecutionException
* if saturated.
*/
public void testSaturatedExecute() {
ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1));
try {
for(int i = 0; i < 5; ++i){
p.execute(new MediumRunnable());
}
shouldThrow();
} catch(RejectedExecutionException success){}
joinPool(p);
}
/**
* executor using CallerRunsPolicy runs task if saturated.
*/
public void testSaturatedExecute2() {
RejectedExecutionHandler h = new CustomTPE.CallerRunsPolicy();
ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1), h);
try {
TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
for(int i = 0; i < 5; ++i){
tasks[i] = new TrackedNoOpRunnable();
}
TrackedLongRunnable mr = new TrackedLongRunnable();
p.execute(mr);
for(int i = 0; i < 5; ++i){
p.execute(tasks[i]);
}
for(int i = 1; i < 5; ++i) {
assertTrue(tasks[i].done);
}
try { p.shutdownNow(); } catch(SecurityException ok) { return; }
} catch(RejectedExecutionException ex){
unexpectedException();
} finally {
joinPool(p);
}
}
/**
* executor using DiscardPolicy drops task if saturated.
*/
public void testSaturatedExecute3() {
RejectedExecutionHandler h = new CustomTPE.DiscardPolicy();
ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1), h);
try {
TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
for(int i = 0; i < 5; ++i){
tasks[i] = new TrackedNoOpRunnable();
}
p.execute(new TrackedLongRunnable());
for(int i = 0; i < 5; ++i){
p.execute(tasks[i]);
}
for(int i = 0; i < 5; ++i){
assertFalse(tasks[i].done);
}
try { p.shutdownNow(); } catch(SecurityException ok) { return; }
} catch(RejectedExecutionException ex){
unexpectedException();
} finally {
joinPool(p);
}
}
/**
* executor using DiscardOldestPolicy drops oldest task if saturated.
*/
public void testSaturatedExecute4() {
RejectedExecutionHandler h = new CustomTPE.DiscardOldestPolicy();
ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1), h);
try {
p.execute(new TrackedLongRunnable());
TrackedLongRunnable r2 = new TrackedLongRunnable();
p.execute(r2);
assertTrue(p.getQueue().contains(r2));
TrackedNoOpRunnable r3 = new TrackedNoOpRunnable();
p.execute(r3);
assertFalse(p.getQueue().contains(r2));
assertTrue(p.getQueue().contains(r3));
try { p.shutdownNow(); } catch(SecurityException ok) { return; }
} catch(RejectedExecutionException ex){
unexpectedException();
} finally {
joinPool(p);
}
}
/**
* execute throws RejectedExecutionException if shutdown
*/
public void testRejectedExecutionExceptionOnShutdown() {
ThreadPoolExecutor tpe =
new CustomTPE(1,1,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(1));
try { tpe.shutdown(); } catch(SecurityException ok) { return; }
try {
tpe.execute(new NoOpRunnable());
shouldThrow();
} catch(RejectedExecutionException success){}
joinPool(tpe);
}
/**
* execute using CallerRunsPolicy drops task on shutdown
*/
public void testCallerRunsOnShutdown() {
RejectedExecutionHandler h = new CustomTPE.CallerRunsPolicy();
ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1), h);
try { p.shutdown(); } catch(SecurityException ok) { return; }
try {
TrackedNoOpRunnable r = new TrackedNoOpRunnable();
p.execute(r);
assertFalse(r.done);
} catch(RejectedExecutionException success){
unexpectedException();
} finally {
joinPool(p);
}
}
/**
* execute using DiscardPolicy drops task on shutdown
*/
public void testDiscardOnShutdown() {
RejectedExecutionHandler h = new CustomTPE.DiscardPolicy();
ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1), h);
try { p.shutdown(); } catch(SecurityException ok) { return; }
try {
TrackedNoOpRunnable r = new TrackedNoOpRunnable();
p.execute(r);
assertFalse(r.done);
} catch(RejectedExecutionException success){
unexpectedException();
} finally {
joinPool(p);
}
}
/**
* execute using DiscardOldestPolicy drops task on shutdown
*/
public void testDiscardOldestOnShutdown() {
RejectedExecutionHandler h = new CustomTPE.DiscardOldestPolicy();
ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1), h);
try { p.shutdown(); } catch(SecurityException ok) { return; }
try {
TrackedNoOpRunnable r = new TrackedNoOpRunnable();
p.execute(r);
assertFalse(r.done);
} catch(RejectedExecutionException success){
unexpectedException();
} finally {
joinPool(p);
}
}
/**
* execute (null) throws NPE
*/
public void testExecuteNull() {
ThreadPoolExecutor tpe = null;
try {
tpe = new CustomTPE(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(10));
tpe.execute(null);
shouldThrow();
} catch(NullPointerException success){}
joinPool(tpe);
}
/**
* setCorePoolSize of negative value throws IllegalArgumentException
*/
public void testCorePoolSizeIllegalArgumentException() {
ThreadPoolExecutor tpe = null;
try {
tpe = new CustomTPE(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(10));
} catch(Exception e){}
try {
tpe.setCorePoolSize(-1);
shouldThrow();
} catch(IllegalArgumentException success){
} finally {
try { tpe.shutdown(); } catch(SecurityException ok) { return; }
}
joinPool(tpe);
}
/**
* setMaximumPoolSize(int) throws IllegalArgumentException if
* given a value less the core pool size
*/
public void testMaximumPoolSizeIllegalArgumentException() {
ThreadPoolExecutor tpe = null;
try {
tpe = new CustomTPE(2,3,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(10));
} catch(Exception e){}
try {
tpe.setMaximumPoolSize(1);
shouldThrow();
} catch(IllegalArgumentException success){
} finally {
try { tpe.shutdown(); } catch(SecurityException ok) { return; }
}
joinPool(tpe);
}
/**
* setMaximumPoolSize throws IllegalArgumentException
* if given a negative value
*/
public void testMaximumPoolSizeIllegalArgumentException2() {
ThreadPoolExecutor tpe = null;
try {
tpe = new CustomTPE(2,3,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(10));
} catch(Exception e){}
try {
tpe.setMaximumPoolSize(-1);
shouldThrow();
} catch(IllegalArgumentException success){
} finally {
try { tpe.shutdown(); } catch(SecurityException ok) { return; }
}
joinPool(tpe);
}
/**
* setKeepAliveTime throws IllegalArgumentException
* when given a negative value
*/
public void testKeepAliveTimeIllegalArgumentException() {
ThreadPoolExecutor tpe = null;
try {
tpe = new CustomTPE(2,3,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(10));
} catch(Exception e){}
try {
tpe.setKeepAliveTime(-1,TimeUnit.MILLISECONDS);
shouldThrow();
} catch(IllegalArgumentException success){
} finally {
try { tpe.shutdown(); } catch(SecurityException ok) { return; }
}
joinPool(tpe);
}
/**
* terminated() is called on termination
*/
public void testTerminated() {
CustomTPE tpe = new CustomTPE();
try { tpe.shutdown(); } catch(SecurityException ok) { return; }
assertTrue(tpe.terminatedCalled);
joinPool(tpe);
}
/**
* beforeExecute and afterExecute are called when executing task
*/
public void testBeforeAfter() {
CustomTPE tpe = new CustomTPE();
try {
TrackedNoOpRunnable r = new TrackedNoOpRunnable();
tpe.execute(r);
Thread.sleep(SHORT_DELAY_MS);
assertTrue(r.done);
assertTrue(tpe.beforeCalled);
assertTrue(tpe.afterCalled);
try { tpe.shutdown(); } catch(SecurityException ok) { return; }
}
catch(Exception ex) {
unexpectedException();
} finally {
joinPool(tpe);
}
}
/**
* completed submit of callable returns result
*/
public void testSubmitCallable() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
Future future = e.submit(new StringTask());
String result = (String)future.get();
assertSame(TEST_STRING, result);
}
catch (ExecutionException ex) {
unexpectedException();
}
catch (InterruptedException ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* completed submit of runnable returns successfully
*/
public void testSubmitRunnable() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
Future future = e.submit(new NoOpRunnable());
future.get();
assertTrue(future.isDone());
}
catch (ExecutionException ex) {
unexpectedException();
}
catch (InterruptedException ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* completed submit of (runnable, result) returns result
*/
public void testSubmitRunnable2() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
Future future = e.submit(new NoOpRunnable(), TEST_STRING);
String result = (String)future.get();
assertSame(TEST_STRING, result);
}
catch (ExecutionException ex) {
unexpectedException();
}
catch (InterruptedException ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(null) throws NPE
*/
public void testInvokeAny1() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
e.invokeAny(null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(empty collection) throws IAE
*/
public void testInvokeAny2() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
e.invokeAny(new ArrayList());
} catch (IllegalArgumentException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(c) throws NPE if c has null elements
*/
public void testInvokeAny3() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAny(l);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(c) throws ExecutionException if no task completes
*/
public void testInvokeAny4() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
e.invokeAny(l);
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(c) returns result of some task
*/
public void testInvokeAny5() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
String result = (String)e.invokeAny(l);
assertSame(TEST_STRING, result);
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(null) throws NPE
*/
public void testInvokeAll1() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
e.invokeAll(null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(empty collection) returns empty collection
*/
public void testInvokeAll2() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
List r = e.invokeAll(new ArrayList());
assertTrue(r.isEmpty());
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(c) throws NPE if c has null elements
*/
public void testInvokeAll3() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAll(l);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* get of element of invokeAll(c) throws exception on failed task
*/
public void testInvokeAll4() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
List result = e.invokeAll(l);
assertEquals(1, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
((Future)it.next()).get();
} catch(ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(c) returns results of all completed tasks
*/
public void testInvokeAll5() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
List result = e.invokeAll(l);
assertEquals(2, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
assertSame(TEST_STRING, ((Future)it.next()).get());
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(null) throws NPE
*/
public void testTimedInvokeAny1() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
e.invokeAny(null, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(,,null) throws NPE
*/
public void testTimedInvokeAnyNullTimeUnit() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
e.invokeAny(l, MEDIUM_DELAY_MS, null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(empty collection) throws IAE
*/
public void testTimedInvokeAny2() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
e.invokeAny(new ArrayList(), MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (IllegalArgumentException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(c) throws NPE if c has null elements
*/
public void testTimedInvokeAny3() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
ex.printStackTrace();
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(c) throws ExecutionException if no task completes
*/
public void testTimedInvokeAny4() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch(ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(c) returns result of some task
*/
public void testTimedInvokeAny5() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
String result = (String)e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertSame(TEST_STRING, result);
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(null) throws NPE
*/
public void testTimedInvokeAll1() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
e.invokeAll(null, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(,,null) throws NPE
*/
public void testTimedInvokeAllNullTimeUnit() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
e.invokeAll(l, MEDIUM_DELAY_MS, null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(empty collection) returns empty collection
*/
public void testTimedInvokeAll2() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
List r = e.invokeAll(new ArrayList(), MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertTrue(r.isEmpty());
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(c) throws NPE if c has null elements
*/
public void testTimedInvokeAll3() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* get of element of invokeAll(c) throws exception on failed task
*/
public void testTimedInvokeAll4() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
List result = e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertEquals(1, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
((Future)it.next()).get();
} catch(ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(c) returns results of all completed tasks
*/
public void testTimedInvokeAll5() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
List result = e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertEquals(2, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
assertSame(TEST_STRING, ((Future)it.next()).get());
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(c) cancels tasks not completed by timeout
*/
public void testTimedInvokeAll6() {
ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
l.add(new StringTask());
List result = e.invokeAll(l, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
assertEquals(3, result.size());
Iterator it = result.iterator();
Future f1 = (Future)it.next();
Future f2 = (Future)it.next();
Future f3 = (Future)it.next();
assertTrue(f1.isDone());
assertTrue(f2.isDone());
assertTrue(f3.isDone());
assertFalse(f1.isCancelled());
assertTrue(f2.isCancelled());
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* Execution continues if there is at least one thread even if
* thread factory fails to create more
*/
public void testFailingThreadFactory() {
ExecutorService e = new CustomTPE(100, 100, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), new FailingThreadFactory());
try {
ArrayList l = new ArrayList();
for (int k = 0; k < 100; ++k) {
e.execute(new NoOpRunnable());
}
Thread.sleep(LONG_DELAY_MS);
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* allowsCoreThreadTimeOut is by default false.
*/
public void testAllowsCoreThreadTimeOut() {
ThreadPoolExecutor tpe = new CustomTPE(2, 2, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertFalse(tpe.allowsCoreThreadTimeOut());
joinPool(tpe);
}
/**
* allowCoreThreadTimeOut(true) causes idle threads to time out
*/
public void testAllowCoreThreadTimeOut_true() {
ThreadPoolExecutor tpe = new CustomTPE(2, 10, 10, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
tpe.allowCoreThreadTimeOut(true);
tpe.execute(new NoOpRunnable());
try {
Thread.sleep(MEDIUM_DELAY_MS);
assertEquals(0, tpe.getPoolSize());
} catch(InterruptedException e){
unexpectedException();
} finally {
joinPool(tpe);
}
}
/**
* allowCoreThreadTimeOut(false) causes idle threads not to time out
*/
public void testAllowCoreThreadTimeOut_false() {
ThreadPoolExecutor tpe = new CustomTPE(2, 10, 10, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
tpe.allowCoreThreadTimeOut(false);
tpe.execute(new NoOpRunnable());
try {
Thread.sleep(MEDIUM_DELAY_MS);
assertTrue(tpe.getPoolSize() >= 1);
} catch(InterruptedException e){
unexpectedException();
} finally {
joinPool(tpe);
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/ConcurrentSkipListSubSetTest.java 0000644 0017507 0003772 00000076276 10431777323 026724 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.io.*;
import edu.emory.mathcs.backport.java.util.*;
import java.util.Comparator;
import java.util.Iterator;
import java.util.SortedSet;
public class ConcurrentSkipListSubSetTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(ConcurrentSkipListSubSetTest.class);
}
static class MyReverseComparator implements Comparator {
public int compare(Object x, Object y) {
int i = ((Integer)x).intValue();
int j = ((Integer)y).intValue();
if (i < j) return 1;
if (i > j) return -1;
return 0;
}
}
/**
* Create a set of given size containing consecutive
* Integers 0 ... n.
*/
private NavigableSet populatedSet(int n) {
ConcurrentSkipListSet q = new ConcurrentSkipListSet();
assertTrue(q.isEmpty());
for(int i = n-1; i >= 0; i-=2)
assertTrue(q.add(new Integer(i)));
for(int i = (n & 1); i < n; i+=2)
assertTrue(q.add(new Integer(i)));
assertTrue(q.add(new Integer(-n)));
assertTrue(q.add(new Integer(n)));
NavigableSet s = q.subSet(new Integer(0), true, new Integer(n), false);
assertFalse(s.isEmpty());
assertEquals(n, s.size());
return s;
}
/**
* Create set of first 5 ints
*/
private NavigableSet set5() {
ConcurrentSkipListSet q = new ConcurrentSkipListSet();
assertTrue(q.isEmpty());
q.add(one);
q.add(two);
q.add(three);
q.add(four);
q.add(five);
q.add(zero);
q.add(seven);
NavigableSet s = q.subSet(one, true, seven, false);
assertEquals(5, s.size());
return s;
}
/**
* Create set of first 5 negative ints
*/
private NavigableSet dset5() {
ConcurrentSkipListSet q = new ConcurrentSkipListSet();
assertTrue(q.isEmpty());
q.add(m1);
q.add(m2);
q.add(m3);
q.add(m4);
q.add(m5);
NavigableSet s = q.descendingSet();
assertEquals(5, s.size());
return s;
}
private static NavigableSet set0() {
ConcurrentSkipListSet set = new ConcurrentSkipListSet();
assertTrue(set.isEmpty());
return set.tailSet(m1, true);
}
private static NavigableSet dset0() {
ConcurrentSkipListSet set = new ConcurrentSkipListSet();
assertTrue(set.isEmpty());
return set;
}
/**
* A new set has unbounded capacity
*/
public void testConstructor1() {
assertEquals(0, set0().size());
}
/**
* isEmpty is true before add, false after
*/
public void testEmpty() {
NavigableSet q = set0();
assertTrue(q.isEmpty());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.add(new Integer(2));
q.pollFirst();
q.pollFirst();
assertTrue(q.isEmpty());
}
/**
* size changes when elements added and removed
*/
public void testSize() {
NavigableSet q = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i, q.size());
q.pollFirst();
}
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
q.add(new Integer(i));
}
}
/**
* add(null) throws NPE
*/
public void testAddNull() {
try {
NavigableSet q = set0();
q.add(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* Add of comparable element succeeds
*/
public void testAdd() {
NavigableSet q = set0();
assertTrue(q.add(six));
}
/**
* Add of duplicate element fails
*/
public void testAddDup() {
NavigableSet q = set0();
assertTrue(q.add(six));
assertFalse(q.add(six));
}
/**
* Add of non-Comparable throws CCE
*/
public void testAddNonComparable() {
try {
NavigableSet q = set0();
q.add(new Object());
q.add(new Object());
q.add(new Object());
shouldThrow();
}
catch(ClassCastException success) {}
}
/**
* addAll(null) throws NPE
*/
public void testAddAll1() {
try {
NavigableSet q = set0();
q.addAll(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with null elements throws NPE
*/
public void testAddAll2() {
try {
NavigableSet q = set0();
Integer[] ints = new Integer[SIZE];
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with any null elements throws NPE after
* possibly adding some elements
*/
public void testAddAll3() {
try {
NavigableSet q = set0();
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i+SIZE);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Set contains all elements of successful addAll
*/
public void testAddAll5() {
try {
Integer[] empty = new Integer[0];
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(SIZE-1- i);
NavigableSet q = set0();
assertFalse(q.addAll(Arrays.asList(empty)));
assertTrue(q.addAll(Arrays.asList(ints)));
for (int i = 0; i < SIZE; ++i)
assertEquals(new Integer(i), q.pollFirst());
}
finally {}
}
/**
* poll succeeds unless empty
*/
public void testPoll() {
NavigableSet q = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.pollFirst()).intValue());
}
assertNull(q.pollFirst());
}
/**
* remove(x) removes x and returns true if present
*/
public void testRemoveElement() {
NavigableSet q = populatedSet(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
assertFalse(q.remove(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* contains(x) reports true when elements added but not yet removed
*/
public void testContains() {
NavigableSet q = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.contains(new Integer(i)));
q.pollFirst();
assertFalse(q.contains(new Integer(i)));
}
}
/**
* clear removes all elements
*/
public void testClear() {
NavigableSet q = populatedSet(SIZE);
q.clear();
assertTrue(q.isEmpty());
assertEquals(0, q.size());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.clear();
assertTrue(q.isEmpty());
}
/**
* containsAll(c) is true when c contains a subset of elements
*/
public void testContainsAll() {
NavigableSet q = populatedSet(SIZE);
NavigableSet p = set0();
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.containsAll(p));
assertFalse(p.containsAll(q));
p.add(new Integer(i));
}
assertTrue(p.containsAll(q));
}
/**
* retainAll(c) retains only those elements of c and reports true if changed
*/
public void testRetainAll() {
NavigableSet q = populatedSet(SIZE);
NavigableSet p = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
boolean changed = q.retainAll(p);
if (i == 0)
assertFalse(changed);
else
assertTrue(changed);
assertTrue(q.containsAll(p));
assertEquals(SIZE-i, q.size());
p.pollFirst();
}
}
/**
* removeAll(c) removes only those elements of c and reports true if changed
*/
public void testRemoveAll() {
for (int i = 1; i < SIZE; ++i) {
NavigableSet q = populatedSet(SIZE);
NavigableSet p = populatedSet(i);
assertTrue(q.removeAll(p));
assertEquals(SIZE-i, q.size());
for (int j = 0; j < i; ++j) {
Integer I = (Integer)(p.pollFirst());
assertFalse(q.contains(I));
}
}
}
/**
* lower returns preceding element
*/
public void testLower() {
NavigableSet q = set5();
Object e1 = q.lower(three);
assertEquals(two, e1);
Object e2 = q.lower(six);
assertEquals(five, e2);
Object e3 = q.lower(one);
assertNull(e3);
Object e4 = q.lower(zero);
assertNull(e4);
}
/**
* higher returns next element
*/
public void testHigher() {
NavigableSet q = set5();
Object e1 = q.higher(three);
assertEquals(four, e1);
Object e2 = q.higher(zero);
assertEquals(one, e2);
Object e3 = q.higher(five);
assertNull(e3);
Object e4 = q.higher(six);
assertNull(e4);
}
/**
* floor returns preceding element
*/
public void testFloor() {
NavigableSet q = set5();
Object e1 = q.floor(three);
assertEquals(three, e1);
Object e2 = q.floor(six);
assertEquals(five, e2);
Object e3 = q.floor(one);
assertEquals(one, e3);
Object e4 = q.floor(zero);
assertNull(e4);
}
/**
* ceiling returns next element
*/
public void testCeiling() {
NavigableSet q = set5();
Object e1 = q.ceiling(three);
assertEquals(three, e1);
Object e2 = q.ceiling(zero);
assertEquals(one, e2);
Object e3 = q.ceiling(five);
assertEquals(five, e3);
Object e4 = q.ceiling(six);
assertNull(e4);
}
/**
* toArray contains all elements
*/
public void testToArray() {
NavigableSet q = populatedSet(SIZE);
Object[] o = q.toArray();
Arrays.sort(o);
for(int i = 0; i < o.length; i++)
assertEquals(o[i], q.pollFirst());
}
/**
* toArray(a) contains all elements
*/
public void testToArray2() {
NavigableSet q = populatedSet(SIZE);
Integer[] ints = new Integer[SIZE];
ints = (Integer[])q.toArray(ints);
Arrays.sort(ints);
for(int i = 0; i < ints.length; i++)
assertEquals(ints[i], q.pollFirst());
}
/**
* iterator iterates through all elements
*/
public void testIterator() {
NavigableSet q = populatedSet(SIZE);
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, SIZE);
}
/**
* iterator of empty set has no elements
*/
public void testEmptyIterator() {
NavigableSet q = set0();
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, 0);
}
/**
* iterator.remove removes current element
*/
public void testIteratorRemove () {
final NavigableSet q = set0();
q.add(new Integer(2));
q.add(new Integer(1));
q.add(new Integer(3));
Iterator it = q.iterator();
it.next();
it.remove();
it = q.iterator();
assertEquals(it.next(), new Integer(2));
assertEquals(it.next(), new Integer(3));
assertFalse(it.hasNext());
}
/**
* toString contains toStrings of elements
*/
public void testToString() {
NavigableSet q = populatedSet(SIZE);
String s = q.toString();
for (int i = 0; i < SIZE; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
/**
* A deserialized serialized set has same elements
*/
public void testSerialization() {
NavigableSet q = populatedSet(SIZE);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
NavigableSet r = (NavigableSet)in.readObject();
assertEquals(q.size(), r.size());
while (!q.isEmpty())
assertEquals(q.pollFirst(), r.pollFirst());
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* subSet returns set with keys in requested range
*/
public void testSubSetContents() {
NavigableSet set = set5();
SortedSet sm = set.subSet(two, four);
assertEquals(two, sm.first());
assertEquals(three, sm.last());
assertEquals(2, sm.size());
assertFalse(sm.contains(one));
assertTrue(sm.contains(two));
assertTrue(sm.contains(three));
assertFalse(sm.contains(four));
assertFalse(sm.contains(five));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
assertFalse(i.hasNext());
Iterator j = sm.iterator();
j.next();
j.remove();
assertFalse(set.contains(two));
assertEquals(4, set.size());
assertEquals(1, sm.size());
assertEquals(three, sm.first());
assertEquals(three, sm.last());
assertTrue(sm.remove(three));
assertTrue(sm.isEmpty());
assertEquals(3, set.size());
}
public void testSubSetContents2() {
NavigableSet set = set5();
SortedSet sm = set.subSet(two, three);
assertEquals(1, sm.size());
assertEquals(two, sm.first());
assertEquals(two, sm.last());
assertFalse(sm.contains(one));
assertTrue(sm.contains(two));
assertFalse(sm.contains(three));
assertFalse(sm.contains(four));
assertFalse(sm.contains(five));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
assertFalse(i.hasNext());
Iterator j = sm.iterator();
j.next();
j.remove();
assertFalse(set.contains(two));
assertEquals(4, set.size());
assertEquals(0, sm.size());
assertTrue(sm.isEmpty());
assertFalse(sm.remove(three));
assertEquals(4, set.size());
}
/**
* headSet returns set with keys in requested range
*/
public void testHeadSetContents() {
NavigableSet set = set5();
SortedSet sm = set.headSet(four);
assertTrue(sm.contains(one));
assertTrue(sm.contains(two));
assertTrue(sm.contains(three));
assertFalse(sm.contains(four));
assertFalse(sm.contains(five));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(one, k);
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
assertFalse(i.hasNext());
sm.clear();
assertTrue(sm.isEmpty());
assertEquals(2, set.size());
assertEquals(four, set.first());
}
/**
* tailSet returns set with keys in requested range
*/
public void testTailSetContents() {
NavigableSet set = set5();
SortedSet sm = set.tailSet(two);
assertFalse(sm.contains(one));
assertTrue(sm.contains(two));
assertTrue(sm.contains(three));
assertTrue(sm.contains(four));
assertTrue(sm.contains(five));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
k = (Integer)(i.next());
assertEquals(four, k);
k = (Integer)(i.next());
assertEquals(five, k);
assertFalse(i.hasNext());
SortedSet ssm = sm.tailSet(four);
assertEquals(four, ssm.first());
assertEquals(five, ssm.last());
assertTrue(ssm.remove(four));
assertEquals(1, ssm.size());
assertEquals(3, sm.size());
assertEquals(4, set.size());
}
/**
* size changes when elements added and removed
*/
public void testDescendingSize() {
NavigableSet q = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i, q.size());
q.pollFirst();
}
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
q.add(new Integer(i));
}
}
/**
* add(null) throws NPE
*/
public void testDescendingAddNull() {
try {
NavigableSet q = dset0();
q.add(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* Add of comparable element succeeds
*/
public void testDescendingAdd() {
NavigableSet q = dset0();
assertTrue(q.add(m6));
}
/**
* Add of duplicate element fails
*/
public void testDescendingAddDup() {
NavigableSet q = dset0();
assertTrue(q.add(m6));
assertFalse(q.add(m6));
}
/**
* Add of non-Comparable throws CCE
*/
public void testDescendingAddNonComparable() {
try {
NavigableSet q = dset0();
q.add(new Object());
q.add(new Object());
q.add(new Object());
shouldThrow();
}
catch(ClassCastException success) {}
}
/**
* addAll(null) throws NPE
*/
public void testDescendingAddAll1() {
try {
NavigableSet q = dset0();
q.addAll(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with null elements throws NPE
*/
public void testDescendingAddAll2() {
try {
NavigableSet q = dset0();
Integer[] ints = new Integer[SIZE];
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with any null elements throws NPE after
* possibly adding some elements
*/
public void testDescendingAddAll3() {
try {
NavigableSet q = dset0();
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i+SIZE);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Set contains all elements of successful addAll
*/
public void testDescendingAddAll5() {
try {
Integer[] empty = new Integer[0];
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(SIZE-1- i);
NavigableSet q = dset0();
assertFalse(q.addAll(Arrays.asList(empty)));
assertTrue(q.addAll(Arrays.asList(ints)));
for (int i = 0; i < SIZE; ++i)
assertEquals(new Integer(i), q.pollFirst());
}
finally {}
}
/**
* poll succeeds unless empty
*/
public void testDescendingPoll() {
NavigableSet q = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.pollFirst()).intValue());
}
assertNull(q.pollFirst());
}
/**
* remove(x) removes x and returns true if present
*/
public void testDescendingRemoveElement() {
NavigableSet q = populatedSet(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
assertFalse(q.remove(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* contains(x) reports true when elements added but not yet removed
*/
public void testDescendingContains() {
NavigableSet q = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.contains(new Integer(i)));
q.pollFirst();
assertFalse(q.contains(new Integer(i)));
}
}
/**
* clear removes all elements
*/
public void testDescendingClear() {
NavigableSet q = populatedSet(SIZE);
q.clear();
assertTrue(q.isEmpty());
assertEquals(0, q.size());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.clear();
assertTrue(q.isEmpty());
}
/**
* containsAll(c) is true when c contains a subset of elements
*/
public void testDescendingContainsAll() {
NavigableSet q = populatedSet(SIZE);
NavigableSet p = dset0();
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.containsAll(p));
assertFalse(p.containsAll(q));
p.add(new Integer(i));
}
assertTrue(p.containsAll(q));
}
/**
* retainAll(c) retains only those elements of c and reports true if changed
*/
public void testDescendingRetainAll() {
NavigableSet q = populatedSet(SIZE);
NavigableSet p = populatedSet(SIZE);
for (int i = 0; i < SIZE; ++i) {
boolean changed = q.retainAll(p);
if (i == 0)
assertFalse(changed);
else
assertTrue(changed);
assertTrue(q.containsAll(p));
assertEquals(SIZE-i, q.size());
p.pollFirst();
}
}
/**
* removeAll(c) removes only those elements of c and reports true if changed
*/
public void testDescendingRemoveAll() {
for (int i = 1; i < SIZE; ++i) {
NavigableSet q = populatedSet(SIZE);
NavigableSet p = populatedSet(i);
assertTrue(q.removeAll(p));
assertEquals(SIZE-i, q.size());
for (int j = 0; j < i; ++j) {
Integer I = (Integer)(p.pollFirst());
assertFalse(q.contains(I));
}
}
}
/**
* lower returns preceding element
*/
public void testDescendingLower() {
NavigableSet q = dset5();
Object e1 = q.lower(m3);
assertEquals(m2, e1);
Object e2 = q.lower(m6);
assertEquals(m5, e2);
Object e3 = q.lower(m1);
assertNull(e3);
Object e4 = q.lower(zero);
assertNull(e4);
}
/**
* higher returns next element
*/
public void testDescendingHigher() {
NavigableSet q = dset5();
Object e1 = q.higher(m3);
assertEquals(m4, e1);
Object e2 = q.higher(zero);
assertEquals(m1, e2);
Object e3 = q.higher(m5);
assertNull(e3);
Object e4 = q.higher(m6);
assertNull(e4);
}
/**
* floor returns preceding element
*/
public void testDescendingFloor() {
NavigableSet q = dset5();
Object e1 = q.floor(m3);
assertEquals(m3, e1);
Object e2 = q.floor(m6);
assertEquals(m5, e2);
Object e3 = q.floor(m1);
assertEquals(m1, e3);
Object e4 = q.floor(zero);
assertNull(e4);
}
/**
* ceiling returns next element
*/
public void testDescendingCeiling() {
NavigableSet q = dset5();
Object e1 = q.ceiling(m3);
assertEquals(m3, e1);
Object e2 = q.ceiling(zero);
assertEquals(m1, e2);
Object e3 = q.ceiling(m5);
assertEquals(m5, e3);
Object e4 = q.ceiling(m6);
assertNull(e4);
}
/**
* toArray contains all elements
*/
public void testDescendingToArray() {
NavigableSet q = populatedSet(SIZE);
Object[] o = q.toArray();
Arrays.sort(o);
for(int i = 0; i < o.length; i++)
assertEquals(o[i], q.pollFirst());
}
/**
* toArray(a) contains all elements
*/
public void testDescendingToArray2() {
NavigableSet q = populatedSet(SIZE);
Integer[] ints = new Integer[SIZE];
ints = (Integer[])q.toArray(ints);
Arrays.sort(ints);
for(int i = 0; i < ints.length; i++)
assertEquals(ints[i], q.pollFirst());
}
/**
* iterator iterates through all elements
*/
public void testDescendingIterator() {
NavigableSet q = populatedSet(SIZE);
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, SIZE);
}
/**
* iterator of empty set has no elements
*/
public void testDescendingEmptyIterator() {
NavigableSet q = dset0();
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, 0);
}
/**
* iterator.remove removes current element
*/
public void testDescendingIteratorRemove () {
final NavigableSet q = dset0();
q.add(new Integer(2));
q.add(new Integer(1));
q.add(new Integer(3));
Iterator it = q.iterator();
it.next();
it.remove();
it = q.iterator();
assertEquals(it.next(), new Integer(2));
assertEquals(it.next(), new Integer(3));
assertFalse(it.hasNext());
}
/**
* toString contains toStrings of elements
*/
public void testDescendingToString() {
NavigableSet q = populatedSet(SIZE);
String s = q.toString();
for (int i = 0; i < SIZE; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
/**
* A deserialized serialized set has same elements
*/
public void testDescendingSerialization() {
NavigableSet q = populatedSet(SIZE);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
NavigableSet r = (NavigableSet)in.readObject();
assertEquals(q.size(), r.size());
while (!q.isEmpty())
assertEquals(q.pollFirst(), r.pollFirst());
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* subSet returns set with keys in requested range
*/
public void testDescendingSubSetContents() {
NavigableSet set = dset5();
SortedSet sm = set.subSet(m2, m4);
assertEquals(m2, sm.first());
assertEquals(m3, sm.last());
assertEquals(2, sm.size());
assertFalse(sm.contains(m1));
assertTrue(sm.contains(m2));
assertTrue(sm.contains(m3));
assertFalse(sm.contains(m4));
assertFalse(sm.contains(m5));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(m2, k);
k = (Integer)(i.next());
assertEquals(m3, k);
assertFalse(i.hasNext());
Iterator j = sm.iterator();
j.next();
j.remove();
assertFalse(set.contains(m2));
assertEquals(4, set.size());
assertEquals(1, sm.size());
assertEquals(m3, sm.first());
assertEquals(m3, sm.last());
assertTrue(sm.remove(m3));
assertTrue(sm.isEmpty());
assertEquals(3, set.size());
}
public void testDescendingSubSetContents2() {
NavigableSet set = dset5();
SortedSet sm = set.subSet(m2, m3);
assertEquals(1, sm.size());
assertEquals(m2, sm.first());
assertEquals(m2, sm.last());
assertFalse(sm.contains(m1));
assertTrue(sm.contains(m2));
assertFalse(sm.contains(m3));
assertFalse(sm.contains(m4));
assertFalse(sm.contains(m5));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(m2, k);
assertFalse(i.hasNext());
Iterator j = sm.iterator();
j.next();
j.remove();
assertFalse(set.contains(m2));
assertEquals(4, set.size());
assertEquals(0, sm.size());
assertTrue(sm.isEmpty());
assertFalse(sm.remove(m3));
assertEquals(4, set.size());
}
/**
* headSet returns set with keys in requested range
*/
public void testDescendingHeadSetContents() {
NavigableSet set = dset5();
SortedSet sm = set.headSet(m4);
assertTrue(sm.contains(m1));
assertTrue(sm.contains(m2));
assertTrue(sm.contains(m3));
assertFalse(sm.contains(m4));
assertFalse(sm.contains(m5));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(m1, k);
k = (Integer)(i.next());
assertEquals(m2, k);
k = (Integer)(i.next());
assertEquals(m3, k);
assertFalse(i.hasNext());
sm.clear();
assertTrue(sm.isEmpty());
assertEquals(2, set.size());
assertEquals(m4, set.first());
}
/**
* tailSet returns set with keys in requested range
*/
public void testDescendingTailSetContents() {
NavigableSet set = dset5();
SortedSet sm = set.tailSet(m2);
assertFalse(sm.contains(m1));
assertTrue(sm.contains(m2));
assertTrue(sm.contains(m3));
assertTrue(sm.contains(m4));
assertTrue(sm.contains(m5));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(m2, k);
k = (Integer)(i.next());
assertEquals(m3, k);
k = (Integer)(i.next());
assertEquals(m4, k);
k = (Integer)(i.next());
assertEquals(m5, k);
assertFalse(i.hasNext());
SortedSet ssm = sm.tailSet(m4);
assertEquals(m4, ssm.first());
assertEquals(m5, ssm.last());
assertTrue(ssm.remove(m4));
assertEquals(1, ssm.size());
assertEquals(3, sm.size());
assertEquals(4, set.size());
}
}
backport-util-concurrent-3.1-src/test/tck/src/AtomicLongArrayTest.java 0000644 0017507 0003772 00000025701 10253674160 025004 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import java.io.*;
import edu.emory.mathcs.backport.java.util.*;
public class AtomicLongArrayTest extends JSR166TestCase {
public static void main (String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(AtomicLongArrayTest.class);
}
/**
* constructor creates array of given size with all elements zero
*/
public void testConstructor(){
AtomicLongArray ai = new AtomicLongArray(SIZE);
for (int i = 0; i < SIZE; ++i)
assertEquals(0,ai.get(i));
}
/**
* constructor with null array throws NPE
*/
public void testConstructor2NPE() {
try {
long[] a = null;
AtomicLongArray ai = new AtomicLongArray(a);
} catch (NullPointerException success) {
} catch (Exception ex) {
unexpectedException();
}
}
/**
* constructor with array is of same size and has all elements
*/
public void testConstructor2() {
long[] a = { 17L, 3L, -42L, 99L, -7L};
AtomicLongArray ai = new AtomicLongArray(a);
assertEquals(a.length, ai.length());
for (int i = 0; i < a.length; ++i)
assertEquals(a[i], ai.get(i));
}
/**
* get and set for out of bound indices throw IndexOutOfBoundsException
*/
public void testIndexing(){
AtomicLongArray ai = new AtomicLongArray(SIZE);
try {
ai.get(SIZE);
} catch(IndexOutOfBoundsException success){
}
try {
ai.get(-1);
} catch(IndexOutOfBoundsException success){
}
try {
ai.set(SIZE, 0);
} catch(IndexOutOfBoundsException success){
}
try {
ai.set(-1, 0);
} catch(IndexOutOfBoundsException success){
}
}
/**
* get returns the last value set at index
*/
public void testGetSet(){
AtomicLongArray ai = new AtomicLongArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
assertEquals(1,ai.get(i));
ai.set(i, 2);
assertEquals(2,ai.get(i));
ai.set(i, -3);
assertEquals(-3,ai.get(i));
}
}
/**
* get returns the last value lazySet at index by same thread
*/
public void testGetLazySet(){
AtomicLongArray ai = new AtomicLongArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.lazySet(i, 1);
assertEquals(1,ai.get(i));
ai.lazySet(i, 2);
assertEquals(2,ai.get(i));
ai.lazySet(i, -3);
assertEquals(-3,ai.get(i));
}
}
/**
* compareAndSet succeeds in changing value if equal to expected else fails
*/
public void testCompareAndSet(){
AtomicLongArray ai = new AtomicLongArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
assertTrue(ai.compareAndSet(i, 1,2));
assertTrue(ai.compareAndSet(i, 2,-4));
assertEquals(-4,ai.get(i));
assertFalse(ai.compareAndSet(i, -5,7));
assertFalse((7 == ai.get(i)));
assertTrue(ai.compareAndSet(i, -4,7));
assertEquals(7,ai.get(i));
}
}
/**
* compareAndSet in one thread enables another waiting for value
* to succeed
*/
public void testCompareAndSetInMultipleThreads() {
final AtomicLongArray a = new AtomicLongArray(1);
a.set(0, 1);
Thread t = new Thread(new Runnable() {
public void run() {
while(!a.compareAndSet(0, 2, 3)) Thread.yield();
}});
try {
t.start();
assertTrue(a.compareAndSet(0, 1, 2));
t.join(LONG_DELAY_MS);
assertFalse(t.isAlive());
assertEquals(a.get(0), 3);
}
catch(Exception e) {
unexpectedException();
}
}
/**
* repeated weakCompareAndSet succeeds in changing value when equal
* to expected
*/
public void testWeakCompareAndSet(){
AtomicLongArray ai = new AtomicLongArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
while(!ai.weakCompareAndSet(i, 1,2));
while(!ai.weakCompareAndSet(i, 2,-4));
assertEquals(-4,ai.get(i));
while(!ai.weakCompareAndSet(i, -4,7));
assertEquals(7,ai.get(i));
}
}
/**
* getAndSet returns previous value and sets to given value at given index
*/
public void testGetAndSet(){
AtomicLongArray ai = new AtomicLongArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
assertEquals(1,ai.getAndSet(i,0));
assertEquals(0,ai.getAndSet(i,-10));
assertEquals(-10,ai.getAndSet(i,1));
}
}
/**
* getAndAdd returns previous value and adds given value
*/
public void testGetAndAdd(){
AtomicLongArray ai = new AtomicLongArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
assertEquals(1,ai.getAndAdd(i,2));
assertEquals(3,ai.get(i));
assertEquals(3,ai.getAndAdd(i,-4));
assertEquals(-1,ai.get(i));
}
}
/**
* getAndDecrement returns previous value and decrements
*/
public void testGetAndDecrement(){
AtomicLongArray ai = new AtomicLongArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
assertEquals(1,ai.getAndDecrement(i));
assertEquals(0,ai.getAndDecrement(i));
assertEquals(-1,ai.getAndDecrement(i));
}
}
/**
* getAndIncrement returns previous value and increments
*/
public void testGetAndIncrement(){
AtomicLongArray ai = new AtomicLongArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
assertEquals(1,ai.getAndIncrement(i));
assertEquals(2,ai.get(i));
ai.set(i,-2);
assertEquals(-2,ai.getAndIncrement(i));
assertEquals(-1,ai.getAndIncrement(i));
assertEquals(0,ai.getAndIncrement(i));
assertEquals(1,ai.get(i));
}
}
/**
* addAndGet adds given value to current, and returns current value
*/
public void testAddAndGet() {
AtomicLongArray ai = new AtomicLongArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
assertEquals(3,ai.addAndGet(i,2));
assertEquals(3,ai.get(i));
assertEquals(-1,ai.addAndGet(i,-4));
assertEquals(-1,ai.get(i));
}
}
/**
* decrementAndGet decrements and returns current value
*/
public void testDecrementAndGet(){
AtomicLongArray ai = new AtomicLongArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
assertEquals(0,ai.decrementAndGet(i));
assertEquals(-1,ai.decrementAndGet(i));
assertEquals(-2,ai.decrementAndGet(i));
assertEquals(-2,ai.get(i));
}
}
/**
* incrementAndGet increments and returns current value
*/
public void testIncrementAndGet() {
AtomicLongArray ai = new AtomicLongArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
assertEquals(2,ai.incrementAndGet(i));
assertEquals(2,ai.get(i));
ai.set(i, -2);
assertEquals(-1,ai.incrementAndGet(i));
assertEquals(0,ai.incrementAndGet(i));
assertEquals(1,ai.incrementAndGet(i));
assertEquals(1,ai.get(i));
}
}
static final long COUNTDOWN = 100000;
class Counter implements Runnable {
final AtomicLongArray ai;
volatile long counts;
Counter(AtomicLongArray a) { ai = a; }
public void run() {
for (;;) {
boolean done = true;
for (int i = 0; i < ai.length(); ++i) {
long v = ai.get(i);
threadAssertTrue(v >= 0);
if (v != 0) {
done = false;
if (ai.compareAndSet(i, v, v-1))
++counts;
}
}
if (done)
break;
}
}
}
/**
* Multiple threads using same array of counters successfully
* update a number of times equal to total count
*/
public void testCountingInMultipleThreads() {
try {
final AtomicLongArray ai = new AtomicLongArray(SIZE);
for (int i = 0; i < SIZE; ++i)
ai.set(i, COUNTDOWN);
Counter c1 = new Counter(ai);
Counter c2 = new Counter(ai);
Thread t1 = new Thread(c1);
Thread t2 = new Thread(c2);
t1.start();
t2.start();
t1.join();
t2.join();
assertEquals(c1.counts+c2.counts, SIZE * COUNTDOWN);
}
catch(InterruptedException ie) {
unexpectedException();
}
}
/**
* a deserialized serialized array holds same values
*/
public void testSerialization() {
AtomicLongArray l = new AtomicLongArray(SIZE);
for (int i = 0; i < SIZE; ++i)
l.set(i, -i);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(l);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
AtomicLongArray r = (AtomicLongArray) in.readObject();
for (int i = 0; i < SIZE; ++i) {
assertEquals(l.get(i), r.get(i));
}
} catch(Exception e){
unexpectedException();
}
}
/**
* toString returns current value.
*/
public void testToString() {
long[] a = { 17, 3, -42, 99, -7};
AtomicLongArray ai = new AtomicLongArray(a);
assertEquals(toString(a), ai.toString());
}
private static String toString(long[] array) {
if (array.length == 0)
return "[]";
StringBuffer buf = new StringBuffer();
buf.append('[');
buf.append(array[0]);
for (int i = 1; i < array.length; i++) {
buf.append(", ");
buf.append(array[i]);
}
buf.append("]");
return buf.toString();
}
}
backport-util-concurrent-3.1-src/test/tck/src/CountDownLatchTest.java 0000644 0017507 0003772 00000014336 10153210664 024641 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
public class CountDownLatchTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(CountDownLatchTest.class);
}
/**
* negative constructor argument throws IAE
*/
public void testConstructor() {
try {
new CountDownLatch(-1);
shouldThrow();
} catch(IllegalArgumentException success){}
}
/**
* getCount returns initial count and decreases after countDown
*/
public void testGetCount() {
final CountDownLatch l = new CountDownLatch(2);
assertEquals(2, l.getCount());
l.countDown();
assertEquals(1, l.getCount());
}
/**
* countDown decrements count when positive and has no effect when zero
*/
public void testCountDown() {
final CountDownLatch l = new CountDownLatch(1);
assertEquals(1, l.getCount());
l.countDown();
assertEquals(0, l.getCount());
l.countDown();
assertEquals(0, l.getCount());
}
/**
* await returns after countDown to zero, but not before
*/
public void testAwait() {
final CountDownLatch l = new CountDownLatch(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertTrue(l.getCount() > 0);
l.await();
threadAssertTrue(l.getCount() == 0);
} catch(InterruptedException e){
e.printStackTrace();
threadUnexpectedException();
}
}
});
t.start();
try {
assertEquals(l.getCount(), 2);
Thread.sleep(SHORT_DELAY_MS);
l.countDown();
assertEquals(l.getCount(), 1);
l.countDown();
assertEquals(l.getCount(), 0);
t.join();
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* timed await returns after countDown to zero
*/
public void testTimedAwait() {
final CountDownLatch l = new CountDownLatch(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertTrue(l.getCount() > 0);
threadAssertTrue(l.await(SMALL_DELAY_MS, TimeUnit.MILLISECONDS));
} catch(InterruptedException e){
threadUnexpectedException();
}
}
});
t.start();
try {
assertEquals(l.getCount(), 2);
Thread.sleep(SHORT_DELAY_MS);
l.countDown();
assertEquals(l.getCount(), 1);
l.countDown();
assertEquals(l.getCount(), 0);
t.join();
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* await throws IE if interrupted before counted down
*/
public void testAwait_InterruptedException() {
final CountDownLatch l = new CountDownLatch(1);
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertTrue(l.getCount() > 0);
l.await();
threadShouldThrow();
} catch(InterruptedException success){}
}
});
t.start();
try {
assertEquals(l.getCount(), 1);
t.interrupt();
t.join();
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* timed await throws IE if interrupted before counted down
*/
public void testTimedAwait_InterruptedException() {
final CountDownLatch l = new CountDownLatch(1);
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertTrue(l.getCount() > 0);
l.await(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch(InterruptedException success){}
}
});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
assertEquals(l.getCount(), 1);
t.interrupt();
t.join();
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* timed await times out if not counted down before timeout
*/
public void testAwaitTimeout() {
final CountDownLatch l = new CountDownLatch(1);
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertTrue(l.getCount() > 0);
threadAssertFalse(l.await(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
threadAssertTrue(l.getCount() > 0);
} catch(InterruptedException ie){
threadUnexpectedException();
}
}
});
t.start();
try {
assertEquals(l.getCount(), 1);
t.join();
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* toString indicates current count
*/
public void testToString() {
CountDownLatch s = new CountDownLatch(2);
String us = s.toString();
assertTrue(us.indexOf("Count = 2") >= 0);
s.countDown();
String s1 = s.toString();
assertTrue(s1.indexOf("Count = 1") >= 0);
s.countDown();
String s2 = s.toString();
assertTrue(s2.indexOf("Count = 0") >= 0);
}
}
backport-util-concurrent-3.1-src/test/tck/src/PriorityBlockingQueueTest.java 0000644 0017507 0003772 00000070004 10346121124 026232 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.io.*;
import edu.emory.mathcs.backport.java.util.PriorityQueue;
import java.util.Comparator;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Iterator;
import java.util.ArrayList;
public class PriorityBlockingQueueTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(PriorityBlockingQueueTest.class);
}
private static final int NOCAP = Integer.MAX_VALUE;
/** Sample Comparator */
static class MyReverseComparator implements Comparator {
public int compare(Object x, Object y) {
int i = ((Integer)x).intValue();
int j = ((Integer)y).intValue();
if (i < j) return 1;
if (i > j) return -1;
return 0;
}
}
/**
* Create a queue of given size containing consecutive
* Integers 0 ... n.
*/
private PriorityBlockingQueue populatedQueue(int n) {
PriorityBlockingQueue q = new PriorityBlockingQueue(n);
assertTrue(q.isEmpty());
for(int i = n-1; i >= 0; i-=2)
assertTrue(q.offer(new Integer(i)));
for(int i = (n & 1); i < n; i+=2)
assertTrue(q.offer(new Integer(i)));
assertFalse(q.isEmpty());
assertEquals(NOCAP, q.remainingCapacity());
assertEquals(n, q.size());
return q;
}
/**
* A new queue has unbounded capacity
*/
public void testConstructor1() {
assertEquals(NOCAP, new PriorityBlockingQueue(SIZE).remainingCapacity());
}
/**
* Constructor throws IAE if capacity argument nonpositive
*/
public void testConstructor2() {
try {
PriorityBlockingQueue q = new PriorityBlockingQueue(0);
shouldThrow();
}
catch (IllegalArgumentException success) {}
}
/**
* Initializing from null Collection throws NPE
*/
public void testConstructor3() {
try {
PriorityBlockingQueue q = new PriorityBlockingQueue(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from Collection of null elements throws NPE
*/
public void testConstructor4() {
try {
Integer[] ints = new Integer[SIZE];
PriorityBlockingQueue q = new PriorityBlockingQueue(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from Collection with some null elements throws NPE
*/
public void testConstructor5() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
PriorityBlockingQueue q = new PriorityBlockingQueue(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Queue contains all elements of collection used to initialize
*/
public void testConstructor6() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
PriorityBlockingQueue q = new PriorityBlockingQueue(Arrays.asList(ints));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* The comparator used in constructor is used
*/
public void testConstructor7() {
try {
MyReverseComparator cmp = new MyReverseComparator();
PriorityBlockingQueue q = new PriorityBlockingQueue(SIZE, cmp);
assertEquals(cmp, q.comparator());
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
for (int i = SIZE-1; i >= 0; --i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* isEmpty is true before add, false after
*/
public void testEmpty() {
PriorityBlockingQueue q = new PriorityBlockingQueue(2);
assertTrue(q.isEmpty());
assertEquals(NOCAP, q.remainingCapacity());
q.add(one);
assertFalse(q.isEmpty());
q.add(two);
q.remove();
q.remove();
assertTrue(q.isEmpty());
}
/**
* remainingCapacity does not change when elements added or removed,
* but size does
*/
public void testRemainingCapacity() {
PriorityBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(NOCAP, q.remainingCapacity());
assertEquals(SIZE-i, q.size());
q.remove();
}
for (int i = 0; i < SIZE; ++i) {
assertEquals(NOCAP, q.remainingCapacity());
assertEquals(i, q.size());
q.add(new Integer(i));
}
}
/**
* offer(null) throws NPE
*/
public void testOfferNull() {
try {
PriorityBlockingQueue q = new PriorityBlockingQueue(1);
q.offer(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* add(null) throws NPE
*/
public void testAddNull() {
try {
PriorityBlockingQueue q = new PriorityBlockingQueue(1);
q.add(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* Offer of comparable element succeeds
*/
public void testOffer() {
PriorityBlockingQueue q = new PriorityBlockingQueue(1);
assertTrue(q.offer(zero));
assertTrue(q.offer(one));
}
/**
* Offer of non-Comparable throws CCE
*/
public void testOfferNonComparable() {
try {
PriorityBlockingQueue q = new PriorityBlockingQueue(1);
q.offer(new Object());
q.offer(new Object());
q.offer(new Object());
shouldThrow();
}
catch(ClassCastException success) {}
}
/**
* add of comparable succeeds
*/
public void testAdd() {
PriorityBlockingQueue q = new PriorityBlockingQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
assertTrue(q.add(new Integer(i)));
}
}
/**
* addAll(null) throws NPE
*/
public void testAddAll1() {
try {
PriorityBlockingQueue q = new PriorityBlockingQueue(1);
q.addAll(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll(this) throws IAE
*/
public void testAddAllSelf() {
try {
PriorityBlockingQueue q = populatedQueue(SIZE);
q.addAll(q);
shouldThrow();
}
catch (IllegalArgumentException success) {}
}
/**
* addAll of a collection with null elements throws NPE
*/
public void testAddAll2() {
try {
PriorityBlockingQueue q = new PriorityBlockingQueue(SIZE);
Integer[] ints = new Integer[SIZE];
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with any null elements throws NPE after
* possibly adding some elements
*/
public void testAddAll3() {
try {
PriorityBlockingQueue q = new PriorityBlockingQueue(SIZE);
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Queue contains all elements of successful addAll
*/
public void testAddAll5() {
try {
Integer[] empty = new Integer[0];
Integer[] ints = new Integer[SIZE];
for (int i = SIZE-1; i >= 0; --i)
ints[i] = new Integer(i);
PriorityBlockingQueue q = new PriorityBlockingQueue(SIZE);
assertFalse(q.addAll(Arrays.asList(empty)));
assertTrue(q.addAll(Arrays.asList(ints)));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* put(null) throws NPE
*/
public void testPutNull() {
try {
PriorityBlockingQueue q = new PriorityBlockingQueue(SIZE);
q.put(null);
shouldThrow();
}
catch (NullPointerException success){
}
}
/**
* all elements successfully put are contained
*/
public void testPut() {
try {
PriorityBlockingQueue q = new PriorityBlockingQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
Integer I = new Integer(i);
q.put(I);
assertTrue(q.contains(I));
}
assertEquals(SIZE, q.size());
}
finally {
}
}
/**
* put doesn't block waiting for take
*/
public void testPutWithTake() {
final PriorityBlockingQueue q = new PriorityBlockingQueue(2);
Thread t = new Thread(new Runnable() {
public void run() {
int added = 0;
try {
q.put(new Integer(0));
++added;
q.put(new Integer(0));
++added;
q.put(new Integer(0));
++added;
q.put(new Integer(0));
++added;
threadAssertTrue(added == 4);
} finally {
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
q.take();
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* timed offer does not time out
*/
public void testTimedOffer() {
final PriorityBlockingQueue q = new PriorityBlockingQueue(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.put(new Integer(0));
q.put(new Integer(0));
threadAssertTrue(q.offer(new Integer(0), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
threadAssertTrue(q.offer(new Integer(0), LONG_DELAY_MS, TimeUnit.MILLISECONDS));
} finally { }
}
});
try {
t.start();
Thread.sleep(SMALL_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* take retrieves elements in priority order
*/
public void testTake() {
try {
PriorityBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.take()).intValue());
}
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* take blocks interruptibly when empty
*/
public void testTakeFromEmpty() {
final PriorityBlockingQueue q = new PriorityBlockingQueue(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.take();
threadShouldThrow();
} catch (InterruptedException success){ }
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* Take removes existing elements until empty, then blocks interruptibly
*/
public void testBlockingTake() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
PriorityBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
threadAssertEquals(i, ((Integer)q.take()).intValue());
}
q.take();
threadShouldThrow();
} catch (InterruptedException success){
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* poll succeeds unless empty
*/
public void testPoll() {
PriorityBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.poll()).intValue());
}
assertNull(q.poll());
}
/**
* timed pool with zero timeout succeeds when non-empty, else times out
*/
public void testTimedPoll0() {
try {
PriorityBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.poll(0, TimeUnit.MILLISECONDS)).intValue());
}
assertNull(q.poll(0, TimeUnit.MILLISECONDS));
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* timed pool with nonzero timeout succeeds when non-empty, else times out
*/
public void testTimedPoll() {
try {
PriorityBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
}
assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* Interrupted timed poll throws InterruptedException instead of
* returning timeout status
*/
public void testInterruptedTimedPoll() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
PriorityBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
threadAssertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
}
threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch (InterruptedException success){
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* timed poll before a delayed offer fails; after offer succeeds;
* on interruption throws
*/
public void testTimedPollWithOffer() {
final PriorityBlockingQueue q = new PriorityBlockingQueue(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch (InterruptedException success) { }
}
});
try {
t.start();
Thread.sleep(SMALL_DELAY_MS);
assertTrue(q.offer(new Integer(0), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* peek returns next element, or null if empty
*/
public void testPeek() {
PriorityBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.peek()).intValue());
q.poll();
assertTrue(q.peek() == null ||
i != ((Integer)q.peek()).intValue());
}
assertNull(q.peek());
}
/**
* element returns next element, or throws NSEE if empty
*/
public void testElement() {
PriorityBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.element()).intValue());
q.poll();
}
try {
q.element();
shouldThrow();
}
catch (NoSuchElementException success) {}
}
/**
* remove removes next element, or throws NSEE if empty
*/
public void testRemove() {
PriorityBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.remove()).intValue());
}
try {
q.remove();
shouldThrow();
} catch (NoSuchElementException success){
}
}
/**
* remove(x) removes x and returns true if present
*/
public void testRemoveElement() {
PriorityBlockingQueue q = populatedQueue(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
assertFalse(q.remove(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* contains(x) reports true when elements added but not yet removed
*/
public void testContains() {
PriorityBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.contains(new Integer(i)));
q.poll();
assertFalse(q.contains(new Integer(i)));
}
}
/**
* clear removes all elements
*/
public void testClear() {
PriorityBlockingQueue q = populatedQueue(SIZE);
q.clear();
assertTrue(q.isEmpty());
assertEquals(0, q.size());
q.add(one);
assertFalse(q.isEmpty());
assertTrue(q.contains(one));
q.clear();
assertTrue(q.isEmpty());
}
/**
* containsAll(c) is true when c contains a subset of elements
*/
public void testContainsAll() {
PriorityBlockingQueue q = populatedQueue(SIZE);
PriorityBlockingQueue p = new PriorityBlockingQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.containsAll(p));
assertFalse(p.containsAll(q));
p.add(new Integer(i));
}
assertTrue(p.containsAll(q));
}
/**
* retainAll(c) retains only those elements of c and reports true if changed
*/
public void testRetainAll() {
PriorityBlockingQueue q = populatedQueue(SIZE);
PriorityBlockingQueue p = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
boolean changed = q.retainAll(p);
if (i == 0)
assertFalse(changed);
else
assertTrue(changed);
assertTrue(q.containsAll(p));
assertEquals(SIZE-i, q.size());
p.remove();
}
}
/**
* removeAll(c) removes only those elements of c and reports true if changed
*/
public void testRemoveAll() {
for (int i = 1; i < SIZE; ++i) {
PriorityBlockingQueue q = populatedQueue(SIZE);
PriorityBlockingQueue p = populatedQueue(i);
assertTrue(q.removeAll(p));
assertEquals(SIZE-i, q.size());
for (int j = 0; j < i; ++j) {
Integer I = (Integer)(p.remove());
assertFalse(q.contains(I));
}
}
}
/**
* toArray contains all elements
*/
public void testToArray() {
PriorityBlockingQueue q = populatedQueue(SIZE);
Object[] o = q.toArray();
Arrays.sort(o);
try {
for(int i = 0; i < o.length; i++)
assertEquals(o[i], q.take());
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* toArray(a) contains all elements
*/
public void testToArray2() {
PriorityBlockingQueue q = populatedQueue(SIZE);
Integer[] ints = new Integer[SIZE];
ints = (Integer[])q.toArray(ints);
Arrays.sort(ints);
try {
for(int i = 0; i < ints.length; i++)
assertEquals(ints[i], q.take());
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* toArray(null) throws NPE
*/
public void testToArray_BadArg() {
try {
PriorityBlockingQueue q = populatedQueue(SIZE);
Object o[] = q.toArray(null);
shouldThrow();
} catch(NullPointerException success){}
}
/**
* toArray with incompatible array type throws CCE
*/
public void testToArray1_BadArg() {
try {
PriorityBlockingQueue q = populatedQueue(SIZE);
Object o[] = q.toArray(new String[10] );
shouldThrow();
} catch(ArrayStoreException success){}
}
/**
* iterator iterates through all elements
*/
public void testIterator() {
PriorityBlockingQueue q = populatedQueue(SIZE);
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, SIZE);
}
/**
* iterator.remove removes current element
*/
public void testIteratorRemove () {
final PriorityBlockingQueue q = new PriorityBlockingQueue(3);
q.add(new Integer(2));
q.add(new Integer(1));
q.add(new Integer(3));
Iterator it = q.iterator();
it.next();
it.remove();
it = q.iterator();
assertEquals(it.next(), new Integer(2));
assertEquals(it.next(), new Integer(3));
assertFalse(it.hasNext());
}
/**
* toString contains toStrings of elements
*/
public void testToString() {
PriorityBlockingQueue q = populatedQueue(SIZE);
String s = q.toString();
for (int i = 0; i < SIZE; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
/**
* offer transfers elements across Executor tasks
*/
public void testPollInExecutor() {
final PriorityBlockingQueue q = new PriorityBlockingQueue(2);
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new Runnable() {
public void run() {
threadAssertNull(q.poll());
try {
threadAssertTrue(null != q.poll(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
threadAssertTrue(q.isEmpty());
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
executor.execute(new Runnable() {
public void run() {
try {
Thread.sleep(SMALL_DELAY_MS);
q.put(new Integer(1));
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
joinPool(executor);
}
/**
* A deserialized serialized queue has same elements
*/
public void testSerialization() {
PriorityBlockingQueue q = populatedQueue(SIZE);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
PriorityBlockingQueue r = (PriorityBlockingQueue)in.readObject();
assertEquals(q.size(), r.size());
while (!q.isEmpty())
assertEquals(q.remove(), r.remove());
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* drainTo(null) throws NPE
*/
public void testDrainToNull() {
PriorityBlockingQueue q = populatedQueue(SIZE);
try {
q.drainTo(null);
shouldThrow();
} catch(NullPointerException success) {
}
}
/**
* drainTo(this) throws IAE
*/
public void testDrainToSelf() {
PriorityBlockingQueue q = populatedQueue(SIZE);
try {
q.drainTo(q);
shouldThrow();
} catch(IllegalArgumentException success) {
}
}
/**
* drainTo(c) empties queue into another collection c
*/
public void testDrainTo() {
PriorityBlockingQueue q = populatedQueue(SIZE);
ArrayList l = new ArrayList();
q.drainTo(l);
assertEquals(q.size(), 0);
assertEquals(l.size(), SIZE);
for (int i = 0; i < SIZE; ++i)
assertEquals(l.get(i), new Integer(i));
q.add(zero);
q.add(one);
assertFalse(q.isEmpty());
assertTrue(q.contains(zero));
assertTrue(q.contains(one));
l.clear();
q.drainTo(l);
assertEquals(q.size(), 0);
assertEquals(l.size(), 2);
for (int i = 0; i < 2; ++i)
assertEquals(l.get(i), new Integer(i));
}
/**
* drainTo empties queue
*/
public void testDrainToWithActivePut() {
final PriorityBlockingQueue q = populatedQueue(SIZE);
Thread t = new Thread(new Runnable() {
public void run() {
q.put(new Integer(SIZE+1));
}
});
try {
t.start();
ArrayList l = new ArrayList();
q.drainTo(l);
assertTrue(l.size() >= SIZE);
for (int i = 0; i < SIZE; ++i)
assertEquals(l.get(i), new Integer(i));
t.join();
assertTrue(q.size() + l.size() >= SIZE);
} catch(Exception e){
unexpectedException();
}
}
/**
* drainTo(null, n) throws NPE
*/
public void testDrainToNullN() {
PriorityBlockingQueue q = populatedQueue(SIZE);
try {
q.drainTo(null, 0);
shouldThrow();
} catch(NullPointerException success) {
}
}
/**
* drainTo(this, n) throws IAE
*/
public void testDrainToSelfN() {
PriorityBlockingQueue q = populatedQueue(SIZE);
try {
q.drainTo(q, 0);
shouldThrow();
} catch(IllegalArgumentException success) {
}
}
/**
* drainTo(c, n) empties first max {n, size} elements of queue into c
*/
public void testDrainToN() {
PriorityBlockingQueue q = new PriorityBlockingQueue(SIZE*2);
for (int i = 0; i < SIZE + 2; ++i) {
for(int j = 0; j < SIZE; j++)
assertTrue(q.offer(new Integer(j)));
ArrayList l = new ArrayList();
q.drainTo(l, i);
int k = (i < SIZE)? i : SIZE;
assertEquals(l.size(), k);
assertEquals(q.size(), SIZE-k);
for (int j = 0; j < k; ++j)
assertEquals(l.get(j), new Integer(j));
while (q.poll() != null) ;
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/EntryTest.java 0000644 0017507 0003772 00000010111 10431260156 023031 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import junit.framework.*;
import java.util.Map;
import edu.emory.mathcs.backport.java.util.AbstractMap;
public class EntryTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(EntryTest.class);
}
static final String k1 = "1";
static final String v1 = "a";
static final String k2 = "2";
static final String v2 = "b";
/**
* A new SimpleEntry(k, v) holds k, v.
*/
public void testConstructor1() {
Map.Entry e = new AbstractMap.SimpleEntry(k1, v1);
assertEquals(k1, e.getKey());
assertEquals(v1, e.getValue());
}
/**
* A new SimpleImmutableEntry(k, v) holds k, v.
*/
public void testConstructor2() {
Map.Entry s = new AbstractMap.SimpleImmutableEntry(k1, v1);
assertEquals(k1, s.getKey());
assertEquals(v1, s.getValue());
}
/**
* A new SimpleEntry(entry(k, v)) holds k, v.
*/
public void testConstructor3() {
Map.Entry e2 = new AbstractMap.SimpleEntry(k1, v1);
Map.Entry e = new AbstractMap.SimpleEntry(e2);
assertEquals(k1, e.getKey());
assertEquals(v1, e.getValue());
}
/**
* A new SimpleImmutableEntry(entry(k, v)) holds k, v.
*/
public void testConstructor4() {
Map.Entry s2 = new AbstractMap.SimpleImmutableEntry(k1, v1);
Map.Entry s = new AbstractMap.SimpleImmutableEntry(s2);
assertEquals(k1, s.getKey());
assertEquals(v1, s.getValue());
}
/**
* Entries with same key-value pairs are equal and have same
* hashcodes
*/
public void testEquals() {
Map.Entry e2 = new AbstractMap.SimpleEntry(k1, v1);
Map.Entry e = new AbstractMap.SimpleEntry(e2);
Map.Entry s2 = new AbstractMap.SimpleImmutableEntry(k1, v1);
Map.Entry s = new AbstractMap.SimpleImmutableEntry(s2);
assertEquals(e2, e);
assertEquals(e2.hashCode(), e.hashCode());
assertEquals(s2, s);
assertEquals(s2.hashCode(), s.hashCode());
assertEquals(e2, s2);
assertEquals(e2.hashCode(), s2.hashCode());
assertEquals(e, s);
assertEquals(e.hashCode(), s.hashCode());
}
/**
* Entries with different key-value pairs are not equal
*/
public void testNotEquals() {
Map.Entry e2 = new AbstractMap.SimpleEntry(k1, v1);
Map.Entry e = new AbstractMap.SimpleEntry(k2, v1);
assertFalse(e2.equals( e));
e = new AbstractMap.SimpleEntry(k1, v2);
assertFalse(e2.equals( e));
e = new AbstractMap.SimpleEntry(k2, v2);
assertFalse(e2.equals( e));
Map.Entry s2 = new AbstractMap.SimpleImmutableEntry(k1, v1);
Map.Entry s = new AbstractMap.SimpleImmutableEntry(k2, v1);
assertFalse(s2.equals( s));
s = new AbstractMap.SimpleImmutableEntry(k1, v2);
assertFalse(s2.equals( s));
s = new AbstractMap.SimpleImmutableEntry(k2, v2);
assertFalse(s2.equals( s));
}
/**
* getValue returns last setValue for SimpleEntry
*/
public void testSetValue1() {
Map.Entry e2 = new AbstractMap.SimpleEntry(k1, v1);
Map.Entry e = new AbstractMap.SimpleEntry(e2);
assertEquals(k1, e.getKey());
assertEquals(v1, e.getValue());
e.setValue(k2);
assertEquals(k2, e.getValue());
assertFalse(e2.equals( e));
}
/**
* setValue for SimpleImmutableEntry throws UnsupportedOperationException
*/
public void testsetValue2() {
Map.Entry s2 = new AbstractMap.SimpleImmutableEntry(k1, v1);
Map.Entry s = new AbstractMap.SimpleImmutableEntry(s2);
assertEquals(k1, s.getKey());
assertEquals(v1, s.getValue());
try {
s.setValue(k2);
fail();
} catch (UnsupportedOperationException success) {}
}
}
backport-util-concurrent-3.1-src/test/tck/src/ArrayDequeTest.java 0000644 0017507 0003772 00000043460 10346121124 024003 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.ArrayDeque;
import java.util.Collection;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Iterator;
import java.util.Random;
public class ArrayDequeTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(ArrayDequeTest.class);
}
/**
* Create a queue of given size containing consecutive
* Integers 0 ... n.
*/
private ArrayDeque populatedDeque(int n) {
ArrayDeque q = new ArrayDeque();
assertTrue(q.isEmpty());
for(int i = 0; i < n; ++i)
assertTrue(q.offerLast(new Integer(i)));
assertFalse(q.isEmpty());
assertEquals(n, q.size());
return q;
}
/**
* new queue is empty
*/
public void testConstructor1() {
assertEquals(0, new ArrayDeque().size());
}
/**
* Initializing from null Collection throws NPE
*/
public void testConstructor3() {
try {
ArrayDeque q = new ArrayDeque((Collection)null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Queue contains all elements of collection used to initialize
*/
public void testConstructor6() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
ArrayDeque q = new ArrayDeque(Arrays.asList(ints));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.pollFirst());
}
finally {}
}
/**
* isEmpty is true before add, false after
*/
public void testEmpty() {
ArrayDeque q = new ArrayDeque();
assertTrue(q.isEmpty());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.add(new Integer(2));
q.removeFirst();
q.removeFirst();
assertTrue(q.isEmpty());
}
/**
* size changes when elements added and removed
*/
public void testSize() {
ArrayDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i, q.size());
q.removeFirst();
}
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
q.add(new Integer(i));
}
}
/**
* push(null) throws NPE
*/
public void testPushNull() {
try {
ArrayDeque q = new ArrayDeque(1);
q.push(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* peekFirst returns element inserted with push
*/
public void testPush() {
ArrayDeque q = populatedDeque(3);
q.pollLast();
q.push(four);
assertEquals(four,q.peekFirst());
}
/**
* pop removes next element, or throws NSEE if empty
*/
public void testPop() {
ArrayDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.pop()).intValue());
}
try {
q.pop();
shouldThrow();
} catch (NoSuchElementException success){
}
}
/**
* offer(null) throws NPE
*/
public void testOfferFirstNull() {
try {
ArrayDeque q = new ArrayDeque();
q.offerFirst(null);
shouldThrow();
} catch (NullPointerException success) {
}
}
/**
* OfferFirst succeeds
*/
public void testOfferFirst() {
ArrayDeque q = new ArrayDeque();
assertTrue(q.offerFirst(new Integer(0)));
assertTrue(q.offerFirst(new Integer(1)));
}
/**
* OfferLast succeeds
*/
public void testOfferLast() {
ArrayDeque q = new ArrayDeque();
assertTrue(q.offerLast(new Integer(0)));
assertTrue(q.offerLast(new Integer(1)));
}
/**
* add succeeds
*/
public void testAdd() {
ArrayDeque q = new ArrayDeque();
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
assertTrue(q.add(new Integer(i)));
}
}
/**
* addAll(null) throws NPE
*/
public void testAddAll1() {
try {
ArrayDeque q = new ArrayDeque();
q.addAll(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Queue contains all elements, in traversal order, of successful addAll
*/
public void testAddAll5() {
try {
Integer[] empty = new Integer[0];
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
ArrayDeque q = new ArrayDeque();
assertFalse(q.addAll(Arrays.asList(empty)));
assertTrue(q.addAll(Arrays.asList(ints)));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.pollFirst());
}
finally {}
}
/**
* pollFirst succeeds unless empty
*/
public void testPollFirst() {
ArrayDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.pollFirst()).intValue());
}
assertNull(q.pollFirst());
}
/**
* pollLast succeeds unless empty
*/
public void testPollLast() {
ArrayDeque q = populatedDeque(SIZE);
for (int i = SIZE-1; i >= 0; --i) {
assertEquals(i, ((Integer)q.pollLast()).intValue());
}
assertNull(q.pollLast());
}
/**
* poll succeeds unless empty
*/
public void testPoll() {
ArrayDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.poll()).intValue());
}
assertNull(q.poll());
}
/**
* remove removes next element, or throws NSEE if empty
*/
public void testRemove() {
ArrayDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.remove()).intValue());
}
try {
q.remove();
shouldThrow();
} catch (NoSuchElementException success){
}
}
/**
* peekFirst returns next element, or null if empty
*/
public void testPeekFirst() {
ArrayDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.peekFirst()).intValue());
q.pollFirst();
assertTrue(q.peekFirst() == null ||
i != ((Integer)q.peekFirst()).intValue());
}
assertNull(q.peekFirst());
}
/**
* peek returns next element, or null if empty
*/
public void testPeek() {
ArrayDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.peek()).intValue());
q.poll();
assertTrue(q.peek() == null ||
i != ((Integer)q.peek()).intValue());
}
assertNull(q.peek());
}
/**
* peekLast returns next element, or null if empty
*/
public void testPeekLast() {
ArrayDeque q = populatedDeque(SIZE);
for (int i = SIZE-1; i >= 0; --i) {
assertEquals(i, ((Integer)q.peekLast()).intValue());
q.pollLast();
assertTrue(q.peekLast() == null ||
i != ((Integer)q.peekLast()).intValue());
}
assertNull(q.peekLast());
}
/**
* getFirst returns next getFirst, or throws NSEE if empty
*/
public void testFirstElement() {
ArrayDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.getFirst()).intValue());
q.pollFirst();
}
try {
q.getFirst();
shouldThrow();
}
catch (NoSuchElementException success) {}
}
/**
* getLast returns next element, or throws NSEE if empty
*/
public void testLastElement() {
ArrayDeque q = populatedDeque(SIZE);
for (int i = SIZE-1; i >= 0; --i) {
assertEquals(i, ((Integer)q.getLast()).intValue());
q.pollLast();
}
try {
q.getLast();
shouldThrow();
}
catch (NoSuchElementException success) {}
assertNull(q.peekLast());
}
/**
* removeFirst removes next element, or throws NSEE if empty
*/
public void testRemoveFirst() {
ArrayDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.removeFirst()).intValue());
}
try {
q.removeFirst();
shouldThrow();
} catch (NoSuchElementException success){
}
}
/**
* removeFirstOccurrence(x) removes x and returns true if present
*/
public void testRemoveFirstOccurrence() {
ArrayDeque q = populatedDeque(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.removeFirstOccurrence(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.removeFirstOccurrence(new Integer(i)));
assertFalse(q.removeFirstOccurrence(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* removeLastOccurrence(x) removes x and returns true if present
*/
public void testRemoveLastOccurrence() {
ArrayDeque q = populatedDeque(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.removeLastOccurrence(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.removeLastOccurrence(new Integer(i)));
assertFalse(q.removeLastOccurrence(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* contains(x) reports true when elements added but not yet removed
*/
public void testContains() {
ArrayDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.contains(new Integer(i)));
q.pollFirst();
assertFalse(q.contains(new Integer(i)));
}
}
/**
* clear removes all elements
*/
public void testClear() {
ArrayDeque q = populatedDeque(SIZE);
q.clear();
assertTrue(q.isEmpty());
assertEquals(0, q.size());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.clear();
assertTrue(q.isEmpty());
}
/**
* containsAll(c) is true when c contains a subset of elements
*/
public void testContainsAll() {
ArrayDeque q = populatedDeque(SIZE);
ArrayDeque p = new ArrayDeque();
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.containsAll(p));
assertFalse(p.containsAll(q));
p.add(new Integer(i));
}
assertTrue(p.containsAll(q));
}
/**
* retainAll(c) retains only those elements of c and reports true if changed
*/
public void testRetainAll() {
ArrayDeque q = populatedDeque(SIZE);
ArrayDeque p = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
boolean changed = q.retainAll(p);
if (i == 0)
assertFalse(changed);
else
assertTrue(changed);
assertTrue(q.containsAll(p));
assertEquals(SIZE-i, q.size());
p.removeFirst();
}
}
/**
* removeAll(c) removes only those elements of c and reports true if changed
*/
public void testRemoveAll() {
for (int i = 1; i < SIZE; ++i) {
ArrayDeque q = populatedDeque(SIZE);
ArrayDeque p = populatedDeque(i);
assertTrue(q.removeAll(p));
assertEquals(SIZE-i, q.size());
for (int j = 0; j < i; ++j) {
Integer I = (Integer)(p.removeFirst());
assertFalse(q.contains(I));
}
}
}
/**
* toArray contains all elements
*/
public void testToArray() {
ArrayDeque q = populatedDeque(SIZE);
Object[] o = q.toArray();
Arrays.sort(o);
for(int i = 0; i < o.length; i++)
assertEquals(o[i], q.pollFirst());
}
/**
* toArray(a) contains all elements
*/
public void testToArray2() {
ArrayDeque q = populatedDeque(SIZE);
Integer[] ints = new Integer[SIZE];
ints = (Integer[])q.toArray(ints);
Arrays.sort(ints);
for(int i = 0; i < ints.length; i++)
assertEquals(ints[i], q.pollFirst());
}
/**
* toArray(null) throws NPE
*/
public void testToArray_BadArg() {
try {
ArrayDeque l = new ArrayDeque();
l.add(new Object());
Object o[] = l.toArray(null);
shouldThrow();
} catch(NullPointerException success){}
}
/**
* toArray with incompatable aray type throws CCE
*/
public void testToArray1_BadArg() {
try {
ArrayDeque l = new ArrayDeque();
l.add(new Integer(5));
Object o[] = l.toArray(new String[10] );
shouldThrow();
} catch(ArrayStoreException success){}
}
/**
* iterator iterates through all elements
*/
public void testIterator() {
ArrayDeque q = populatedDeque(SIZE);
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, SIZE);
}
/**
* iterator ordering is FIFO
*/
public void testIteratorOrdering() {
final ArrayDeque q = new ArrayDeque();
q.add(new Integer(1));
q.add(new Integer(2));
q.add(new Integer(3));
int k = 0;
for (Iterator it = q.iterator(); it.hasNext();) {
int i = ((Integer)(it.next())).intValue();
assertEquals(++k, i);
}
assertEquals(3, k);
}
/**
* iterator.remove removes current element
*/
public void testIteratorRemove () {
final ArrayDeque q = new ArrayDeque();
final Random rng = new Random();
for (int iters = 0; iters < 100; ++iters) {
int max = rng.nextInt(5) + 2;
int split = rng.nextInt(max-1) + 1;
for (int j = 1; j <= max; ++j)
q.add(new Integer(j));
Iterator it = q.iterator();
for (int j = 1; j <= split; ++j)
assertEquals(it.next(), new Integer(j));
it.remove();
assertEquals(it.next(), new Integer(split+1));
for (int j = 1; j <= split; ++j)
q.remove(new Integer(j));
it = q.iterator();
for (int j = split+1; j <= max; ++j) {
assertEquals(it.next(), new Integer(j));
it.remove();
}
assertFalse(it.hasNext());
assertTrue(q.isEmpty());
}
}
/**
* Descending iterator iterates through all elements
*/
public void testDescendingIterator() {
ArrayDeque q = populatedDeque(SIZE);
int i = 0;
Iterator it = q.descendingIterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, SIZE);
assertFalse(it.hasNext());
try {
it.next();
} catch(NoSuchElementException success) {
}
}
/**
* Descending iterator ordering is reverse FIFO
*/
public void testDescendingIteratorOrdering() {
final ArrayDeque q = new ArrayDeque();
for (int iters = 0; iters < 100; ++iters) {
q.add(new Integer(3));
q.add(new Integer(2));
q.add(new Integer(1));
int k = 0;
for (Iterator it = q.descendingIterator(); it.hasNext();) {
int i = ((Integer)(it.next())).intValue();
assertEquals(++k, i);
}
assertEquals(3, k);
q.remove();
q.remove();
q.remove();
}
}
/**
* descendingIterator.remove removes current element
*/
public void testDescendingIteratorRemove () {
final ArrayDeque q = new ArrayDeque();
final Random rng = new Random();
for (int iters = 0; iters < 100; ++iters) {
int max = rng.nextInt(5) + 2;
int split = rng.nextInt(max-1) + 1;
for (int j = max; j >= 1; --j)
q.add(new Integer(j));
Iterator it = q.descendingIterator();
for (int j = 1; j <= split; ++j)
assertEquals(it.next(), new Integer(j));
it.remove();
assertEquals(it.next(), new Integer(split+1));
for (int j = 1; j <= split; ++j)
q.remove(new Integer(j));
it = q.descendingIterator();
for (int j = split+1; j <= max; ++j) {
assertEquals(it.next(), new Integer(j));
it.remove();
}
assertFalse(it.hasNext());
assertTrue(q.isEmpty());
}
}
/**
* toString contains toStrings of elements
*/
public void testToString() {
ArrayDeque q = populatedDeque(SIZE);
String s = q.toString();
for (int i = 0; i < SIZE; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
/**
* peekFirst returns element inserted with addFirst
*/
public void testAddFirst() {
ArrayDeque q = populatedDeque(3);
q.addFirst(four);
assertEquals(four,q.peekFirst());
}
/**
* peekLast returns element inserted with addLast
*/
public void testAddLast() {
ArrayDeque q = populatedDeque(3);
q.addLast(four);
assertEquals(four,q.peekLast());
}
}
backport-util-concurrent-3.1-src/test/tck/src/LinkedListTest.java 0000644 0017507 0003772 00000042223 10346121124 023777 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.LinkedList;
import java.util.Collection;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Iterator;
public class LinkedListTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(LinkedListTest.class);
}
/**
* Create a queue of given size containing consecutive
* Integers 0 ... n.
*/
private LinkedList populatedQueue(int n) {
LinkedList q = new LinkedList();
assertTrue(q.isEmpty());
for(int i = 0; i < n; ++i)
assertTrue(q.offer(new Integer(i)));
assertFalse(q.isEmpty());
assertEquals(n, q.size());
return q;
}
/**
* new queue is empty
*/
public void testConstructor1() {
assertEquals(0, new LinkedList().size());
}
/**
* Initializing from null Collection throws NPE
*/
public void testConstructor3() {
try {
LinkedList q = new LinkedList((Collection)null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Queue contains all elements of collection used to initialize
*/
public void testConstructor6() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
LinkedList q = new LinkedList(Arrays.asList(ints));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* isEmpty is true before add, false after
*/
public void testEmpty() {
LinkedList q = new LinkedList();
assertTrue(q.isEmpty());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.add(new Integer(2));
q.remove();
q.remove();
assertTrue(q.isEmpty());
}
/**
* size changes when elements added and removed
*/
public void testSize() {
LinkedList q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i, q.size());
q.remove();
}
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
q.add(new Integer(i));
}
}
/**
* offer(null) succeeds
*/
public void testOfferNull() {
try {
LinkedList q = new LinkedList();
q.offer(null);
} catch (NullPointerException ie) {
unexpectedException();
}
}
/**
* Offer succeeds
*/
public void testOffer() {
LinkedList q = new LinkedList();
assertTrue(q.offer(new Integer(0)));
assertTrue(q.offer(new Integer(1)));
}
/**
* add succeeds
*/
public void testAdd() {
LinkedList q = new LinkedList();
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
assertTrue(q.add(new Integer(i)));
}
}
/**
* addAll(null) throws NPE
*/
public void testAddAll1() {
try {
LinkedList q = new LinkedList();
q.addAll(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Queue contains all elements, in traversal order, of successful addAll
*/
public void testAddAll5() {
try {
Integer[] empty = new Integer[0];
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
LinkedList q = new LinkedList();
assertFalse(q.addAll(Arrays.asList(empty)));
assertTrue(q.addAll(Arrays.asList(ints)));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* addAll with too large an index throws IOOBE
*/
public void testAddAll2_IndexOutOfBoundsException() {
try {
LinkedList l = new LinkedList();
l.add(new Object());
LinkedList m = new LinkedList();
m.add(new Object());
l.addAll(4,m);
shouldThrow();
} catch(IndexOutOfBoundsException success) {}
}
/**
* addAll with negative index throws IOOBE
*/
public void testAddAll4_BadIndex() {
try {
LinkedList l = new LinkedList();
l.add(new Object());
LinkedList m = new LinkedList();
m.add(new Object());
l.addAll(-1,m);
shouldThrow();
} catch(IndexOutOfBoundsException success){}
}
/**
* poll succeeds unless empty
*/
public void testPoll() {
LinkedList q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.poll()).intValue());
}
assertNull(q.poll());
}
/**
* peek returns next element, or null if empty
*/
public void testPeek() {
LinkedList q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.peek()).intValue());
q.poll();
assertTrue(q.peek() == null ||
i != ((Integer)q.peek()).intValue());
}
assertNull(q.peek());
}
/**
* element returns next element, or throws NSEE if empty
*/
public void testElement() {
LinkedList q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.element()).intValue());
q.poll();
}
try {
q.element();
shouldThrow();
}
catch (NoSuchElementException success) {}
}
/**
* remove removes next element, or throws NSEE if empty
*/
public void testRemove() {
LinkedList q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.remove()).intValue());
}
try {
q.remove();
shouldThrow();
} catch (NoSuchElementException success){
}
}
/**
* remove(x) removes x and returns true if present
*/
public void testRemoveElement() {
LinkedList q = populatedQueue(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
assertFalse(q.remove(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* contains(x) reports true when elements added but not yet removed
*/
public void testContains() {
LinkedList q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.contains(new Integer(i)));
q.poll();
assertFalse(q.contains(new Integer(i)));
}
}
/**
* clear removes all elements
*/
public void testClear() {
LinkedList q = populatedQueue(SIZE);
q.clear();
assertTrue(q.isEmpty());
assertEquals(0, q.size());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.clear();
assertTrue(q.isEmpty());
}
/**
* containsAll(c) is true when c contains a subset of elements
*/
public void testContainsAll() {
LinkedList q = populatedQueue(SIZE);
LinkedList p = new LinkedList();
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.containsAll(p));
assertFalse(p.containsAll(q));
p.add(new Integer(i));
}
assertTrue(p.containsAll(q));
}
/**
* retainAll(c) retains only those elements of c and reports true if changed
*/
public void testRetainAll() {
LinkedList q = populatedQueue(SIZE);
LinkedList p = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
boolean changed = q.retainAll(p);
if (i == 0)
assertFalse(changed);
else
assertTrue(changed);
assertTrue(q.containsAll(p));
assertEquals(SIZE-i, q.size());
p.remove();
}
}
/**
* removeAll(c) removes only those elements of c and reports true if changed
*/
public void testRemoveAll() {
for (int i = 1; i < SIZE; ++i) {
LinkedList q = populatedQueue(SIZE);
LinkedList p = populatedQueue(i);
assertTrue(q.removeAll(p));
assertEquals(SIZE-i, q.size());
for (int j = 0; j < i; ++j) {
Integer I = (Integer)(p.remove());
assertFalse(q.contains(I));
}
}
}
/**
* toArray contains all elements
*/
public void testToArray() {
LinkedList q = populatedQueue(SIZE);
Object[] o = q.toArray();
Arrays.sort(o);
for(int i = 0; i < o.length; i++)
assertEquals(o[i], q.poll());
}
/**
* toArray(a) contains all elements
*/
public void testToArray2() {
LinkedList q = populatedQueue(SIZE);
Integer[] ints = new Integer[SIZE];
ints = (Integer[])q.toArray(ints);
Arrays.sort(ints);
for(int i = 0; i < ints.length; i++)
assertEquals(ints[i], q.poll());
}
/**
* toArray(null) throws NPE
*/
public void testToArray_BadArg() {
try {
LinkedList l = new LinkedList();
l.add(new Object());
Object o[] = l.toArray(null);
shouldThrow();
} catch(NullPointerException success){}
}
/**
* toArray with incompatable aray type throws CCE
*/
public void testToArray1_BadArg() {
try {
LinkedList l = new LinkedList();
l.add(new Integer(5));
Object o[] = l.toArray(new String[10] );
shouldThrow();
} catch(ArrayStoreException success){}
}
/**
* iterator iterates through all elements
*/
public void testIterator() {
LinkedList q = populatedQueue(SIZE);
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, SIZE);
}
/**
* iterator ordering is FIFO
*/
public void testIteratorOrdering() {
final LinkedList q = new LinkedList();
q.add(new Integer(1));
q.add(new Integer(2));
q.add(new Integer(3));
int k = 0;
for (Iterator it = q.iterator(); it.hasNext();) {
int i = ((Integer)(it.next())).intValue();
assertEquals(++k, i);
}
assertEquals(3, k);
}
/**
* iterator.remove removes current element
*/
public void testIteratorRemove () {
final LinkedList q = new LinkedList();
q.add(new Integer(1));
q.add(new Integer(2));
q.add(new Integer(3));
Iterator it = q.iterator();
it.next();
it.remove();
it = q.iterator();
assertEquals(it.next(), new Integer(2));
assertEquals(it.next(), new Integer(3));
assertFalse(it.hasNext());
}
/**
* Descending iterator iterates through all elements
*/
public void testDescendingIterator() {
LinkedList q = populatedQueue(SIZE);
int i = 0;
Iterator it = q.descendingIterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, SIZE);
assertFalse(it.hasNext());
try {
it.next();
} catch(NoSuchElementException success) {
}
}
/**
* Descending iterator ordering is reverse FIFO
*/
public void testDescendingIteratorOrdering() {
final LinkedList q = new LinkedList();
q.add(new Integer(3));
q.add(new Integer(2));
q.add(new Integer(1));
int k = 0;
for (Iterator it = q.descendingIterator(); it.hasNext();) {
int i = ((Integer)(it.next())).intValue();
assertEquals(++k, i);
}
assertEquals(3, k);
}
/**
* descendingIterator.remove removes current element
*/
public void testDescendingIteratorRemove () {
final LinkedList q = new LinkedList();
q.add(new Integer(3));
q.add(new Integer(2));
q.add(new Integer(1));
Iterator it = q.descendingIterator();
it.next();
it.remove();
it = q.descendingIterator();
assertEquals(it.next(), new Integer(2));
assertEquals(it.next(), new Integer(3));
assertFalse(it.hasNext());
}
/**
* toString contains toStrings of elements
*/
public void testToString() {
LinkedList q = populatedQueue(SIZE);
String s = q.toString();
for (int i = 0; i < SIZE; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
/**
* peek returns element inserted with addFirst
*/
public void testAddFirst() {
LinkedList q = populatedQueue(3);
q.addFirst(four);
assertEquals(four,q.peek());
}
/**
* peekFirst returns element inserted with push
*/
public void testPush() {
LinkedList q = populatedQueue(3);
q.pollLast();
q.push(four);
assertEquals(four,q.peekFirst());
}
/**
* pop removes next element, or throws NSEE if empty
*/
public void testPop() {
LinkedList q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.pop()).intValue());
}
try {
q.pop();
shouldThrow();
} catch (NoSuchElementException success){
}
}
/**
* OfferFirst succeeds
*/
public void testOfferFirst() {
LinkedList q = new LinkedList();
assertTrue(q.offerFirst(new Integer(0)));
assertTrue(q.offerFirst(new Integer(1)));
}
/**
* OfferLast succeeds
*/
public void testOfferLast() {
LinkedList q = new LinkedList();
assertTrue(q.offerLast(new Integer(0)));
assertTrue(q.offerLast(new Integer(1)));
}
/**
* pollLast succeeds unless empty
*/
public void testPollLast() {
LinkedList q = populatedQueue(SIZE);
for (int i = SIZE-1; i >= 0; --i) {
assertEquals(i, ((Integer)q.pollLast()).intValue());
}
assertNull(q.pollLast());
}
/**
* peekFirst returns next element, or null if empty
*/
public void testPeekFirst() {
LinkedList q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.peekFirst()).intValue());
q.pollFirst();
assertTrue(q.peekFirst() == null ||
i != ((Integer)q.peekFirst()).intValue());
}
assertNull(q.peekFirst());
}
/**
* peekLast returns next element, or null if empty
*/
public void testPeekLast() {
LinkedList q = populatedQueue(SIZE);
for (int i = SIZE-1; i >= 0; --i) {
assertEquals(i, ((Integer)q.peekLast()).intValue());
q.pollLast();
assertTrue(q.peekLast() == null ||
i != ((Integer)q.peekLast()).intValue());
}
assertNull(q.peekLast());
}
public void testFirstElement() {
LinkedList q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.getFirst()).intValue());
q.pollFirst();
}
try {
q.getFirst();
shouldThrow();
}
catch (NoSuchElementException success) {}
}
/**
* getLast returns next element, or throws NSEE if empty
*/
public void testLastElement() {
LinkedList q = populatedQueue(SIZE);
for (int i = SIZE-1; i >= 0; --i) {
assertEquals(i, ((Integer)q.getLast()).intValue());
q.pollLast();
}
try {
q.getLast();
shouldThrow();
}
catch (NoSuchElementException success) {}
assertNull(q.peekLast());
}
/**
* removeFirstOccurrence(x) removes x and returns true if present
*/
public void testRemoveFirstOccurrence() {
LinkedList q = populatedQueue(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.removeFirstOccurrence(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.removeFirstOccurrence(new Integer(i)));
assertFalse(q.removeFirstOccurrence(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* removeLastOccurrence(x) removes x and returns true if present
*/
public void testRemoveLastOccurrence() {
LinkedList q = populatedQueue(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.removeLastOccurrence(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.removeLastOccurrence(new Integer(i)));
assertFalse(q.removeLastOccurrence(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
}
backport-util-concurrent-3.1-src/test/tck/src/DelayQueueTest.java 0000644 0017507 0003772 00000071252 10365510635 024016 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.helpers.*;
import java.util.NoSuchElementException;
import java.util.Iterator;
import java.util.ArrayList;
public class DelayQueueTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(DelayQueueTest.class);
}
private static final int NOCAP = Integer.MAX_VALUE;
/**
* A delayed implementation for testing.
* Most tests use Pseudodelays, where delays are all elapsed
* (so, no blocking solely for delays) but are still ordered
*/
static class PDelay implements Delayed {
int pseudodelay;
PDelay(int i) { pseudodelay = Integer.MIN_VALUE + i; }
public int compareTo(Object y) {
int i = pseudodelay;
int j = ((PDelay)y).pseudodelay;
if (i < j) return -1;
if (i > j) return 1;
return 0;
}
public int compareTo(Delayed y) {
int i = pseudodelay;
int j = ((PDelay)y).pseudodelay;
if (i < j) return -1;
if (i > j) return 1;
return 0;
}
public boolean equals(Object other) {
return ((PDelay)other).pseudodelay == pseudodelay;
}
public boolean equals(PDelay other) {
return ((PDelay)other).pseudodelay == pseudodelay;
}
public long getDelay(TimeUnit ignore) {
return pseudodelay;
}
public int intValue() {
return pseudodelay;
}
public String toString() {
return String.valueOf(pseudodelay);
}
}
/**
* Delayed implementation that actually delays
*/
static class NanoDelay implements Delayed {
long trigger;
NanoDelay(long i) {
trigger = Utils.nanoTime() + i;
}
public int compareTo(Object y) {
long i = trigger;
long j = ((NanoDelay)y).trigger;
if (i < j) return -1;
if (i > j) return 1;
return 0;
}
public int compareTo(Delayed y) {
long i = trigger;
long j = ((NanoDelay)y).trigger;
if (i < j) return -1;
if (i > j) return 1;
return 0;
}
public boolean equals(Object other) {
return ((NanoDelay)other).trigger == trigger;
}
public boolean equals(NanoDelay other) {
return ((NanoDelay)other).trigger == trigger;
}
public long getDelay(TimeUnit unit) {
long n = trigger - Utils.nanoTime();
return unit.convert(n, TimeUnit.NANOSECONDS);
}
public long getTriggerTime() {
return trigger;
}
public String toString() {
return String.valueOf(trigger);
}
}
/**
* Create a queue of given size containing consecutive
* PDelays 0 ... n.
*/
private DelayQueue populatedQueue(int n) {
DelayQueue q = new DelayQueue();
assertTrue(q.isEmpty());
for(int i = n-1; i >= 0; i-=2)
assertTrue(q.offer(new PDelay(i)));
for(int i = (n & 1); i < n; i+=2)
assertTrue(q.offer(new PDelay(i)));
assertFalse(q.isEmpty());
assertEquals(NOCAP, q.remainingCapacity());
assertEquals(n, q.size());
return q;
}
/**
* A new queue has unbounded capacity
*/
public void testConstructor1() {
assertEquals(NOCAP, new DelayQueue().remainingCapacity());
}
/**
* Initializing from null Collection throws NPE
*/
public void testConstructor3() {
try {
DelayQueue q = new DelayQueue(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from Collection of null elements throws NPE
*/
public void testConstructor4() {
try {
PDelay[] ints = new PDelay[SIZE];
DelayQueue q = new DelayQueue(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from Collection with some null elements throws NPE
*/
public void testConstructor5() {
try {
PDelay[] ints = new PDelay[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new PDelay(i);
DelayQueue q = new DelayQueue(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Queue contains all elements of collection used to initialize
*/
public void testConstructor6() {
try {
PDelay[] ints = new PDelay[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new PDelay(i);
DelayQueue q = new DelayQueue(Arrays.asList(ints));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* isEmpty is true before add, false after
*/
public void testEmpty() {
DelayQueue q = new DelayQueue();
assertTrue(q.isEmpty());
assertEquals(NOCAP, q.remainingCapacity());
q.add(new PDelay(1));
assertFalse(q.isEmpty());
q.add(new PDelay(2));
q.remove();
q.remove();
assertTrue(q.isEmpty());
}
/**
* remainingCapacity does not change when elementa added or removed,
* but size does
*/
public void testRemainingCapacity() {
DelayQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(NOCAP, q.remainingCapacity());
assertEquals(SIZE-i, q.size());
q.remove();
}
for (int i = 0; i < SIZE; ++i) {
assertEquals(NOCAP, q.remainingCapacity());
assertEquals(i, q.size());
q.add(new PDelay(i));
}
}
/**
* offer(null) throws NPE
*/
public void testOfferNull() {
try {
DelayQueue q = new DelayQueue();
q.offer(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* add(null) throws NPE
*/
public void testAddNull() {
try {
DelayQueue q = new DelayQueue();
q.add(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* offer non-null succeeds
*/
public void testOffer() {
DelayQueue q = new DelayQueue();
assertTrue(q.offer(new PDelay(0)));
assertTrue(q.offer(new PDelay(1)));
}
/**
* add succeeds
*/
public void testAdd() {
DelayQueue q = new DelayQueue();
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
assertTrue(q.add(new PDelay(i)));
}
}
/**
* addAll(null) throws NPE
*/
public void testAddAll1() {
try {
DelayQueue q = new DelayQueue();
q.addAll(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll(this) throws IAE
*/
public void testAddAllSelf() {
try {
DelayQueue q = populatedQueue(SIZE);
q.addAll(q);
shouldThrow();
}
catch (IllegalArgumentException success) {}
}
/**
* addAll of a collection with null elements throws NPE
*/
public void testAddAll2() {
try {
DelayQueue q = new DelayQueue();
PDelay[] ints = new PDelay[SIZE];
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with any null elements throws NPE after
* possibly adding some elements
*/
public void testAddAll3() {
try {
DelayQueue q = new DelayQueue();
PDelay[] ints = new PDelay[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new PDelay(i);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Queue contains all elements of successful addAll
*/
public void testAddAll5() {
try {
PDelay[] empty = new PDelay[0];
PDelay[] ints = new PDelay[SIZE];
for (int i = SIZE-1; i >= 0; --i)
ints[i] = new PDelay(i);
DelayQueue q = new DelayQueue();
assertFalse(q.addAll(Arrays.asList(empty)));
assertTrue(q.addAll(Arrays.asList(ints)));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* put(null) throws NPE
*/
public void testPutNull() {
try {
DelayQueue q = new DelayQueue();
q.put(null);
shouldThrow();
}
catch (NullPointerException success){
}
}
/**
* all elements successfully put are contained
*/
public void testPut() {
try {
DelayQueue q = new DelayQueue();
for (int i = 0; i < SIZE; ++i) {
PDelay I = new PDelay(i);
q.put(I);
assertTrue(q.contains(I));
}
assertEquals(SIZE, q.size());
}
finally {
}
}
/**
* put doesn't block waiting for take
*/
public void testPutWithTake() {
final DelayQueue q = new DelayQueue();
Thread t = new Thread(new Runnable() {
public void run() {
int added = 0;
try {
q.put(new PDelay(0));
++added;
q.put(new PDelay(0));
++added;
q.put(new PDelay(0));
++added;
q.put(new PDelay(0));
++added;
threadAssertTrue(added == 4);
} finally {
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
q.take();
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* timed offer does not time out
*/
public void testTimedOffer() {
final DelayQueue q = new DelayQueue();
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.put(new PDelay(0));
q.put(new PDelay(0));
threadAssertTrue(q.offer(new PDelay(0), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
threadAssertTrue(q.offer(new PDelay(0), LONG_DELAY_MS, TimeUnit.MILLISECONDS));
} finally { }
}
});
try {
t.start();
Thread.sleep(SMALL_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* take retrieves elements in priority order
*/
public void testTake() {
try {
DelayQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(new PDelay(i), ((PDelay)q.take()));
}
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* take blocks interruptibly when empty
*/
public void testTakeFromEmpty() {
final DelayQueue q = new DelayQueue();
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.take();
threadShouldThrow();
} catch (InterruptedException success){ }
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* Take removes existing elements until empty, then blocks interruptibly
*/
public void testBlockingTake() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
DelayQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
threadAssertEquals(new PDelay(i), ((PDelay)q.take()));
}
q.take();
threadShouldThrow();
} catch (InterruptedException success){
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* poll succeeds unless empty
*/
public void testPoll() {
DelayQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(new PDelay(i), ((PDelay)q.poll()));
}
assertNull(q.poll());
}
/**
* timed pool with zero timeout succeeds when non-empty, else times out
*/
public void testTimedPoll0() {
try {
DelayQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(new PDelay(i), ((PDelay)q.poll(0, TimeUnit.MILLISECONDS)));
}
assertNull(q.poll(0, TimeUnit.MILLISECONDS));
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* timed pool with nonzero timeout succeeds when non-empty, else times out
*/
public void testTimedPoll() {
try {
DelayQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(new PDelay(i), ((PDelay)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)));
}
assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* Interrupted timed poll throws InterruptedException instead of
* returning timeout status
*/
public void testInterruptedTimedPoll() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
DelayQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
threadAssertEquals(new PDelay(i), ((PDelay)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)));
}
threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch (InterruptedException success){
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* timed poll before a delayed offer fails; after offer succeeds;
* on interruption throws
*/
public void testTimedPollWithOffer() {
final DelayQueue q = new DelayQueue();
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
threadFail("Should block");
} catch (InterruptedException success) { }
}
});
try {
t.start();
Thread.sleep(SMALL_DELAY_MS);
assertTrue(q.offer(new PDelay(0), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* peek returns next element, or null if empty
*/
public void testPeek() {
DelayQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(new PDelay(i), ((PDelay)q.peek()));
q.poll();
if (q.isEmpty())
assertNull(q.peek());
else
assertTrue(i != ((PDelay)q.peek()).intValue());
}
assertNull(q.peek());
}
/**
* element returns next element, or throws NSEE if empty
*/
public void testElement() {
DelayQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(new PDelay(i), ((PDelay)q.element()));
q.poll();
}
try {
q.element();
shouldThrow();
}
catch (NoSuchElementException success) {}
}
/**
* remove removes next element, or throws NSEE if empty
*/
public void testRemove() {
DelayQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(new PDelay(i), ((PDelay)q.remove()));
}
try {
q.remove();
shouldThrow();
} catch (NoSuchElementException success){
}
}
/**
* remove(x) removes x and returns true if present
*/
public void testRemoveElement() {
DelayQueue q = populatedQueue(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.remove(new PDelay(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.remove(new PDelay(i)));
assertFalse(q.remove(new PDelay(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* contains(x) reports true when elements added but not yet removed
*/
public void testContains() {
DelayQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.contains(new PDelay(i)));
q.poll();
assertFalse(q.contains(new PDelay(i)));
}
}
/**
* clear removes all elements
*/
public void testClear() {
DelayQueue q = populatedQueue(SIZE);
q.clear();
assertTrue(q.isEmpty());
assertEquals(0, q.size());
assertEquals(NOCAP, q.remainingCapacity());
PDelay x = new PDelay(1);
q.add(x);
assertFalse(q.isEmpty());
assertTrue(q.contains(x));
q.clear();
assertTrue(q.isEmpty());
}
/**
* containsAll(c) is true when c contains a subset of elements
*/
public void testContainsAll() {
DelayQueue q = populatedQueue(SIZE);
DelayQueue p = new DelayQueue();
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.containsAll(p));
assertFalse(p.containsAll(q));
p.add(new PDelay(i));
}
assertTrue(p.containsAll(q));
}
/**
* retainAll(c) retains only those elements of c and reports true if changed
*/
public void testRetainAll() {
DelayQueue q = populatedQueue(SIZE);
DelayQueue p = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
boolean changed = q.retainAll(p);
if (i == 0)
assertFalse(changed);
else
assertTrue(changed);
assertTrue(q.containsAll(p));
assertEquals(SIZE-i, q.size());
p.remove();
}
}
/**
* removeAll(c) removes only those elements of c and reports true if changed
*/
public void testRemoveAll() {
for (int i = 1; i < SIZE; ++i) {
DelayQueue q = populatedQueue(SIZE);
DelayQueue p = populatedQueue(i);
assertTrue(q.removeAll(p));
assertEquals(SIZE-i, q.size());
for (int j = 0; j < i; ++j) {
PDelay I = (PDelay)(p.remove());
assertFalse(q.contains(I));
}
}
}
/**
* toArray contains all elements
*/
public void testToArray() {
DelayQueue q = populatedQueue(SIZE);
Object[] o = q.toArray();
Arrays.sort(o);
try {
for(int i = 0; i < o.length; i++)
assertEquals(o[i], q.take());
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* toArray(a) contains all elements
*/
public void testToArray2() {
DelayQueue q = populatedQueue(SIZE);
PDelay[] ints = new PDelay[SIZE];
ints = (PDelay[])q.toArray(ints);
Arrays.sort(ints);
try {
for(int i = 0; i < ints.length; i++)
assertEquals(ints[i], q.take());
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* toArray(null) throws NPE
*/
public void testToArray_BadArg() {
try {
DelayQueue q = populatedQueue(SIZE);
Object o[] = q.toArray(null);
shouldThrow();
} catch(NullPointerException success){}
}
/**
* toArray with incompatible array type throws CCE
*/
public void testToArray1_BadArg() {
try {
DelayQueue q = populatedQueue(SIZE);
Object o[] = q.toArray(new String[10] );
shouldThrow();
} catch(ArrayStoreException success){}
}
/**
* iterator iterates through all elements
*/
public void testIterator() {
DelayQueue q = populatedQueue(SIZE);
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, SIZE);
}
/**
* iterator.remove removes current element
*/
public void testIteratorRemove () {
final DelayQueue q = new DelayQueue();
q.add(new PDelay(2));
q.add(new PDelay(1));
q.add(new PDelay(3));
Iterator it = q.iterator();
it.next();
it.remove();
it = q.iterator();
assertEquals(it.next(), new PDelay(2));
assertEquals(it.next(), new PDelay(3));
assertFalse(it.hasNext());
}
/**
* toString contains toStrings of elements
*/
public void testToString() {
DelayQueue q = populatedQueue(SIZE);
String s = q.toString();
for (int i = 0; i < SIZE; ++i) {
assertTrue(s.indexOf(String.valueOf(Integer.MIN_VALUE+i)) >= 0);
}
}
/**
* offer transfers elements across Executor tasks
*/
public void testPollInExecutor() {
final DelayQueue q = new DelayQueue();
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new Runnable() {
public void run() {
threadAssertNull(q.poll());
try {
threadAssertTrue(null != q.poll(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
threadAssertTrue(q.isEmpty());
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
executor.execute(new Runnable() {
public void run() {
try {
Thread.sleep(SHORT_DELAY_MS);
q.put(new PDelay(1));
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
joinPool(executor);
}
/**
* Delayed actions do not occur until their delay elapses
*/
public void testDelay() {
DelayQueue q = new DelayQueue();
NanoDelay[] elements = new NanoDelay[SIZE];
for (int i = 0; i < SIZE; ++i) {
elements[i] = new NanoDelay(1000000000L + 1000000L * (SIZE - i));
}
for (int i = 0; i < SIZE; ++i) {
q.add(elements[i]);
}
try {
long last = 0;
for (int i = 0; i < SIZE; ++i) {
NanoDelay e = (NanoDelay)(q.take());
long tt = e.getTriggerTime();
assertTrue(tt <= Utils.nanoTime());
if (i != 0)
assertTrue(tt >= last);
last = tt;
}
}
catch(InterruptedException ie) {
unexpectedException();
}
}
/**
* peek of a non-empty queue returns non-null even if not expired
*/
public void testPeekDelayed() {
DelayQueue q = new DelayQueue();
q.add(new NanoDelay(Long.MAX_VALUE));
assert(q.peek() != null);
}
/**
* poll of a non-empty queue returns null if no expired elements.
*/
public void testPollDelayed() {
DelayQueue q = new DelayQueue();
q.add(new NanoDelay(Long.MAX_VALUE));
assertNull(q.poll());
}
/**
* timed poll of a non-empty queue returns null if no expired elements.
*/
public void testTimedPollDelayed() {
DelayQueue q = new DelayQueue();
q.add(new NanoDelay(LONG_DELAY_MS * 1000000L));
try {
assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch (Exception ex) {
unexpectedException();
}
}
/**
* drainTo(null) throws NPE
*/
public void testDrainToNull() {
DelayQueue q = populatedQueue(SIZE);
try {
q.drainTo(null);
shouldThrow();
} catch(NullPointerException success) {
}
}
/**
* drainTo(this) throws IAE
*/
public void testDrainToSelf() {
DelayQueue q = populatedQueue(SIZE);
try {
q.drainTo(q);
shouldThrow();
} catch(IllegalArgumentException success) {
}
}
/**
* drainTo(c) empties queue into another collection c
*/
public void testDrainTo() {
DelayQueue q = new DelayQueue();
PDelay[] elems = new PDelay[SIZE];
for (int i = 0; i < SIZE; ++i) {
elems[i] = new PDelay(i);
q.add(elems[i]);
}
ArrayList l = new ArrayList();
q.drainTo(l);
assertEquals(q.size(), 0);
for (int i = 0; i < SIZE; ++i)
assertEquals(l.get(i), elems[i]);
q.add(elems[0]);
q.add(elems[1]);
assertFalse(q.isEmpty());
assertTrue(q.contains(elems[0]));
assertTrue(q.contains(elems[1]));
l.clear();
q.drainTo(l);
assertEquals(q.size(), 0);
assertEquals(l.size(), 2);
for (int i = 0; i < 2; ++i)
assertEquals(l.get(i), elems[i]);
}
/**
* drainTo empties queue
*/
public void testDrainToWithActivePut() {
final DelayQueue q = populatedQueue(SIZE);
Thread t = new Thread(new Runnable() {
public void run() {
q.put(new PDelay(SIZE+1));
}
});
try {
t.start();
ArrayList l = new ArrayList();
q.drainTo(l);
assertTrue(l.size() >= SIZE);
t.join();
assertTrue(q.size() + l.size() >= SIZE);
} catch(Exception e){
unexpectedException();
}
}
/**
* drainTo(null, n) throws NPE
*/
public void testDrainToNullN() {
DelayQueue q = populatedQueue(SIZE);
try {
q.drainTo(null, 0);
shouldThrow();
} catch(NullPointerException success) {
}
}
/**
* drainTo(this, n) throws IAE
*/
public void testDrainToSelfN() {
DelayQueue q = populatedQueue(SIZE);
try {
q.drainTo(q, 0);
shouldThrow();
} catch(IllegalArgumentException success) {
}
}
/**
* drainTo(c, n) empties first max {n, size} elements of queue into c
*/
public void testDrainToN() {
for (int i = 0; i < SIZE + 2; ++i) {
DelayQueue q = populatedQueue(SIZE);
ArrayList l = new ArrayList();
q.drainTo(l, i);
int k = (i < SIZE)? i : SIZE;
assertEquals(q.size(), SIZE-k);
assertEquals(l.size(), k);
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/AbstractExecutorServiceTest.java 0000644 0017507 0003772 00000060062 10431260156 026545 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.security.*;
import java.util.List;
import java.util.Collections;
import java.util.ArrayList;
import java.util.Iterator;
public class AbstractExecutorServiceTest extends JSR166TestCase{
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(AbstractExecutorServiceTest.class);
}
/**
* A no-frills implementation of AbstractExecutorService, designed
* to test the submit methods only.
*/
static class DirectExecutorService extends AbstractExecutorService {
public void execute(Runnable r) { r.run(); }
public void shutdown() { shutdown = true; }
public List shutdownNow() { shutdown = true; return Collections.EMPTY_LIST; }
public boolean isShutdown() { return shutdown; }
public boolean isTerminated() { return isShutdown(); }
public boolean awaitTermination(long timeout, TimeUnit unit) { return isShutdown(); }
private volatile boolean shutdown = false;
}
/**
* execute(runnable) runs it to completion
*/
public void testExecuteRunnable() {
try {
ExecutorService e = new DirectExecutorService();
TrackedShortRunnable task = new TrackedShortRunnable();
assertFalse(task.done);
Future future = e.submit(task);
future.get();
assertTrue(task.done);
}
catch (ExecutionException ex) {
unexpectedException();
}
catch (InterruptedException ex) {
unexpectedException();
}
}
/**
* Completed submit(callable) returns result
*/
public void testSubmitCallable() {
try {
ExecutorService e = new DirectExecutorService();
Future future = e.submit(new StringTask());
String result = (String)future.get();
assertSame(TEST_STRING, result);
}
catch (ExecutionException ex) {
unexpectedException();
}
catch (InterruptedException ex) {
unexpectedException();
}
}
/**
* Completed submit(runnable) returns successfully
*/
public void testSubmitRunnable() {
try {
ExecutorService e = new DirectExecutorService();
Future future = e.submit(new NoOpRunnable());
future.get();
assertTrue(future.isDone());
}
catch (ExecutionException ex) {
unexpectedException();
}
catch (InterruptedException ex) {
unexpectedException();
}
}
/**
* Completed submit(runnable, result) returns result
*/
public void testSubmitRunnable2() {
try {
ExecutorService e = new DirectExecutorService();
Future future = e.submit(new NoOpRunnable(), TEST_STRING);
String result = (String)future.get();
assertSame(TEST_STRING, result);
}
catch (ExecutionException ex) {
unexpectedException();
}
catch (InterruptedException ex) {
unexpectedException();
}
}
/**
* A submitted privileged action to completion
*/
public void testSubmitPrivilegedAction() {
Policy savedPolicy = null;
try {
savedPolicy = Policy.getPolicy();
AdjustablePolicy policy = new AdjustablePolicy();
policy.addPermission(new RuntimePermission("getContextClassLoader"));
policy.addPermission(new RuntimePermission("setContextClassLoader"));
Policy.setPolicy(policy);
} catch(AccessControlException ok) {
return;
}
try {
ExecutorService e = new DirectExecutorService();
Future future = e.submit(Executors.callable(new PrivilegedAction() {
public Object run() {
return TEST_STRING;
}}));
Object result = future.get();
assertSame(TEST_STRING, result);
}
catch (ExecutionException ex) {
unexpectedException();
}
catch (InterruptedException ex) {
unexpectedException();
}
finally {
try {
Policy.setPolicy(savedPolicy);
} catch(AccessControlException ok) {
return;
}
}
}
/**
* A submitted a privileged exception action runs to completion
*/
public void testSubmitPrivilegedExceptionAction() {
Policy savedPolicy = null;
try {
savedPolicy = Policy.getPolicy();
AdjustablePolicy policy = new AdjustablePolicy();
policy.addPermission(new RuntimePermission("getContextClassLoader"));
policy.addPermission(new RuntimePermission("setContextClassLoader"));
Policy.setPolicy(policy);
} catch(AccessControlException ok) {
return;
}
try {
ExecutorService e = new DirectExecutorService();
Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
public Object run() {
return TEST_STRING;
}}));
Object result = future.get();
assertSame(TEST_STRING, result);
}
catch (ExecutionException ex) {
unexpectedException();
}
catch (InterruptedException ex) {
unexpectedException();
}
finally {
Policy.setPolicy(savedPolicy);
}
}
/**
* A submitted failed privileged exception action reports exception
*/
public void testSubmitFailedPrivilegedExceptionAction() {
Policy savedPolicy = null;
try {
savedPolicy = Policy.getPolicy();
AdjustablePolicy policy = new AdjustablePolicy();
policy.addPermission(new RuntimePermission("getContextClassLoader"));
policy.addPermission(new RuntimePermission("setContextClassLoader"));
Policy.setPolicy(policy);
} catch(AccessControlException ok) {
return;
}
try {
ExecutorService e = new DirectExecutorService();
Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
public Object run() throws Exception {
throw new IndexOutOfBoundsException();
}}));
Object result = future.get();
shouldThrow();
}
catch (ExecutionException success) {
}
catch (InterruptedException ex) {
unexpectedException();
}
finally {
Policy.setPolicy(savedPolicy);
}
}
/**
* execute(null runnable) throws NPE
*/
public void testExecuteNullRunnable() {
try {
ExecutorService e = new DirectExecutorService();
TrackedShortRunnable task = null;
Future future = e.submit(task);
shouldThrow();
}
catch (NullPointerException success) {
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* submit(null callable) throws NPE
*/
public void testSubmitNullCallable() {
try {
ExecutorService e = new DirectExecutorService();
StringTask t = null;
Future future = e.submit(t);
shouldThrow();
}
catch (NullPointerException success) {
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* submit(runnable) throws RejectedExecutionException if
* executor is saturated.
*/
public void testExecute1() {
ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, 60, TimeUnit.SECONDS, new ArrayBlockingQueue(1));
try {
for(int i = 0; i < 5; ++i){
p.submit(new MediumRunnable());
}
shouldThrow();
} catch(RejectedExecutionException success){}
joinPool(p);
}
/**
* submit(callable) throws RejectedExecutionException
* if executor is saturated.
*/
public void testExecute2() {
ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, 60, TimeUnit.SECONDS, new ArrayBlockingQueue(1));
try {
for(int i = 0; i < 5; ++i) {
p.submit(new SmallCallable());
}
shouldThrow();
} catch(RejectedExecutionException e){}
joinPool(p);
}
/**
* Blocking on submit(callable) throws InterruptedException if
* caller interrupted.
*/
public void testInterruptedSubmit() {
final ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,60, TimeUnit.SECONDS, new ArrayBlockingQueue(10));
Thread t = new Thread(new Runnable() {
public void run() {
try {
p.submit(new Callable() {
public Object call() {
try {
Thread.sleep(MEDIUM_DELAY_MS);
shouldThrow();
} catch(InterruptedException e){
}
return null;
}
}).get();
} catch(InterruptedException success){
} catch(Exception e) {
unexpectedException();
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
} catch(Exception e){
unexpectedException();
}
joinPool(p);
}
/**
* get of submitted callable throws Exception if callable
* interrupted
*/
public void testSubmitIE() {
final ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,60, TimeUnit.SECONDS, new ArrayBlockingQueue(10));
final Callable c = new Callable() {
public Object call() {
try {
p.submit(new SmallCallable()).get();
shouldThrow();
} catch(InterruptedException e){}
catch(RejectedExecutionException e2){}
catch(ExecutionException e3){}
return Boolean.TRUE;
}
};
Thread t = new Thread(new Runnable() {
public void run() {
try {
c.call();
} catch(Exception e){}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch(InterruptedException e){
unexpectedException();
}
joinPool(p);
}
/**
* get of submit(callable) throws ExecutionException if callable
* throws exception
*/
public void testSubmitEE() {
ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,60, TimeUnit.SECONDS, new ArrayBlockingQueue(10));
try {
Callable c = new Callable() {
public Object call() {
int i = 5/0;
return Boolean.TRUE;
}
};
for(int i =0; i < 5; i++){
p.submit(c).get();
}
shouldThrow();
}
catch(ExecutionException success){
} catch(Exception e) {
unexpectedException();
}
joinPool(p);
}
/**
* invokeAny(null) throws NPE
*/
public void testInvokeAny1() {
ExecutorService e = new DirectExecutorService();
try {
e.invokeAny(null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(empty collection) throws IAE
*/
public void testInvokeAny2() {
ExecutorService e = new DirectExecutorService();
try {
e.invokeAny(new ArrayList());
} catch (IllegalArgumentException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(c) throws NPE if c has null elements
*/
public void testInvokeAny3() {
ExecutorService e = new DirectExecutorService();
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAny(l);
} catch (NullPointerException success) {
} catch(Exception ex) {
ex.printStackTrace();
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(c) throws ExecutionException if no task in c completes
*/
public void testInvokeAny4() {
ExecutorService e = new DirectExecutorService();
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
e.invokeAny(l);
} catch(ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(c) returns result of some task in c if at least one completes
*/
public void testInvokeAny5() {
ExecutorService e = new DirectExecutorService();
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
String result = (String)e.invokeAny(l);
assertSame(TEST_STRING, result);
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(null) throws NPE
*/
public void testInvokeAll1() {
ExecutorService e = new DirectExecutorService();
try {
e.invokeAll(null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(empty collection) returns empty collection
*/
public void testInvokeAll2() {
ExecutorService e = new DirectExecutorService();
try {
List r = e.invokeAll(new ArrayList());
assertTrue(r.isEmpty());
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(c) throws NPE if c has null elements
*/
public void testInvokeAll3() {
ExecutorService e = new DirectExecutorService();
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAll(l);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* get of returned element of invokeAll(c) throws exception on failed task
*/
public void testInvokeAll4() {
ExecutorService e = new DirectExecutorService();
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
List result = e.invokeAll(l);
assertEquals(1, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
((Future)it.next()).get();
} catch(ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(c) returns results of all completed tasks in c
*/
public void testInvokeAll5() {
ExecutorService e = new DirectExecutorService();
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
List result = e.invokeAll(l);
assertEquals(2, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
assertSame(TEST_STRING, ((Future)it.next()).get());
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(null) throws NPE
*/
public void testTimedInvokeAny1() {
ExecutorService e = new DirectExecutorService();
try {
e.invokeAny(null, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(null time unit) throws NPE
*/
public void testTimedInvokeAnyNullTimeUnit() {
ExecutorService e = new DirectExecutorService();
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
e.invokeAny(l, MEDIUM_DELAY_MS, null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(empty collection) throws IAE
*/
public void testTimedInvokeAny2() {
ExecutorService e = new DirectExecutorService();
try {
e.invokeAny(new ArrayList(), MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (IllegalArgumentException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(c) throws NPE if c has null elements
*/
public void testTimedInvokeAny3() {
ExecutorService e = new DirectExecutorService();
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
ex.printStackTrace();
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(c) throws ExecutionException if no task completes
*/
public void testTimedInvokeAny4() {
ExecutorService e = new DirectExecutorService();
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch(ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(c) returns result of some task in c
*/
public void testTimedInvokeAny5() {
ExecutorService e = new DirectExecutorService();
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
String result = (String)e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertSame(TEST_STRING, result);
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(null) throws NPE
*/
public void testTimedInvokeAll1() {
ExecutorService e = new DirectExecutorService();
try {
e.invokeAll(null, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(null time unit) throws NPE
*/
public void testTimedInvokeAllNullTimeUnit() {
ExecutorService e = new DirectExecutorService();
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
e.invokeAll(l, MEDIUM_DELAY_MS, null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(empty collection) returns empty collection
*/
public void testTimedInvokeAll2() {
ExecutorService e = new DirectExecutorService();
try {
List r = e.invokeAll(new ArrayList(), MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertTrue(r.isEmpty());
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(c) throws NPE if c has null elements
*/
public void testTimedInvokeAll3() {
ExecutorService e = new DirectExecutorService();
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* get of returned element of invokeAll(c) throws exception on failed task
*/
public void testTimedInvokeAll4() {
ExecutorService e = new DirectExecutorService();
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
List result = e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertEquals(1, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
((Future)it.next()).get();
} catch(ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(c) returns results of all completed tasks in c
*/
public void testTimedInvokeAll5() {
ExecutorService e = new DirectExecutorService();
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
List result = e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertEquals(2, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
assertSame(TEST_STRING, ((Future)it.next()).get());
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll cancels tasks not completed by timeout
*/
public void testTimedInvokeAll6() {
ExecutorService e = new DirectExecutorService();
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
l.add(new StringTask());
List result = e.invokeAll(l, SMALL_DELAY_MS, TimeUnit.MILLISECONDS);
assertEquals(3, result.size());
Iterator it = result.iterator();
Future f1 = (Future)it.next();
Future f2 = (Future)it.next();
Future f3 = (Future)it.next();
assertTrue(f1.isDone());
assertFalse(f1.isCancelled());
assertTrue(f2.isDone());
assertTrue(f3.isDone());
assertTrue(f3.isCancelled());
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/LinkedBlockingDequeTest.java 0000644 0017507 0003772 00000160345 10346121124 025606 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.io.*;
import java.util.NoSuchElementException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.ConcurrentModificationException;
import java.util.ArrayList;
public class LinkedBlockingDequeTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(LinkedBlockingDequeTest.class);
}
/**
* Create a deque of given size containing consecutive
* Integers 0 ... n.
*/
private LinkedBlockingDeque populatedDeque(int n) {
LinkedBlockingDeque q = new LinkedBlockingDeque(n);
assertTrue(q.isEmpty());
for(int i = 0; i < n; i++)
assertTrue(q.offer(new Integer(i)));
assertFalse(q.isEmpty());
assertEquals(0, q.remainingCapacity());
assertEquals(n, q.size());
return q;
}
/**
* isEmpty is true before add, false after
*/
public void testEmpty() {
LinkedBlockingDeque q = new LinkedBlockingDeque();
assertTrue(q.isEmpty());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.add(new Integer(2));
q.removeFirst();
q.removeFirst();
assertTrue(q.isEmpty());
}
/**
* size changes when elements added and removed
*/
public void testSize() {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i, q.size());
q.removeFirst();
}
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
q.add(new Integer(i));
}
}
/**
* offer(null) throws NPE
*/
public void testOfferFirstNull() {
try {
LinkedBlockingDeque q = new LinkedBlockingDeque();
q.offerFirst(null);
shouldThrow();
} catch (NullPointerException success) {
}
}
/**
* OfferFirst succeeds
*/
public void testOfferFirst() {
LinkedBlockingDeque q = new LinkedBlockingDeque();
assertTrue(q.offerFirst(new Integer(0)));
assertTrue(q.offerFirst(new Integer(1)));
}
/**
* OfferLast succeeds
*/
public void testOfferLast() {
LinkedBlockingDeque q = new LinkedBlockingDeque();
assertTrue(q.offerLast(new Integer(0)));
assertTrue(q.offerLast(new Integer(1)));
}
/**
* pollFirst succeeds unless empty
*/
public void testPollFirst() {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.pollFirst()).intValue());
}
assertNull(q.pollFirst());
}
/**
* pollLast succeeds unless empty
*/
public void testPollLast() {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = SIZE-1; i >= 0; --i) {
assertEquals(i, ((Integer)q.pollLast()).intValue());
}
assertNull(q.pollLast());
}
/**
* peekFirst returns next element, or null if empty
*/
public void testPeekFirst() {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.peekFirst()).intValue());
q.pollFirst();
assertTrue(q.peekFirst() == null ||
i != ((Integer)q.peekFirst()).intValue());
}
assertNull(q.peekFirst());
}
/**
* peek returns next element, or null if empty
*/
public void testPeek() {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.peek()).intValue());
q.pollFirst();
assertTrue(q.peek() == null ||
i != ((Integer)q.peek()).intValue());
}
assertNull(q.peek());
}
/**
* peekLast returns next element, or null if empty
*/
public void testPeekLast() {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = SIZE-1; i >= 0; --i) {
assertEquals(i, ((Integer)q.peekLast()).intValue());
q.pollLast();
assertTrue(q.peekLast() == null ||
i != ((Integer)q.peekLast()).intValue());
}
assertNull(q.peekLast());
}
/**
* getFirst returns next getFirst, or throws NSEE if empty
*/
public void testFirstElement() {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.getFirst()).intValue());
q.pollFirst();
}
try {
q.getFirst();
shouldThrow();
}
catch (NoSuchElementException success) {}
}
/**
* getLast returns next element, or throws NSEE if empty
*/
public void testLastElement() {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = SIZE-1; i >= 0; --i) {
assertEquals(i, ((Integer)q.getLast()).intValue());
q.pollLast();
}
try {
q.getLast();
shouldThrow();
}
catch (NoSuchElementException success) {}
assertNull(q.peekLast());
}
/**
* removeFirst removes next element, or throws NSEE if empty
*/
public void testRemoveFirst() {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.removeFirst()).intValue());
}
try {
q.removeFirst();
shouldThrow();
} catch (NoSuchElementException success){
}
}
/**
* remove removes next element, or throws NSEE if empty
*/
public void testRemove() {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.remove()).intValue());
}
try {
q.remove();
shouldThrow();
} catch (NoSuchElementException success){
}
}
/**
* removeFirstOccurrence(x) removes x and returns true if present
*/
public void testRemoveFirstOccurrence() {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.removeFirstOccurrence(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.removeFirstOccurrence(new Integer(i)));
assertFalse(q.removeFirstOccurrence(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* removeLastOccurrence(x) removes x and returns true if present
*/
public void testRemoveLastOccurrence() {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.removeLastOccurrence(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.removeLastOccurrence(new Integer(i)));
assertFalse(q.removeLastOccurrence(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* peekFirst returns element inserted with addFirst
*/
public void testAddFirst() {
LinkedBlockingDeque q = populatedDeque(3);
q.pollLast();
q.addFirst(four);
assertEquals(four,q.peekFirst());
}
/**
* peekLast returns element inserted with addLast
*/
public void testAddLast() {
LinkedBlockingDeque q = populatedDeque(3);
q.pollLast();
q.addLast(four);
assertEquals(four,q.peekLast());
}
/**
* A new deque has the indicated capacity, or Integer.MAX_VALUE if
* none given
*/
public void testConstructor1() {
assertEquals(SIZE, new LinkedBlockingDeque(SIZE).remainingCapacity());
assertEquals(Integer.MAX_VALUE, new LinkedBlockingDeque().remainingCapacity());
}
/**
* Constructor throws IAE if capacity argument nonpositive
*/
public void testConstructor2() {
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(0);
shouldThrow();
}
catch (IllegalArgumentException success) {}
}
/**
* Initializing from null Collection throws NPE
*/
public void testConstructor3() {
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from Collection of null elements throws NPE
*/
public void testConstructor4() {
try {
Integer[] ints = new Integer[SIZE];
LinkedBlockingDeque q = new LinkedBlockingDeque(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from Collection with some null elements throws NPE
*/
public void testConstructor5() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
LinkedBlockingDeque q = new LinkedBlockingDeque(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Deque contains all elements of collection used to initialize
*/
public void testConstructor6() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
LinkedBlockingDeque q = new LinkedBlockingDeque(Arrays.asList(ints));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* Deque transitions from empty to full when elements added
*/
public void testEmptyFull() {
LinkedBlockingDeque q = new LinkedBlockingDeque(2);
assertTrue(q.isEmpty());
assertEquals("should have room for 2", 2, q.remainingCapacity());
q.add(one);
assertFalse(q.isEmpty());
q.add(two);
assertFalse(q.isEmpty());
assertEquals(0, q.remainingCapacity());
assertFalse(q.offer(three));
}
/**
* remainingCapacity decreases on add, increases on remove
*/
public void testRemainingCapacity() {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.remainingCapacity());
assertEquals(SIZE-i, q.size());
q.remove();
}
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i, q.remainingCapacity());
assertEquals(i, q.size());
q.add(new Integer(i));
}
}
/**
* offer(null) throws NPE
*/
public void testOfferNull() {
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(1);
q.offer(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* add(null) throws NPE
*/
public void testAddNull() {
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(1);
q.add(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* push(null) throws NPE
*/
public void testPushNull() {
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(1);
q.push(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* push succeeds if not full; throws ISE if full
*/
public void testPush() {
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
Integer I = new Integer(i);
q.push(I);
assertEquals(I, q.peek());
}
assertEquals(0, q.remainingCapacity());
q.push(new Integer(SIZE));
} catch (IllegalStateException success){
}
}
/**
* peekFirst returns element inserted with push
*/
public void testPushWithPeek() {
LinkedBlockingDeque q = populatedDeque(3);
q.pollLast();
q.push(four);
assertEquals(four,q.peekFirst());
}
/**
* pop removes next element, or throws NSEE if empty
*/
public void testPop() {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.pop()).intValue());
}
try {
q.pop();
shouldThrow();
} catch (NoSuchElementException success){
}
}
/**
* Offer succeeds if not full; fails if full
*/
public void testOffer() {
LinkedBlockingDeque q = new LinkedBlockingDeque(1);
assertTrue(q.offer(zero));
assertFalse(q.offer(one));
}
/**
* add succeeds if not full; throws ISE if full
*/
public void testAdd() {
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.add(new Integer(i)));
}
assertEquals(0, q.remainingCapacity());
q.add(new Integer(SIZE));
} catch (IllegalStateException success){
}
}
/**
* addAll(null) throws NPE
*/
public void testAddAll1() {
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(1);
q.addAll(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll(this) throws IAE
*/
public void testAddAllSelf() {
try {
LinkedBlockingDeque q = populatedDeque(SIZE);
q.addAll(q);
shouldThrow();
}
catch (IllegalArgumentException success) {}
}
/**
* addAll of a collection with null elements throws NPE
*/
public void testAddAll2() {
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
Integer[] ints = new Integer[SIZE];
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with any null elements throws NPE after
* possibly adding some elements
*/
public void testAddAll3() {
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll throws ISE if not enough room
*/
public void testAddAll4() {
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(1);
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (IllegalStateException success) {}
}
/**
* Deque contains all elements, in traversal order, of successful addAll
*/
public void testAddAll5() {
try {
Integer[] empty = new Integer[0];
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
assertFalse(q.addAll(Arrays.asList(empty)));
assertTrue(q.addAll(Arrays.asList(ints)));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* put(null) throws NPE
*/
public void testPutNull() {
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
q.put(null);
shouldThrow();
}
catch (NullPointerException success){
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* all elements successfully put are contained
*/
public void testPut() {
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
Integer I = new Integer(i);
q.put(I);
assertTrue(q.contains(I));
}
assertEquals(0, q.remainingCapacity());
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* put blocks interruptibly if full
*/
public void testBlockingPut() {
Thread t = new Thread(new Runnable() {
public void run() {
int added = 0;
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
q.put(new Integer(i));
++added;
}
q.put(new Integer(SIZE));
threadShouldThrow();
} catch (InterruptedException ie){
threadAssertEquals(added, SIZE);
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* put blocks waiting for take when full
*/
public void testPutWithTake() {
final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
Thread t = new Thread(new Runnable() {
public void run() {
int added = 0;
try {
q.put(new Object());
++added;
q.put(new Object());
++added;
q.put(new Object());
++added;
q.put(new Object());
++added;
threadShouldThrow();
} catch (InterruptedException e){
threadAssertTrue(added >= 2);
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
q.take();
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* timed offer times out if full and elements not taken
*/
public void testTimedOffer() {
final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.put(new Object());
q.put(new Object());
threadAssertFalse(q.offer(new Object(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
q.offer(new Object(), LONG_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch (InterruptedException success){}
}
});
try {
t.start();
Thread.sleep(SMALL_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* take retrieves elements in FIFO order
*/
public void testTake() {
try {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.take()).intValue());
}
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* take blocks interruptibly when empty
*/
public void testTakeFromEmpty() {
final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.take();
threadShouldThrow();
} catch (InterruptedException success){ }
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* Take removes existing elements until empty, then blocks interruptibly
*/
public void testBlockingTake() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.take()).intValue());
}
q.take();
threadShouldThrow();
} catch (InterruptedException success){
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* poll succeeds unless empty
*/
public void testPoll() {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.poll()).intValue());
}
assertNull(q.poll());
}
/**
* timed poll with zero timeout succeeds when non-empty, else times out
*/
public void testTimedPoll0() {
try {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.poll(0, TimeUnit.MILLISECONDS)).intValue());
}
assertNull(q.poll(0, TimeUnit.MILLISECONDS));
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* timed poll with nonzero timeout succeeds when non-empty, else times out
*/
public void testTimedPoll() {
try {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
}
assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* Interrupted timed poll throws InterruptedException instead of
* returning timeout status
*/
public void testInterruptedTimedPoll() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
threadAssertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
}
threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch (InterruptedException success){
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* timed poll before a delayed offer fails; after offer succeeds;
* on interruption throws
*/
public void testTimedPollWithOffer() {
final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch (InterruptedException success) { }
}
});
try {
t.start();
Thread.sleep(SMALL_DELAY_MS);
assertTrue(q.offer(zero, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* putFirst(null) throws NPE
*/
public void testPutFirstNull() {
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
q.putFirst(null);
shouldThrow();
}
catch (NullPointerException success){
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* all elements successfully putFirst are contained
*/
public void testPutFirst() {
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
Integer I = new Integer(i);
q.putFirst(I);
assertTrue(q.contains(I));
}
assertEquals(0, q.remainingCapacity());
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* putFirst blocks interruptibly if full
*/
public void testBlockingPutFirst() {
Thread t = new Thread(new Runnable() {
public void run() {
int added = 0;
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
q.putFirst(new Integer(i));
++added;
}
q.putFirst(new Integer(SIZE));
threadShouldThrow();
} catch (InterruptedException ie){
threadAssertEquals(added, SIZE);
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* putFirst blocks waiting for take when full
*/
public void testPutFirstWithTake() {
final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
Thread t = new Thread(new Runnable() {
public void run() {
int added = 0;
try {
q.putFirst(new Object());
++added;
q.putFirst(new Object());
++added;
q.putFirst(new Object());
++added;
q.putFirst(new Object());
++added;
threadShouldThrow();
} catch (InterruptedException e){
threadAssertTrue(added >= 2);
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
q.take();
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* timed offerFirst times out if full and elements not taken
*/
public void testTimedOfferFirst() {
final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.putFirst(new Object());
q.putFirst(new Object());
threadAssertFalse(q.offerFirst(new Object(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
q.offerFirst(new Object(), LONG_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch (InterruptedException success){}
}
});
try {
t.start();
Thread.sleep(SMALL_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* take retrieves elements in FIFO order
*/
public void testTakeFirst() {
try {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.takeFirst()).intValue());
}
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* takeFirst blocks interruptibly when empty
*/
public void testTakeFirstFromEmpty() {
final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.takeFirst();
threadShouldThrow();
} catch (InterruptedException success){ }
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* TakeFirst removes existing elements until empty, then blocks interruptibly
*/
public void testBlockingTakeFirst() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.takeFirst()).intValue());
}
q.takeFirst();
threadShouldThrow();
} catch (InterruptedException success){
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* timed pollFirst with zero timeout succeeds when non-empty, else times out
*/
public void testTimedPollFirst0() {
try {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.pollFirst(0, TimeUnit.MILLISECONDS)).intValue());
}
assertNull(q.pollFirst(0, TimeUnit.MILLISECONDS));
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* timed pollFirst with nonzero timeout succeeds when non-empty, else times out
*/
public void testTimedPollFirst() {
try {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.pollFirst(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
}
assertNull(q.pollFirst(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* Interrupted timed pollFirst throws InterruptedException instead of
* returning timeout status
*/
public void testInterruptedTimedPollFirst() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
threadAssertEquals(i, ((Integer)q.pollFirst(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
}
threadAssertNull(q.pollFirst(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch (InterruptedException success){
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* timed pollFirst before a delayed offerFirst fails; after offerFirst succeeds;
* on interruption throws
*/
public void testTimedPollFirstWithOfferFirst() {
final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertNull(q.pollFirst(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
q.pollFirst(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
q.pollFirst(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch (InterruptedException success) { }
}
});
try {
t.start();
Thread.sleep(SMALL_DELAY_MS);
assertTrue(q.offerFirst(zero, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* putLast(null) throws NPE
*/
public void testPutLastNull() {
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
q.putLast(null);
shouldThrow();
}
catch (NullPointerException success){
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* all elements successfully putLast are contained
*/
public void testPutLast() {
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
Integer I = new Integer(i);
q.putLast(I);
assertTrue(q.contains(I));
}
assertEquals(0, q.remainingCapacity());
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* putLast blocks interruptibly if full
*/
public void testBlockingPutLast() {
Thread t = new Thread(new Runnable() {
public void run() {
int added = 0;
try {
LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
q.putLast(new Integer(i));
++added;
}
q.putLast(new Integer(SIZE));
threadShouldThrow();
} catch (InterruptedException ie){
threadAssertEquals(added, SIZE);
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* putLast blocks waiting for take when full
*/
public void testPutLastWithTake() {
final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
Thread t = new Thread(new Runnable() {
public void run() {
int added = 0;
try {
q.putLast(new Object());
++added;
q.putLast(new Object());
++added;
q.putLast(new Object());
++added;
q.putLast(new Object());
++added;
threadShouldThrow();
} catch (InterruptedException e){
threadAssertTrue(added >= 2);
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
q.take();
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* timed offerLast times out if full and elements not taken
*/
public void testTimedOfferLast() {
final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.putLast(new Object());
q.putLast(new Object());
threadAssertFalse(q.offerLast(new Object(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
q.offerLast(new Object(), LONG_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch (InterruptedException success){}
}
});
try {
t.start();
Thread.sleep(SMALL_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* takeLast retrieves elements in FIFO order
*/
public void testTakeLast() {
try {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i-1, ((Integer)q.takeLast()).intValue());
}
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* takeLast blocks interruptibly when empty
*/
public void testTakeLastFromEmpty() {
final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.takeLast();
threadShouldThrow();
} catch (InterruptedException success){ }
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* TakeLast removes existing elements until empty, then blocks interruptibly
*/
public void testBlockingTakeLast() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i-1, ((Integer)q.takeLast()).intValue());
}
q.takeLast();
threadShouldThrow();
} catch (InterruptedException success){
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* timed pollLast with zero timeout succeeds when non-empty, else times out
*/
public void testTimedPollLast0() {
try {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i-1, ((Integer)q.pollLast(0, TimeUnit.MILLISECONDS)).intValue());
}
assertNull(q.pollLast(0, TimeUnit.MILLISECONDS));
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* timed pollLast with nonzero timeout succeeds when non-empty, else times out
*/
public void testTimedPollLast() {
try {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i-1, ((Integer)q.pollLast(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
}
assertNull(q.pollLast(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* Interrupted timed pollLast throws InterruptedException instead of
* returning timeout status
*/
public void testInterruptedTimedPollLast() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
threadAssertEquals(SIZE-i-1, ((Integer)q.pollLast(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
}
threadAssertNull(q.pollLast(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch (InterruptedException success){
}
}});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* timed poll before a delayed offerLast fails; after offerLast succeeds;
* on interruption throws
*/
public void testTimedPollWithOfferLast() {
final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch (InterruptedException success) { }
}
});
try {
t.start();
Thread.sleep(SMALL_DELAY_MS);
assertTrue(q.offerLast(zero, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* element returns next element, or throws NSEE if empty
*/
public void testElement() {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.element()).intValue());
q.poll();
}
try {
q.element();
shouldThrow();
}
catch (NoSuchElementException success) {}
}
/**
* remove(x) removes x and returns true if present
*/
public void testRemoveElement() {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
assertFalse(q.remove(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* contains(x) reports true when elements added but not yet removed
*/
public void testContains() {
LinkedBlockingDeque q = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.contains(new Integer(i)));
q.poll();
assertFalse(q.contains(new Integer(i)));
}
}
/**
* clear removes all elements
*/
public void testClear() {
LinkedBlockingDeque q = populatedDeque(SIZE);
q.clear();
assertTrue(q.isEmpty());
assertEquals(0, q.size());
assertEquals(SIZE, q.remainingCapacity());
q.add(one);
assertFalse(q.isEmpty());
assertTrue(q.contains(one));
q.clear();
assertTrue(q.isEmpty());
}
/**
* containsAll(c) is true when c contains a subset of elements
*/
public void testContainsAll() {
LinkedBlockingDeque q = populatedDeque(SIZE);
LinkedBlockingDeque p = new LinkedBlockingDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.containsAll(p));
assertFalse(p.containsAll(q));
p.add(new Integer(i));
}
assertTrue(p.containsAll(q));
}
/**
* retainAll(c) retains only those elements of c and reports true if changed
*/
public void testRetainAll() {
LinkedBlockingDeque q = populatedDeque(SIZE);
LinkedBlockingDeque p = populatedDeque(SIZE);
for (int i = 0; i < SIZE; ++i) {
boolean changed = q.retainAll(p);
if (i == 0)
assertFalse(changed);
else
assertTrue(changed);
assertTrue(q.containsAll(p));
assertEquals(SIZE-i, q.size());
p.remove();
}
}
/**
* removeAll(c) removes only those elements of c and reports true if changed
*/
public void testRemoveAll() {
for (int i = 1; i < SIZE; ++i) {
LinkedBlockingDeque q = populatedDeque(SIZE);
LinkedBlockingDeque p = populatedDeque(i);
assertTrue(q.removeAll(p));
assertEquals(SIZE-i, q.size());
for (int j = 0; j < i; ++j) {
Integer I = (Integer)(p.remove());
assertFalse(q.contains(I));
}
}
}
/**
* toArray contains all elements
*/
public void testToArray() {
LinkedBlockingDeque q = populatedDeque(SIZE);
Object[] o = q.toArray();
try {
for(int i = 0; i < o.length; i++)
assertEquals(o[i], q.take());
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* toArray(a) contains all elements
*/
public void testToArray2() {
LinkedBlockingDeque q = populatedDeque(SIZE);
Integer[] ints = new Integer[SIZE];
ints = (Integer[])q.toArray(ints);
try {
for(int i = 0; i < ints.length; i++)
assertEquals(ints[i], q.take());
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* toArray(null) throws NPE
*/
public void testToArray_BadArg() {
try {
LinkedBlockingDeque q = populatedDeque(SIZE);
Object o[] = q.toArray(null);
shouldThrow();
} catch(NullPointerException success){}
}
/**
* toArray with incompatible array type throws CCE
*/
public void testToArray1_BadArg() {
try {
LinkedBlockingDeque q = populatedDeque(SIZE);
Object o[] = q.toArray(new String[10] );
shouldThrow();
} catch(ArrayStoreException success){}
}
/**
* iterator iterates through all elements
*/
public void testIterator() {
LinkedBlockingDeque q = populatedDeque(SIZE);
Iterator it = q.iterator();
try {
while(it.hasNext()){
assertEquals(it.next(), q.take());
}
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* iterator.remove removes current element
*/
public void testIteratorRemove () {
final LinkedBlockingDeque q = new LinkedBlockingDeque(3);
q.add(two);
q.add(one);
q.add(three);
Iterator it = q.iterator();
it.next();
it.remove();
it = q.iterator();
assertEquals(it.next(), one);
assertEquals(it.next(), three);
assertFalse(it.hasNext());
}
/**
* iterator ordering is FIFO
*/
public void testIteratorOrdering() {
final LinkedBlockingDeque q = new LinkedBlockingDeque(3);
q.add(one);
q.add(two);
q.add(three);
assertEquals(0, q.remainingCapacity());
int k = 0;
for (Iterator it = q.iterator(); it.hasNext();) {
int i = ((Integer)(it.next())).intValue();
assertEquals(++k, i);
}
assertEquals(3, k);
}
/**
* Modifications do not cause iterators to fail
*/
public void testWeaklyConsistentIteration () {
final LinkedBlockingDeque q = new LinkedBlockingDeque(3);
q.add(one);
q.add(two);
q.add(three);
try {
for (Iterator it = q.iterator(); it.hasNext();) {
q.remove();
it.next();
}
}
catch (ConcurrentModificationException e) {
unexpectedException();
}
assertEquals(0, q.size());
}
/**
* Descending iterator iterates through all elements
*/
public void testDescendingIterator() {
LinkedBlockingDeque q = populatedDeque(SIZE);
int i = 0;
Iterator it = q.descendingIterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, SIZE);
assertFalse(it.hasNext());
try {
it.next();
} catch(NoSuchElementException success) {
}
}
/**
* Descending iterator ordering is reverse FIFO
*/
public void testDescendingIteratorOrdering() {
final LinkedBlockingDeque q = new LinkedBlockingDeque();
for (int iters = 0; iters < 100; ++iters) {
q.add(new Integer(3));
q.add(new Integer(2));
q.add(new Integer(1));
int k = 0;
for (Iterator it = q.descendingIterator(); it.hasNext();) {
int i = ((Integer)(it.next())).intValue();
assertEquals(++k, i);
}
assertEquals(3, k);
q.remove();
q.remove();
q.remove();
}
}
/**
* descendingIterator.remove removes current element
*/
public void testDescendingIteratorRemove () {
final LinkedBlockingDeque q = new LinkedBlockingDeque();
for (int iters = 0; iters < 100; ++iters) {
q.add(new Integer(3));
q.add(new Integer(2));
q.add(new Integer(1));
Iterator it = q.descendingIterator();
assertEquals(it.next(), new Integer(1));
it.remove();
assertEquals(it.next(), new Integer(2));
it = q.descendingIterator();
assertEquals(it.next(), new Integer(2));
assertEquals(it.next(), new Integer(3));
it.remove();
assertFalse(it.hasNext());
q.remove();
}
}
/**
* toString contains toStrings of elements
*/
public void testToString() {
LinkedBlockingDeque q = populatedDeque(SIZE);
String s = q.toString();
for (int i = 0; i < SIZE; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
/**
* offer transfers elements across Executor tasks
*/
public void testOfferInExecutor() {
final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
q.add(one);
q.add(two);
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new Runnable() {
public void run() {
threadAssertFalse(q.offer(three));
try {
threadAssertTrue(q.offer(three, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
threadAssertEquals(0, q.remainingCapacity());
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
executor.execute(new Runnable() {
public void run() {
try {
Thread.sleep(SMALL_DELAY_MS);
threadAssertEquals(one, q.take());
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
joinPool(executor);
}
/**
* poll retrieves elements across Executor threads
*/
public void testPollInExecutor() {
final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new Runnable() {
public void run() {
threadAssertNull(q.poll());
try {
threadAssertTrue(null != q.poll(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
threadAssertTrue(q.isEmpty());
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
executor.execute(new Runnable() {
public void run() {
try {
Thread.sleep(SMALL_DELAY_MS);
q.put(one);
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
joinPool(executor);
}
/**
* A deserialized serialized deque has same elements in same order
*/
public void testSerialization() {
LinkedBlockingDeque q = populatedDeque(SIZE);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
LinkedBlockingDeque r = (LinkedBlockingDeque)in.readObject();
assertEquals(q.size(), r.size());
while (!q.isEmpty())
assertEquals(q.remove(), r.remove());
} catch(Exception e){
unexpectedException();
}
}
/**
* drainTo(null) throws NPE
*/
public void testDrainToNull() {
LinkedBlockingDeque q = populatedDeque(SIZE);
try {
q.drainTo(null);
shouldThrow();
} catch(NullPointerException success) {
}
}
/**
* drainTo(this) throws IAE
*/
public void testDrainToSelf() {
LinkedBlockingDeque q = populatedDeque(SIZE);
try {
q.drainTo(q);
shouldThrow();
} catch(IllegalArgumentException success) {
}
}
/**
* drainTo(c) empties deque into another collection c
*/
public void testDrainTo() {
LinkedBlockingDeque q = populatedDeque(SIZE);
ArrayList l = new ArrayList();
q.drainTo(l);
assertEquals(q.size(), 0);
assertEquals(l.size(), SIZE);
for (int i = 0; i < SIZE; ++i)
assertEquals(l.get(i), new Integer(i));
q.add(zero);
q.add(one);
assertFalse(q.isEmpty());
assertTrue(q.contains(zero));
assertTrue(q.contains(one));
l.clear();
q.drainTo(l);
assertEquals(q.size(), 0);
assertEquals(l.size(), 2);
for (int i = 0; i < 2; ++i)
assertEquals(l.get(i), new Integer(i));
}
/**
* drainTo empties full deque, unblocking a waiting put.
*/
public void testDrainToWithActivePut() {
final LinkedBlockingDeque q = populatedDeque(SIZE);
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.put(new Integer(SIZE+1));
} catch (InterruptedException ie){
threadUnexpectedException();
}
}
});
try {
t.start();
ArrayList l = new ArrayList();
q.drainTo(l);
assertTrue(l.size() >= SIZE);
for (int i = 0; i < SIZE; ++i)
assertEquals(l.get(i), new Integer(i));
t.join();
assertTrue(q.size() + l.size() >= SIZE);
} catch(Exception e){
unexpectedException();
}
}
/**
* drainTo(null, n) throws NPE
*/
public void testDrainToNullN() {
LinkedBlockingDeque q = populatedDeque(SIZE);
try {
q.drainTo(null, 0);
shouldThrow();
} catch(NullPointerException success) {
}
}
/**
* drainTo(this, n) throws IAE
*/
public void testDrainToSelfN() {
LinkedBlockingDeque q = populatedDeque(SIZE);
try {
q.drainTo(q, 0);
shouldThrow();
} catch(IllegalArgumentException success) {
}
}
/**
* drainTo(c, n) empties first max {n, size} elements of deque into c
*/
public void testDrainToN() {
LinkedBlockingDeque q = new LinkedBlockingDeque();
for (int i = 0; i < SIZE + 2; ++i) {
for(int j = 0; j < SIZE; j++)
assertTrue(q.offer(new Integer(j)));
ArrayList l = new ArrayList();
q.drainTo(l, i);
int k = (i < SIZE)? i : SIZE;
assertEquals(l.size(), k);
assertEquals(q.size(), SIZE-k);
for (int j = 0; j < k; ++j)
assertEquals(l.get(j), new Integer(j));
while (q.poll() != null) ;
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/ExchangerTest.java 0000644 0017507 0003772 00000015774 10153210664 023660 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
public class ExchangerTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(ExchangerTest.class);
}
/**
* exchange exchanges objects across two threads
*/
public void testExchange() {
final Exchanger e = new Exchanger();
Thread t1 = new Thread(new Runnable(){
public void run(){
try {
Object v = e.exchange(one);
threadAssertEquals(v, two);
Object w = e.exchange(v);
threadAssertEquals(w, one);
} catch(InterruptedException e){
threadUnexpectedException();
}
}
});
Thread t2 = new Thread(new Runnable(){
public void run(){
try {
Object v = e.exchange(two);
threadAssertEquals(v, one);
Object w = e.exchange(v);
threadAssertEquals(w, two);
} catch(InterruptedException e){
threadUnexpectedException();
}
}
});
try {
t1.start();
t2.start();
t1.join();
t2.join();
} catch(InterruptedException ex) {
unexpectedException();
}
}
/**
* timed exchange exchanges objects across two threads
*/
public void testTimedExchange() {
final Exchanger e = new Exchanger();
Thread t1 = new Thread(new Runnable(){
public void run(){
try {
Object v = e.exchange(one, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
threadAssertEquals(v, two);
Object w = e.exchange(v, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
threadAssertEquals(w, one);
} catch(InterruptedException e){
threadUnexpectedException();
} catch(TimeoutException toe) {
threadUnexpectedException();
}
}
});
Thread t2 = new Thread(new Runnable(){
public void run(){
try {
Object v = e.exchange(two, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
threadAssertEquals(v, one);
Object w = e.exchange(v, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
threadAssertEquals(w, two);
} catch(InterruptedException e){
threadUnexpectedException();
} catch(TimeoutException toe) {
threadUnexpectedException();
}
}
});
try {
t1.start();
t2.start();
t1.join();
t2.join();
} catch(InterruptedException ex) {
unexpectedException();
}
}
/**
* interrupt during wait for exchange throws IE
*/
public void testExchange_InterruptedException(){
final Exchanger e = new Exchanger();
Thread t = new Thread(new Runnable() {
public void run(){
try {
e.exchange(one);
threadShouldThrow();
} catch(InterruptedException success){
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch(InterruptedException ex) {
unexpectedException();
}
}
/**
* interrupt during wait for timed exchange throws IE
*/
public void testTimedExchange_InterruptedException(){
final Exchanger e = new Exchanger();
Thread t = new Thread(new Runnable() {
public void run(){
try {
e.exchange(null, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch(InterruptedException success){
} catch(Exception e2){
threadFail("should throw IE");
}
}
});
try {
t.start();
t.interrupt();
t.join();
} catch(InterruptedException ex){
unexpectedException();
}
}
/**
* timeout during wait for timed exchange throws TOE
*/
public void testExchange_TimeOutException(){
final Exchanger e = new Exchanger();
Thread t = new Thread(new Runnable() {
public void run(){
try {
e.exchange(null, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch(TimeoutException success){
} catch(InterruptedException e2){
threadFail("should throw TOE");
}
}
});
try {
t.start();
t.join();
} catch(InterruptedException ex){
unexpectedException();
}
}
/**
* If one exchanging thread is interrupted, another succeeds.
*/
public void testReplacementAfterExchange() {
final Exchanger e = new Exchanger();
Thread t1 = new Thread(new Runnable(){
public void run(){
try {
Object v = e.exchange(one);
threadAssertEquals(v, two);
Object w = e.exchange(v);
threadShouldThrow();
} catch(InterruptedException success){
}
}
});
Thread t2 = new Thread(new Runnable(){
public void run(){
try {
Object v = e.exchange(two);
threadAssertEquals(v, one);
Thread.sleep(SMALL_DELAY_MS);
Object w = e.exchange(v);
threadAssertEquals(w, three);
} catch(InterruptedException e){
threadUnexpectedException();
}
}
});
Thread t3 = new Thread(new Runnable(){
public void run(){
try {
Thread.sleep(SMALL_DELAY_MS);
Object w = e.exchange(three);
threadAssertEquals(w, one);
} catch(InterruptedException e){
threadUnexpectedException();
}
}
});
try {
t1.start();
t2.start();
t3.start();
Thread.sleep(SHORT_DELAY_MS);
t1.interrupt();
t1.join();
t2.join();
t3.join();
} catch(InterruptedException ex) {
unexpectedException();
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/AtomicStampedReferenceTest.java 0000644 0017507 0003772 00000011621 10153210664 026310 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
public class AtomicStampedReferenceTest extends JSR166TestCase{
public static void main (String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(AtomicStampedReferenceTest.class);
}
/**
* constructor initializes to given reference and stamp
*/
public void testConstructor(){
AtomicStampedReference ai = new AtomicStampedReference(one, 0);
assertEquals(one,ai.getReference());
assertEquals(0, ai.getStamp());
AtomicStampedReference a2 = new AtomicStampedReference(null, 1);
assertNull(a2.getReference());
assertEquals(1, a2.getStamp());
}
/**
* get returns the last values of reference and stamp set
*/
public void testGetSet(){
int[] mark = new int[1];
AtomicStampedReference ai = new AtomicStampedReference(one, 0);
assertEquals(one,ai.getReference());
assertEquals(0, ai.getStamp());
assertEquals(one, ai.get(mark));
assertEquals(0, mark[0]);
ai.set(two, 0);
assertEquals(two,ai.getReference());
assertEquals(0, ai.getStamp());
assertEquals(two, ai.get(mark));
assertEquals(0, mark[0]);
ai.set(one, 1);
assertEquals(one,ai.getReference());
assertEquals(1, ai.getStamp());
assertEquals(one, ai.get(mark));
assertEquals(1,mark[0]);
}
/**
* attemptStamp succeeds in single thread
*/
public void testAttemptStamp(){
int[] mark = new int[1];
AtomicStampedReference ai = new AtomicStampedReference(one, 0);
assertEquals(0, ai.getStamp());
assertTrue(ai.attemptStamp(one, 1));
assertEquals(1, ai.getStamp());
assertEquals(one, ai.get(mark));
assertEquals(1, mark[0]);
}
/**
* compareAndSet succeeds in changing values if equal to expected reference
* and stamp else fails
*/
public void testCompareAndSet(){
int[] mark = new int[1];
AtomicStampedReference ai = new AtomicStampedReference(one, 0);
assertEquals(one, ai.get(mark));
assertEquals(0, ai.getStamp());
assertEquals(0, mark[0]);
assertTrue(ai.compareAndSet(one, two, 0, 0));
assertEquals(two, ai.get(mark));
assertEquals(0, mark[0]);
assertTrue(ai.compareAndSet(two, m3, 0, 1));
assertEquals(m3, ai.get(mark));
assertEquals(1, mark[0]);
assertFalse(ai.compareAndSet(two, m3, 1, 1));
assertEquals(m3, ai.get(mark));
assertEquals(1, mark[0]);
}
/**
* compareAndSet in one thread enables another waiting for reference value
* to succeed
*/
public void testCompareAndSetInMultipleThreads() {
final AtomicStampedReference ai = new AtomicStampedReference(one, 0);
Thread t = new Thread(new Runnable() {
public void run() {
while(!ai.compareAndSet(two, three, 0, 0)) Thread.yield();
}});
try {
t.start();
assertTrue(ai.compareAndSet(one, two, 0, 0));
t.join(LONG_DELAY_MS);
assertFalse(t.isAlive());
assertEquals(ai.getReference(), three);
assertEquals(ai.getStamp(), 0);
}
catch(Exception e) {
unexpectedException();
}
}
/**
* compareAndSet in one thread enables another waiting for stamp value
* to succeed
*/
public void testCompareAndSetInMultipleThreads2() {
final AtomicStampedReference ai = new AtomicStampedReference(one, 0);
Thread t = new Thread(new Runnable() {
public void run() {
while(!ai.compareAndSet(one, one, 1, 2)) Thread.yield();
}});
try {
t.start();
assertTrue(ai.compareAndSet(one, one, 0, 1));
t.join(LONG_DELAY_MS);
assertFalse(t.isAlive());
assertEquals(ai.getReference(), one);
assertEquals(ai.getStamp(), 2);
}
catch(Exception e) {
unexpectedException();
}
}
/**
* repeated weakCompareAndSet succeeds in changing values when equal
* to expected
*/
public void testWeakCompareAndSet(){
int[] mark = new int[1];
AtomicStampedReference ai = new AtomicStampedReference(one, 0);
assertEquals(one, ai.get(mark));
assertEquals(0, ai.getStamp ());
assertEquals(0, mark[0]);
while(!ai.weakCompareAndSet(one, two, 0, 0));
assertEquals(two, ai.get(mark));
assertEquals(0, mark[0]);
while(!ai.weakCompareAndSet(two, m3, 0, 1));
assertEquals(m3, ai.get(mark));
assertEquals(1, mark[0]);
}
}
backport-util-concurrent-3.1-src/test/tck/src/CyclicBarrierTest.java 0000644 0017507 0003772 00000051271 10253674160 024467 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
public class CyclicBarrierTest extends JSR166TestCase{
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(CyclicBarrierTest.class);
}
private volatile int countAction;
private class MyAction implements Runnable {
public void run() { ++countAction; }
}
/**
* Creating with negative parties throws IAE
*/
public void testConstructor1() {
try {
new CyclicBarrier(-1, (Runnable)null);
shouldThrow();
} catch(IllegalArgumentException e){}
}
/**
* Creating with negative parties and no action throws IAE
*/
public void testConstructor2() {
try {
new CyclicBarrier(-1);
shouldThrow();
} catch(IllegalArgumentException e){}
}
/**
* getParties returns the number of parties given in constructor
*/
public void testGetParties() {
CyclicBarrier b = new CyclicBarrier(2);
assertEquals(2, b.getParties());
assertEquals(0, b.getNumberWaiting());
}
/**
* A 1-party barrier triggers after single await
*/
public void testSingleParty() {
try {
CyclicBarrier b = new CyclicBarrier(1);
assertEquals(1, b.getParties());
assertEquals(0, b.getNumberWaiting());
b.await();
b.await();
assertEquals(0, b.getNumberWaiting());
}
catch(Exception e) {
unexpectedException();
}
}
/**
* The supplied barrier action is run at barrier
*/
public void testBarrierAction() {
try {
countAction = 0;
CyclicBarrier b = new CyclicBarrier(1, new MyAction());
assertEquals(1, b.getParties());
assertEquals(0, b.getNumberWaiting());
b.await();
b.await();
assertEquals(0, b.getNumberWaiting());
assertEquals(countAction, 2);
}
catch(Exception e) {
unexpectedException();
}
}
/**
* A 2-party/thread barrier triggers after both threads invoke await
*/
public void testTwoParties() {
final CyclicBarrier b = new CyclicBarrier(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
b.await();
b.await();
b.await();
b.await();
} catch(Exception e){
threadUnexpectedException();
}}});
try {
t.start();
b.await();
b.await();
b.await();
b.await();
t.join();
} catch(Exception e){
unexpectedException();
}
}
/**
* An interruption in one party causes others waiting in await to
* throw BrokenBarrierException
*/
public void testAwait1_Interrupted_BrokenBarrier() {
final CyclicBarrier c = new CyclicBarrier(3);
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
c.await();
threadShouldThrow();
} catch(InterruptedException success){}
catch(Exception b){
threadUnexpectedException();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
c.await();
threadShouldThrow();
} catch(BrokenBarrierException success){
} catch(Exception i){
threadUnexpectedException();
}
}
});
try {
t1.start();
t2.start();
Thread.sleep(SHORT_DELAY_MS);
t1.interrupt();
t1.join();
t2.join();
} catch(InterruptedException e){
unexpectedException();
}
}
/**
* An interruption in one party causes others waiting in timed await to
* throw BrokenBarrierException
*/
public void testAwait2_Interrupted_BrokenBarrier() {
final CyclicBarrier c = new CyclicBarrier(3);
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
c.await(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch(InterruptedException success){
} catch(Exception b){
threadUnexpectedException();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
c.await(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch(BrokenBarrierException success){
} catch(Exception i){
threadUnexpectedException();
}
}
});
try {
t1.start();
t2.start();
Thread.sleep(SHORT_DELAY_MS);
t1.interrupt();
t1.join();
t2.join();
} catch(InterruptedException e){
unexpectedException();
}
}
/**
* A timeout in timed await throws TimeoutException
*/
public void testAwait3_TimeOutException() {
final CyclicBarrier c = new CyclicBarrier(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
c.await(SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch(TimeoutException success){
} catch(Exception b){
threadUnexpectedException();
}
}
});
try {
t.start();
t.join();
} catch(InterruptedException e){
unexpectedException();
}
}
/**
* A timeout in one party causes others waiting in timed await to
* throw BrokenBarrierException
*/
public void testAwait4_Timeout_BrokenBarrier() {
final CyclicBarrier c = new CyclicBarrier(3);
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
c.await(SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch(TimeoutException success){
} catch(Exception b){
threadUnexpectedException();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
c.await(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch(BrokenBarrierException success){
} catch(Exception i){
threadUnexpectedException();
}
}
});
try {
t1.start();
t2.start();
t1.join();
t2.join();
} catch(InterruptedException e){
unexpectedException();
}
}
/**
* A timeout in one party causes others waiting in await to
* throw BrokenBarrierException
*/
public void testAwait5_Timeout_BrokenBarrier() {
final CyclicBarrier c = new CyclicBarrier(3);
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
c.await(SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch(TimeoutException success){
} catch(Exception b){
threadUnexpectedException();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
c.await();
threadShouldThrow();
} catch(BrokenBarrierException success){
} catch(Exception i){
threadUnexpectedException();
}
}
});
try {
t1.start();
t2.start();
t1.join();
t2.join();
} catch(InterruptedException e){
unexpectedException();
}
}
/**
* A reset of an active barrier causes waiting threads to throw
* BrokenBarrierException
*/
public void testReset_BrokenBarrier() {
final CyclicBarrier c = new CyclicBarrier(3);
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
c.await();
threadShouldThrow();
} catch(BrokenBarrierException success){}
catch(Exception b){
threadUnexpectedException();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
c.await();
threadShouldThrow();
} catch(BrokenBarrierException success){
} catch(Exception i){
threadUnexpectedException();
}
}
});
try {
t1.start();
t2.start();
Thread.sleep(SHORT_DELAY_MS);
c.reset();
t1.join();
t2.join();
} catch(InterruptedException e){
unexpectedException();
}
}
/**
* A reset before threads enter barrier does not throw
* BrokenBarrierException
*/
public void testReset_NoBrokenBarrier() {
final CyclicBarrier c = new CyclicBarrier(3);
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
c.await();
} catch(Exception b){
threadUnexpectedException();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
c.await();
} catch(Exception i){
threadUnexpectedException();
}
}
});
try {
c.reset();
t1.start();
t2.start();
c.await();
t1.join();
t2.join();
} catch(Exception e){
unexpectedException();
}
}
/**
* All threads block while a barrier is broken.
*/
public void testReset_Leakage() {
try {
final CyclicBarrier c = new CyclicBarrier(2);
final AtomicBoolean done = new AtomicBoolean();
Thread t = new Thread() {
public void run() {
while (!done.get()) {
try {
while (c.isBroken())
c.reset();
c.await();
threadFail("await should not return");
}
catch (BrokenBarrierException e) {
}
catch (InterruptedException ie) {
}
}
}
};
t.start();
for( int i = 0; i < 4; i++) {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
}
done.set(true);
t.interrupt();
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* Reset of a non-broken barrier does not break barrier
*/
public void testResetWithoutBreakage() {
try {
final CyclicBarrier start = new CyclicBarrier(3);
final CyclicBarrier barrier = new CyclicBarrier(3);
for (int i = 0; i < 3; i++) {
Thread t1 = new Thread(new Runnable() {
public void run() {
try { start.await(); }
catch (Exception ie) {
threadFail("start barrier");
}
try { barrier.await(); }
catch (Throwable thrown) {
unexpectedException();
}}});
Thread t2 = new Thread(new Runnable() {
public void run() {
try { start.await(); }
catch (Exception ie) {
threadFail("start barrier");
}
try { barrier.await(); }
catch (Throwable thrown) {
unexpectedException();
}}});
t1.start();
t2.start();
try { start.await(); }
catch (Exception ie) { threadFail("start barrier"); }
barrier.await();
t1.join();
t2.join();
assertFalse(barrier.isBroken());
assertEquals(0, barrier.getNumberWaiting());
if (i == 1) barrier.reset();
assertFalse(barrier.isBroken());
assertEquals(0, barrier.getNumberWaiting());
}
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* Reset of a barrier after interruption reinitializes it.
*/
public void testResetAfterInterrupt() {
try {
final CyclicBarrier start = new CyclicBarrier(3);
final CyclicBarrier barrier = new CyclicBarrier(3);
for (int i = 0; i < 2; i++) {
Thread t1 = new Thread(new Runnable() {
public void run() {
try { start.await(); }
catch (Exception ie) {
threadFail("start barrier");
}
try { barrier.await(); }
catch(InterruptedException ok) {}
catch (Throwable thrown) {
unexpectedException();
}}});
Thread t2 = new Thread(new Runnable() {
public void run() {
try { start.await(); }
catch (Exception ie) {
threadFail("start barrier");
}
try { barrier.await(); }
catch(BrokenBarrierException ok) {}
catch (Throwable thrown) {
unexpectedException();
}}});
t1.start();
t2.start();
try { start.await(); }
catch (Exception ie) { threadFail("start barrier"); }
t1.interrupt();
t1.join();
t2.join();
assertTrue(barrier.isBroken());
assertEquals(0, barrier.getNumberWaiting());
barrier.reset();
assertFalse(barrier.isBroken());
assertEquals(0, barrier.getNumberWaiting());
}
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* Reset of a barrier after timeout reinitializes it.
*/
public void testResetAfterTimeout() {
try {
final CyclicBarrier start = new CyclicBarrier(3);
final CyclicBarrier barrier = new CyclicBarrier(3);
for (int i = 0; i < 2; i++) {
Thread t1 = new Thread(new Runnable() {
public void run() {
try { start.await(); }
catch (Exception ie) {
threadFail("start barrier");
}
try { barrier.await(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS); }
catch(TimeoutException ok) {}
catch (Throwable thrown) {
unexpectedException();
}}});
Thread t2 = new Thread(new Runnable() {
public void run() {
try { start.await(); }
catch (Exception ie) {
threadFail("start barrier");
}
try { barrier.await(); }
catch(BrokenBarrierException ok) {}
catch (Throwable thrown) {
unexpectedException();
}}});
t1.start();
t2.start();
try { start.await(); }
catch (Exception ie) { threadFail("start barrier"); }
t1.join();
t2.join();
assertTrue(barrier.isBroken());
assertEquals(0, barrier.getNumberWaiting());
barrier.reset();
assertFalse(barrier.isBroken());
assertEquals(0, barrier.getNumberWaiting());
}
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* Reset of a barrier after a failed command reinitializes it.
*/
public void testResetAfterCommandException() {
try {
final CyclicBarrier start = new CyclicBarrier(3);
final CyclicBarrier barrier =
new CyclicBarrier(3, new Runnable() {
public void run() {
throw new NullPointerException(); }});
for (int i = 0; i < 2; i++) {
Thread t1 = new Thread(new Runnable() {
public void run() {
try { start.await(); }
catch (Exception ie) {
threadFail("start barrier");
}
try { barrier.await(); }
catch(BrokenBarrierException ok) {}
catch (Throwable thrown) {
unexpectedException();
}}});
Thread t2 = new Thread(new Runnable() {
public void run() {
try { start.await(); }
catch (Exception ie) {
threadFail("start barrier");
}
try { barrier.await(); }
catch(BrokenBarrierException ok) {}
catch (Throwable thrown) {
unexpectedException();
}}});
t1.start();
t2.start();
try { start.await(); }
catch (Exception ie) { threadFail("start barrier"); }
while (barrier.getNumberWaiting() < 2) { Thread.yield(); }
try { barrier.await(); }
catch (Exception ok) { }
t1.join();
t2.join();
assertTrue(barrier.isBroken());
assertEquals(0, barrier.getNumberWaiting());
barrier.reset();
assertFalse(barrier.isBroken());
assertEquals(0, barrier.getNumberWaiting());
}
}
catch (Exception ex) {
unexpectedException();
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/CopyOnWriteArrayListTest.java 0000644 0017507 0003772 00000044050 10256105160 026014 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.io.*;
import java.util.Arrays;
import java.util.Vector;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.List;
public class CopyOnWriteArrayListTest extends JSR166TestCase{
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(CopyOnWriteArrayListTest.class);
}
static CopyOnWriteArrayList populatedArray(int n){
CopyOnWriteArrayList a = new CopyOnWriteArrayList();
assertTrue(a.isEmpty());
for (int i = 0; i < n; ++i)
a.add(new Integer(i));
assertFalse(a.isEmpty());
assertEquals(n, a.size());
return a;
}
/**
* a new list is empty
*/
public void testConstructor() {
CopyOnWriteArrayList a = new CopyOnWriteArrayList();
assertTrue(a.isEmpty());
}
/**
* new list contains all elements of initializing array
*/
public void testConstructor2() {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
CopyOnWriteArrayList a = new CopyOnWriteArrayList(ints);
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], a.get(i));
}
/**
* new list contains all elements of initializing collection
*/
public void testConstructor3() {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
CopyOnWriteArrayList a = new CopyOnWriteArrayList(Arrays.asList(ints));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], a.get(i));
}
/**
* addAll adds each element from the given collection
*/
public void testAddAll() {
CopyOnWriteArrayList full = populatedArray(3);
Vector v = new Vector();
v.add(three);
v.add(four);
v.add(five);
full.addAll(v);
assertEquals(6, full.size());
}
/**
* addAllAbsent adds each element from the given collection that did not
* already exist in the List
*/
public void testAddAllAbsent() {
CopyOnWriteArrayList full = populatedArray(3);
Vector v = new Vector();
v.add(three);
v.add(four);
v.add(one); // will not add this element
full.addAllAbsent(v);
assertEquals(5, full.size());
}
/**
* addIfAbsent will not add the element if it already exists in the list
*/
public void testAddIfAbsent() {
CopyOnWriteArrayList full = populatedArray(SIZE);
full.addIfAbsent(one);
assertEquals(SIZE, full.size());
}
/**
* addIfAbsent adds the element when it does not exist in the list
*/
public void testAddIfAbsent2() {
CopyOnWriteArrayList full = populatedArray(SIZE);
full.addIfAbsent(three);
assertTrue(full.contains(three));
}
/**
* clear removes all elements from the list
*/
public void testClear() {
CopyOnWriteArrayList full = populatedArray(SIZE);
full.clear();
assertEquals(0, full.size());
}
/**
* Cloned list is equal
*/
public void testClone() {
CopyOnWriteArrayList l1 = populatedArray(SIZE);
CopyOnWriteArrayList l2 = (CopyOnWriteArrayList)(l1.clone());
assertEquals(l1, l2);
l1.clear();
assertFalse(l1.equals(l2));
}
/**
* contains is true for added elements
*/
public void testContains() {
CopyOnWriteArrayList full = populatedArray(3);
assertTrue(full.contains(one));
assertFalse(full.contains(five));
}
/**
* adding at an index places it in the indicated index
*/
public void testAddIndex() {
CopyOnWriteArrayList full = populatedArray(3);
full.add(0, m1);
assertEquals(4, full.size());
assertEquals(m1, full.get(0));
assertEquals(zero, full.get(1));
full.add(2, m2);
assertEquals(5, full.size());
assertEquals(m2, full.get(2));
assertEquals(two, full.get(4));
}
/**
* lists with same elements are equal and have same hashCode
*/
public void testEquals() {
CopyOnWriteArrayList a = populatedArray(3);
CopyOnWriteArrayList b = populatedArray(3);
assertTrue(a.equals(b));
assertTrue(b.equals(a));
assertEquals(a.hashCode(), b.hashCode());
a.add(m1);
assertFalse(a.equals(b));
assertFalse(b.equals(a));
b.add(m1);
assertTrue(a.equals(b));
assertTrue(b.equals(a));
assertEquals(a.hashCode(), b.hashCode());
}
/**
* containsAll returns true for collection with subset of elements
*/
public void testContainsAll() {
CopyOnWriteArrayList full = populatedArray(3);
Vector v = new Vector();
v.add(one);
v.add(two);
assertTrue(full.containsAll(v));
v.add(six);
assertFalse(full.containsAll(v));
}
/**
* get returns the value at the given index
*/
public void testGet() {
CopyOnWriteArrayList full = populatedArray(3);
assertEquals(0, ((Integer)full.get(0)).intValue());
}
/**
* indexOf gives the index for the given object
*/
public void testIndexOf() {
CopyOnWriteArrayList full = populatedArray(3);
assertEquals(1, full.indexOf(one));
assertEquals(-1, full.indexOf("puppies"));
}
/**
* indexOf gives the index based on the given index
* at which to start searching
*/
public void testIndexOf2() {
CopyOnWriteArrayList full = populatedArray(3);
assertEquals(1, full.indexOf(one, 0));
assertEquals(-1, full.indexOf(one, 2));
}
/**
* isEmpty returns true when empty, else false
*/
public void testIsEmpty() {
CopyOnWriteArrayList empty = new CopyOnWriteArrayList();
CopyOnWriteArrayList full = populatedArray(SIZE);
assertTrue(empty.isEmpty());
assertFalse(full.isEmpty());
}
/**
* iterator() returns an iterator containing the elements of the list
*/
public void testIterator() {
CopyOnWriteArrayList full = populatedArray(SIZE);
Iterator i = full.iterator();
int j;
for(j = 0; i.hasNext(); j++)
assertEquals(j, ((Integer)i.next()).intValue());
assertEquals(SIZE, j);
}
/**
* iterator.remove throws UnsupportedOperationException
*/
public void testIteratorRemove () {
CopyOnWriteArrayList full = populatedArray(SIZE);
Iterator it = full.iterator();
it.next();
try {
it.remove();
shouldThrow();
}
catch (UnsupportedOperationException success) {}
}
/**
* toString contains toString of elements
*/
public void testToString() {
CopyOnWriteArrayList full = populatedArray(3);
String s = full.toString();
for (int i = 0; i < 3; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
/**
* lastIndexOf returns the index for the given object
*/
public void testLastIndexOf1() {
CopyOnWriteArrayList full = populatedArray(3);
full.add(one);
full.add(three);
assertEquals(3, full.lastIndexOf(one));
assertEquals(-1, full.lastIndexOf(six));
}
/**
* lastIndexOf returns the index from the given starting point
*/
public void testlastIndexOf2() {
CopyOnWriteArrayList full = populatedArray(3);
full.add(one);
full.add(three);
assertEquals(3, full.lastIndexOf(one, 4));
assertEquals(-1, full.lastIndexOf(three, 3));
}
/**
* listIterator traverses all elements
*/
public void testListIterator1() {
CopyOnWriteArrayList full = populatedArray(SIZE);
ListIterator i = full.listIterator();
int j;
for(j = 0; i.hasNext(); j++)
assertEquals(j, ((Integer)i.next()).intValue());
assertEquals(SIZE, j);
}
/**
* listIterator only returns those elements after the given index
*/
public void testListIterator2() {
CopyOnWriteArrayList full = populatedArray(3);
ListIterator i = full.listIterator(1);
int j;
for(j = 0; i.hasNext(); j++)
assertEquals(j+1, ((Integer)i.next()).intValue());
assertEquals(2, j);
}
/**
* remove removes and returns the object at the given index
*/
public void testRemove() {
CopyOnWriteArrayList full = populatedArray(3);
assertEquals(two, full.remove(2));
assertEquals(2, full.size());
}
/**
* removeAll removes all elements from the given collection
*/
public void testRemoveAll() {
CopyOnWriteArrayList full = populatedArray(3);
Vector v = new Vector();
v.add(one);
v.add(two);
full.removeAll(v);
assertEquals(1, full.size());
}
/**
* set changes the element at the given index
*/
public void testSet() {
CopyOnWriteArrayList full = populatedArray(3);
assertEquals(two, full.set(2, four));
assertEquals(4, ((Integer)full.get(2)).intValue());
}
/**
* size returns the number of elements
*/
public void testSize() {
CopyOnWriteArrayList empty = new CopyOnWriteArrayList();
CopyOnWriteArrayList full = populatedArray(SIZE);
assertEquals(SIZE, full.size());
assertEquals(0, empty.size());
}
/**
* toArray returns an Object array containing all elements from the list
*/
public void testToArray() {
CopyOnWriteArrayList full = populatedArray(3);
Object[] o = full.toArray();
assertEquals(3, o.length);
assertEquals(0, ((Integer)o[0]).intValue());
assertEquals(1, ((Integer)o[1]).intValue());
assertEquals(2, ((Integer)o[2]).intValue());
}
/**
* toArray returns an Integer array containing all elements from
* the list
*/
public void testToArray2() {
CopyOnWriteArrayList full = populatedArray(3);
Integer[] i = new Integer[3];
i = (Integer[])full.toArray(i);
assertEquals(3, i.length);
assertEquals(0, i[0].intValue());
assertEquals(1, i[1].intValue());
assertEquals(2, i[2].intValue());
}
/**
* sublists contains elements at indexes offset from their base
*/
public void testSubList() {
CopyOnWriteArrayList a = populatedArray(10);
assertTrue(a.subList(1,1).isEmpty());
for(int j = 0; j < 9; ++j) {
for(int i = j ; i < 10; ++i) {
List b = a.subList(j,i);
for(int k = j; k < i; ++k) {
assertEquals(new Integer(k), b.get(k-j));
}
}
}
List s = a.subList(2, 5);
assertEquals(s.size(), 3);
s.set(2, m1);
assertEquals(a.get(4), m1);
s.clear();
assertEquals(a.size(), 7);
}
// Exception tests
/**
* toArray throws an ArrayStoreException when the given array
* can not store the objects inside the list
*/
public void testToArray_ArrayStoreException() {
try {
CopyOnWriteArrayList c = new CopyOnWriteArrayList();
c.add("zfasdfsdf");
c.add("asdadasd");
c.toArray(new Long[5]);
shouldThrow();
} catch(ArrayStoreException e){}
}
/**
* get throws an IndexOutOfBoundsException on a negative index
*/
public void testGet1_IndexOutOfBoundsException() {
try {
CopyOnWriteArrayList c = new CopyOnWriteArrayList();
c.get(-1);
shouldThrow();
} catch(IndexOutOfBoundsException e){}
}
/**
* get throws an IndexOutOfBoundsException on a too high index
*/
public void testGet2_IndexOutOfBoundsException() {
try {
CopyOnWriteArrayList c = new CopyOnWriteArrayList();
c.add("asdasd");
c.add("asdad");
c.get(100);
shouldThrow();
} catch(IndexOutOfBoundsException e){}
}
/**
* set throws an IndexOutOfBoundsException on a negative index
*/
public void testSet1_IndexOutOfBoundsException() {
try {
CopyOnWriteArrayList c = new CopyOnWriteArrayList();
c.set(-1,"qwerty");
shouldThrow();
} catch(IndexOutOfBoundsException e){}
}
/**
* set throws an IndexOutOfBoundsException on a too high index
*/
public void testSet2() {
try {
CopyOnWriteArrayList c = new CopyOnWriteArrayList();
c.add("asdasd");
c.add("asdad");
c.set(100, "qwerty");
shouldThrow();
} catch(IndexOutOfBoundsException e){}
}
/**
* add throws an IndexOutOfBoundsException on a negative index
*/
public void testAdd1_IndexOutOfBoundsException() {
try {
CopyOnWriteArrayList c = new CopyOnWriteArrayList();
c.add(-1,"qwerty");
shouldThrow();
} catch(IndexOutOfBoundsException e){}
}
/**
* add throws an IndexOutOfBoundsException on a too high index
*/
public void testAdd2_IndexOutOfBoundsException() {
try {
CopyOnWriteArrayList c = new CopyOnWriteArrayList();
c.add("asdasd");
c.add("asdasdasd");
c.add(100, "qwerty");
shouldThrow();
} catch(IndexOutOfBoundsException e){}
}
/**
* remove throws an IndexOutOfBoundsException on a negative index
*/
public void testRemove1_IndexOutOfBounds() {
try {
CopyOnWriteArrayList c = new CopyOnWriteArrayList();
c.remove(-1);
shouldThrow();
} catch(IndexOutOfBoundsException e){}
}
/**
* remove throws an IndexOutOfBoundsException on a too high index
*/
public void testRemove2_IndexOutOfBounds() {
try {
CopyOnWriteArrayList c = new CopyOnWriteArrayList();
c.add("asdasd");
c.add("adasdasd");
c.remove(100);
shouldThrow();
} catch(IndexOutOfBoundsException e){}
}
/**
* addAll throws an IndexOutOfBoundsException on a negative index
*/
public void testAddAll1_IndexOutOfBoundsException() {
try {
CopyOnWriteArrayList c = new CopyOnWriteArrayList();
c.addAll(-1,new LinkedList());
shouldThrow();
} catch(IndexOutOfBoundsException e){}
}
/**
* addAll throws an IndexOutOfBoundsException on a too high index
*/
public void testAddAll2_IndexOutOfBoundsException() {
try {
CopyOnWriteArrayList c = new CopyOnWriteArrayList();
c.add("asdasd");
c.add("asdasdasd");
c.addAll(100, new LinkedList());
shouldThrow();
} catch(IndexOutOfBoundsException e){}
}
/**
* listIterator throws an IndexOutOfBoundsException on a negative index
*/
public void testListIterator1_IndexOutOfBoundsException() {
try {
CopyOnWriteArrayList c = new CopyOnWriteArrayList();
c.listIterator(-1);
shouldThrow();
} catch(IndexOutOfBoundsException e){}
}
/**
* listIterator throws an IndexOutOfBoundsException on a too high index
*/
public void testListIterator2_IndexOutOfBoundsException() {
try {
CopyOnWriteArrayList c = new CopyOnWriteArrayList();
c.add("adasd");
c.add("asdasdas");
c.listIterator(100);
shouldThrow();
} catch(IndexOutOfBoundsException e){}
}
/**
* subList throws an IndexOutOfBoundsException on a negative index
*/
public void testSubList1_IndexOutOfBoundsException() {
try {
CopyOnWriteArrayList c = new CopyOnWriteArrayList();
c.subList(-1,100);
shouldThrow();
} catch(IndexOutOfBoundsException e){}
}
/**
* subList throws an IndexOutOfBoundsException on a too high index
*/
public void testSubList2_IndexOutOfBoundsException() {
try {
CopyOnWriteArrayList c = new CopyOnWriteArrayList();
c.add("asdasd");
c.subList(1,100);
shouldThrow();
} catch(IndexOutOfBoundsException e){}
}
/**
* subList throws IndexOutOfBoundsException when the second index
* is lower then the first
*/
public void testSubList3_IndexOutOfBoundsException() {
try {
CopyOnWriteArrayList c = new CopyOnWriteArrayList();
c.subList(3,1);
shouldThrow();
} catch(IndexOutOfBoundsException e){}
}
/**
* a deserialized serialiszed list is equal
*/
public void testSerialization() {
CopyOnWriteArrayList q = populatedArray(SIZE);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
CopyOnWriteArrayList r = (CopyOnWriteArrayList)in.readObject();
assertEquals(q.size(), r.size());
assertTrue(q.equals(r));
assertTrue(r.equals(q));
} catch(Exception e){
unexpectedException();
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/ScheduledExecutorSubclassTest.java 0000755 0017507 0003772 00000111620 10431260156 027061 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import junit.framework.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
public class ScheduledExecutorSubclassTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(ScheduledExecutorTest.class);
}
static class CustomTask implements RunnableScheduledFuture {
RunnableScheduledFuture task;
volatile boolean ran;
CustomTask(RunnableScheduledFuture t) { task = t; }
public boolean isPeriodic() { return task.isPeriodic(); }
public void run() {
ran = true;
task.run();
}
public long getDelay(TimeUnit unit) { return task.getDelay(unit); }
public int compareTo(Object o) {
return compareTo((Delayed)o);
}
public int compareTo(Delayed t) {
return task.compareTo(((CustomTask)t).task);
}
public boolean cancel(boolean mayInterruptIfRunning) {
return task.cancel(mayInterruptIfRunning);
}
public boolean isCancelled() { return task.isCancelled(); }
public boolean isDone() { return task.isDone(); }
public Object get() throws InterruptedException, ExecutionException {
Object v = task.get();
assertTrue(ran);
return v;
}
public Object get(long time, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
Object v = task.get(time, unit);
assertTrue(ran);
return v;
}
}
public class CustomExecutor extends ScheduledThreadPoolExecutor {
protected RunnableScheduledFuture decorateTask(Runnable r, RunnableScheduledFuture task) {
return new CustomTask(task);
}
protected RunnableScheduledFuture decorateTask(Callable c, RunnableScheduledFuture task) {
return new CustomTask(task);
}
CustomExecutor(int corePoolSize) { super(corePoolSize);}
CustomExecutor(int corePoolSize, RejectedExecutionHandler handler) {
super(corePoolSize, handler);
}
CustomExecutor(int corePoolSize, ThreadFactory threadFactory) {
super(corePoolSize, threadFactory);
}
CustomExecutor(int corePoolSize, ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
super(corePoolSize, threadFactory, handler);
}
}
/**
* execute successfully executes a runnable
*/
public void testExecute() {
try {
TrackedShortRunnable runnable =new TrackedShortRunnable();
CustomExecutor p1 = new CustomExecutor(1);
p1.execute(runnable);
assertFalse(runnable.done);
Thread.sleep(SHORT_DELAY_MS);
try { p1.shutdown(); } catch(SecurityException ok) { return; }
try {
Thread.sleep(MEDIUM_DELAY_MS);
} catch(InterruptedException e){
unexpectedException();
}
assertTrue(runnable.done);
try { p1.shutdown(); } catch(SecurityException ok) { return; }
joinPool(p1);
}
catch(Exception e){
unexpectedException();
}
}
/**
* delayed schedule of callable successfully executes after delay
*/
public void testSchedule1() {
try {
TrackedCallable callable = new TrackedCallable();
CustomExecutor p1 = new CustomExecutor(1);
Future f = p1.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
assertFalse(callable.done);
Thread.sleep(MEDIUM_DELAY_MS);
assertTrue(callable.done);
assertEquals(Boolean.TRUE, f.get());
try { p1.shutdown(); } catch(SecurityException ok) { return; }
joinPool(p1);
} catch(RejectedExecutionException e){}
catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* delayed schedule of runnable successfully executes after delay
*/
public void testSchedule3() {
try {
TrackedShortRunnable runnable = new TrackedShortRunnable();
CustomExecutor p1 = new CustomExecutor(1);
p1.schedule(runnable, SMALL_DELAY_MS, TimeUnit.MILLISECONDS);
Thread.sleep(SHORT_DELAY_MS);
assertFalse(runnable.done);
Thread.sleep(MEDIUM_DELAY_MS);
assertTrue(runnable.done);
try { p1.shutdown(); } catch(SecurityException ok) { return; }
joinPool(p1);
} catch(Exception e){
unexpectedException();
}
}
/**
* scheduleAtFixedRate executes runnable after given initial delay
*/
public void testSchedule4() {
try {
TrackedShortRunnable runnable = new TrackedShortRunnable();
CustomExecutor p1 = new CustomExecutor(1);
ScheduledFuture h = p1.scheduleAtFixedRate(runnable, SHORT_DELAY_MS, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
assertFalse(runnable.done);
Thread.sleep(MEDIUM_DELAY_MS);
assertTrue(runnable.done);
h.cancel(true);
joinPool(p1);
} catch(Exception e){
unexpectedException();
}
}
static class RunnableCounter implements Runnable {
AtomicInteger count = new AtomicInteger(0);
public void run() { count.getAndIncrement(); }
}
/**
* scheduleWithFixedDelay executes runnable after given initial delay
*/
public void testSchedule5() {
try {
TrackedShortRunnable runnable = new TrackedShortRunnable();
CustomExecutor p1 = new CustomExecutor(1);
ScheduledFuture h = p1.scheduleWithFixedDelay(runnable, SHORT_DELAY_MS, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
assertFalse(runnable.done);
Thread.sleep(MEDIUM_DELAY_MS);
assertTrue(runnable.done);
h.cancel(true);
joinPool(p1);
} catch(Exception e){
unexpectedException();
}
}
/**
* scheduleAtFixedRate executes series of tasks at given rate
*/
public void testFixedRateSequence() {
try {
CustomExecutor p1 = new CustomExecutor(1);
RunnableCounter counter = new RunnableCounter();
ScheduledFuture h =
p1.scheduleAtFixedRate(counter, 0, 1, TimeUnit.MILLISECONDS);
Thread.sleep(SMALL_DELAY_MS);
h.cancel(true);
int c = counter.count.get();
// By time scaling conventions, we must have at least
// an execution per SHORT delay, but no more than one SHORT more
assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
joinPool(p1);
} catch(Exception e){
unexpectedException();
}
}
/**
* scheduleWithFixedDelay executes series of tasks with given period
*/
public void testFixedDelaySequence() {
try {
CustomExecutor p1 = new CustomExecutor(1);
RunnableCounter counter = new RunnableCounter();
ScheduledFuture h =
p1.scheduleWithFixedDelay(counter, 0, 1, TimeUnit.MILLISECONDS);
Thread.sleep(SMALL_DELAY_MS);
h.cancel(true);
int c = counter.count.get();
assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
joinPool(p1);
} catch(Exception e){
unexpectedException();
}
}
/**
* execute (null) throws NPE
*/
public void testExecuteNull() {
CustomExecutor se = null;
try {
se = new CustomExecutor(1);
se.execute(null);
shouldThrow();
} catch(NullPointerException success){}
catch(Exception e){
unexpectedException();
}
joinPool(se);
}
/**
* schedule (null) throws NPE
*/
public void testScheduleNull() {
CustomExecutor se = new CustomExecutor(1);
try {
TrackedCallable callable = null;
Future f = se.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
shouldThrow();
} catch(NullPointerException success){}
catch(Exception e){
unexpectedException();
}
joinPool(se);
}
/**
* execute throws RejectedExecutionException if shutdown
*/
public void testSchedule1_RejectedExecutionException() {
CustomExecutor se = new CustomExecutor(1);
try {
se.shutdown();
se.schedule(new NoOpRunnable(),
MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
shouldThrow();
} catch(RejectedExecutionException success){
} catch (SecurityException ok) {
}
joinPool(se);
}
/**
* schedule throws RejectedExecutionException if shutdown
*/
public void testSchedule2_RejectedExecutionException() {
CustomExecutor se = new CustomExecutor(1);
try {
se.shutdown();
se.schedule(new NoOpCallable(),
MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
shouldThrow();
} catch(RejectedExecutionException success){
} catch (SecurityException ok) {
}
joinPool(se);
}
/**
* schedule callable throws RejectedExecutionException if shutdown
*/
public void testSchedule3_RejectedExecutionException() {
CustomExecutor se = new CustomExecutor(1);
try {
se.shutdown();
se.schedule(new NoOpCallable(),
MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
shouldThrow();
} catch(RejectedExecutionException success){
} catch (SecurityException ok) {
}
joinPool(se);
}
/**
* scheduleAtFixedRate throws RejectedExecutionException if shutdown
*/
public void testScheduleAtFixedRate1_RejectedExecutionException() {
CustomExecutor se = new CustomExecutor(1);
try {
se.shutdown();
se.scheduleAtFixedRate(new NoOpRunnable(),
MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
shouldThrow();
} catch(RejectedExecutionException success){
} catch (SecurityException ok) {
}
joinPool(se);
}
/**
* scheduleWithFixedDelay throws RejectedExecutionException if shutdown
*/
public void testScheduleWithFixedDelay1_RejectedExecutionException() {
CustomExecutor se = new CustomExecutor(1);
try {
se.shutdown();
se.scheduleWithFixedDelay(new NoOpRunnable(),
MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
shouldThrow();
} catch(RejectedExecutionException success){
} catch (SecurityException ok) {
}
joinPool(se);
}
/**
* getActiveCount increases but doesn't overestimate, when a
* thread becomes active
*/
public void testGetActiveCount() {
CustomExecutor p2 = new CustomExecutor(2);
assertEquals(0, p2.getActiveCount());
p2.execute(new SmallRunnable());
try {
Thread.sleep(SHORT_DELAY_MS);
} catch(Exception e){
unexpectedException();
}
assertEquals(1, p2.getActiveCount());
joinPool(p2);
}
/**
* getCompletedTaskCount increases, but doesn't overestimate,
* when tasks complete
*/
public void testGetCompletedTaskCount() {
CustomExecutor p2 = new CustomExecutor(2);
assertEquals(0, p2.getCompletedTaskCount());
p2.execute(new SmallRunnable());
try {
Thread.sleep(MEDIUM_DELAY_MS);
} catch(Exception e){
unexpectedException();
}
assertEquals(1, p2.getCompletedTaskCount());
joinPool(p2);
}
/**
* getCorePoolSize returns size given in constructor if not otherwise set
*/
public void testGetCorePoolSize() {
CustomExecutor p1 = new CustomExecutor(1);
assertEquals(1, p1.getCorePoolSize());
joinPool(p1);
}
/**
* getLargestPoolSize increases, but doesn't overestimate, when
* multiple threads active
*/
public void testGetLargestPoolSize() {
CustomExecutor p2 = new CustomExecutor(2);
assertEquals(0, p2.getLargestPoolSize());
p2.execute(new SmallRunnable());
p2.execute(new SmallRunnable());
try {
Thread.sleep(SHORT_DELAY_MS);
} catch(Exception e){
unexpectedException();
}
assertEquals(2, p2.getLargestPoolSize());
joinPool(p2);
}
/**
* getPoolSize increases, but doesn't overestimate, when threads
* become active
*/
public void testGetPoolSize() {
CustomExecutor p1 = new CustomExecutor(1);
assertEquals(0, p1.getPoolSize());
p1.execute(new SmallRunnable());
assertEquals(1, p1.getPoolSize());
joinPool(p1);
}
/**
* getTaskCount increases, but doesn't overestimate, when tasks
* submitted
*/
public void testGetTaskCount() {
CustomExecutor p1 = new CustomExecutor(1);
assertEquals(0, p1.getTaskCount());
for(int i = 0; i < 5; i++)
p1.execute(new SmallRunnable());
try {
Thread.sleep(SHORT_DELAY_MS);
} catch(Exception e){
unexpectedException();
}
assertEquals(5, p1.getTaskCount());
joinPool(p1);
}
/**
* getThreadFactory returns factory in constructor if not set
*/
public void testGetThreadFactory() {
ThreadFactory tf = new SimpleThreadFactory();
CustomExecutor p = new CustomExecutor(1, tf);
assertSame(tf, p.getThreadFactory());
joinPool(p);
}
/**
* setThreadFactory sets the thread factory returned by getThreadFactory
*/
public void testSetThreadFactory() {
ThreadFactory tf = new SimpleThreadFactory();
CustomExecutor p = new CustomExecutor(1);
p.setThreadFactory(tf);
assertSame(tf, p.getThreadFactory());
joinPool(p);
}
/**
* setThreadFactory(null) throws NPE
*/
public void testSetThreadFactoryNull() {
CustomExecutor p = new CustomExecutor(1);
try {
p.setThreadFactory(null);
shouldThrow();
} catch (NullPointerException success) {
} finally {
joinPool(p);
}
}
/**
* is isShutDown is false before shutdown, true after
*/
public void testIsShutdown() {
CustomExecutor p1 = new CustomExecutor(1);
try {
assertFalse(p1.isShutdown());
}
finally {
try { p1.shutdown(); } catch(SecurityException ok) { return; }
}
assertTrue(p1.isShutdown());
}
/**
* isTerminated is false before termination, true after
*/
public void testIsTerminated() {
CustomExecutor p1 = new CustomExecutor(1);
try {
p1.execute(new SmallRunnable());
} finally {
try { p1.shutdown(); } catch(SecurityException ok) { return; }
}
try {
assertTrue(p1.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
assertTrue(p1.isTerminated());
} catch(Exception e){
unexpectedException();
}
}
/**
* isTerminating is not true when running or when terminated
*/
public void testIsTerminating() {
CustomExecutor p1 = new CustomExecutor(1);
assertFalse(p1.isTerminating());
try {
p1.execute(new SmallRunnable());
assertFalse(p1.isTerminating());
} finally {
try { p1.shutdown(); } catch(SecurityException ok) { return; }
}
try {
assertTrue(p1.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
assertTrue(p1.isTerminated());
assertFalse(p1.isTerminating());
} catch(Exception e){
unexpectedException();
}
}
/**
* getQueue returns the work queue, which contains queued tasks
*/
public void testGetQueue() {
CustomExecutor p1 = new CustomExecutor(1);
ScheduledFuture[] tasks = new ScheduledFuture[5];
for(int i = 0; i < 5; i++){
tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, TimeUnit.MILLISECONDS);
}
try {
Thread.sleep(SHORT_DELAY_MS);
BlockingQueue q = p1.getQueue();
assertTrue(q.contains(tasks[4]));
assertFalse(q.contains(tasks[0]));
} catch(Exception e) {
unexpectedException();
} finally {
joinPool(p1);
}
}
/**
* remove(task) removes queued task, and fails to remove active task
*/
public void testRemove() {
CustomExecutor p1 = new CustomExecutor(1);
ScheduledFuture[] tasks = new ScheduledFuture[5];
for(int i = 0; i < 5; i++){
tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, TimeUnit.MILLISECONDS);
}
try {
Thread.sleep(SHORT_DELAY_MS);
BlockingQueue q = p1.getQueue();
assertFalse(p1.remove((Runnable)tasks[0]));
assertTrue(q.contains((Runnable)tasks[4]));
assertTrue(q.contains((Runnable)tasks[3]));
assertTrue(p1.remove((Runnable)tasks[4]));
assertFalse(p1.remove((Runnable)tasks[4]));
assertFalse(q.contains((Runnable)tasks[4]));
assertTrue(q.contains((Runnable)tasks[3]));
assertTrue(p1.remove((Runnable)tasks[3]));
assertFalse(q.contains((Runnable)tasks[3]));
} catch(Exception e) {
unexpectedException();
} finally {
joinPool(p1);
}
}
/**
* purge removes cancelled tasks from the queue
*/
public void testPurge() {
CustomExecutor p1 = new CustomExecutor(1);
ScheduledFuture[] tasks = new ScheduledFuture[5];
for(int i = 0; i < 5; i++){
tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
}
try {
int max = 5;
if (tasks[4].cancel(true)) --max;
if (tasks[3].cancel(true)) --max;
// There must eventually be an interference-free point at
// which purge will not fail. (At worst, when queue is empty.)
int k;
for (k = 0; k < SMALL_DELAY_MS; ++k) {
p1.purge();
long count = p1.getTaskCount();
if (count >= 0 && count <= max)
break;
Thread.sleep(1);
}
assertTrue(k < SMALL_DELAY_MS);
} catch(Exception e) {
unexpectedException();
} finally {
joinPool(p1);
}
}
/**
* shutDownNow returns a list containing tasks that were not run
*/
public void testShutDownNow() {
CustomExecutor p1 = new CustomExecutor(1);
for(int i = 0; i < 5; i++)
p1.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
List l;
try {
l = p1.shutdownNow();
} catch (SecurityException ok) {
return;
}
assertTrue(p1.isShutdown());
assertTrue(l.size() > 0 && l.size() <= 5);
joinPool(p1);
}
/**
* In default setting, shutdown cancels periodic but not delayed
* tasks at shutdown
*/
public void testShutDown1() {
try {
CustomExecutor p1 = new CustomExecutor(1);
assertTrue(p1.getExecuteExistingDelayedTasksAfterShutdownPolicy());
assertFalse(p1.getContinueExistingPeriodicTasksAfterShutdownPolicy());
ScheduledFuture[] tasks = new ScheduledFuture[5];
for(int i = 0; i < 5; i++)
tasks[i] = p1.schedule(new NoOpRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
try { p1.shutdown(); } catch(SecurityException ok) { return; }
BlockingQueue q = p1.getQueue();
for (Iterator it = q.iterator(); it.hasNext();) {
ScheduledFuture t = (ScheduledFuture)it.next();
assertFalse(t.isCancelled());
}
assertTrue(p1.isShutdown());
Thread.sleep(SMALL_DELAY_MS);
for (int i = 0; i < 5; ++i) {
assertTrue(tasks[i].isDone());
assertFalse(tasks[i].isCancelled());
}
}
catch(Exception ex) {
unexpectedException();
}
}
/**
* If setExecuteExistingDelayedTasksAfterShutdownPolicy is false,
* delayed tasks are cancelled at shutdown
*/
public void testShutDown2() {
try {
CustomExecutor p1 = new CustomExecutor(1);
p1.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
ScheduledFuture[] tasks = new ScheduledFuture[5];
for(int i = 0; i < 5; i++)
tasks[i] = p1.schedule(new NoOpRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
try { p1.shutdown(); } catch(SecurityException ok) { return; }
assertTrue(p1.isShutdown());
BlockingQueue q = p1.getQueue();
assertTrue(q.isEmpty());
Thread.sleep(SMALL_DELAY_MS);
assertTrue(p1.isTerminated());
}
catch(Exception ex) {
unexpectedException();
}
}
/**
* If setContinueExistingPeriodicTasksAfterShutdownPolicy is set false,
* periodic tasks are not cancelled at shutdown
*/
public void testShutDown3() {
try {
CustomExecutor p1 = new CustomExecutor(1);
p1.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
ScheduledFuture task =
p1.scheduleAtFixedRate(new NoOpRunnable(), 5, 5, TimeUnit.MILLISECONDS);
try { p1.shutdown(); } catch(SecurityException ok) { return; }
assertTrue(p1.isShutdown());
BlockingQueue q = p1.getQueue();
assertTrue(q.isEmpty());
Thread.sleep(SHORT_DELAY_MS);
assertTrue(p1.isTerminated());
}
catch(Exception ex) {
unexpectedException();
}
}
/**
* if setContinueExistingPeriodicTasksAfterShutdownPolicy is true,
* periodic tasks are cancelled at shutdown
*/
public void testShutDown4() {
CustomExecutor p1 = new CustomExecutor(1);
try {
p1.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
ScheduledFuture task =
p1.scheduleAtFixedRate(new NoOpRunnable(), 1, 1, TimeUnit.MILLISECONDS);
assertFalse(task.isCancelled());
try { p1.shutdown(); } catch(SecurityException ok) { return; }
assertFalse(task.isCancelled());
assertFalse(p1.isTerminated());
assertTrue(p1.isShutdown());
Thread.sleep(SHORT_DELAY_MS);
assertFalse(task.isCancelled());
assertTrue(task.cancel(true));
assertTrue(task.isDone());
Thread.sleep(SHORT_DELAY_MS);
assertTrue(p1.isTerminated());
}
catch(Exception ex) {
unexpectedException();
}
finally {
joinPool(p1);
}
}
/**
* completed submit of callable returns result
*/
public void testSubmitCallable() {
ExecutorService e = new CustomExecutor(2);
try {
Future future = e.submit(new StringTask());
String result = (String)future.get();
assertSame(TEST_STRING, result);
}
catch (ExecutionException ex) {
unexpectedException();
}
catch (InterruptedException ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* completed submit of runnable returns successfully
*/
public void testSubmitRunnable() {
ExecutorService e = new CustomExecutor(2);
try {
Future future = e.submit(new NoOpRunnable());
future.get();
assertTrue(future.isDone());
}
catch (ExecutionException ex) {
unexpectedException();
}
catch (InterruptedException ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* completed submit of (runnable, result) returns result
*/
public void testSubmitRunnable2() {
ExecutorService e = new CustomExecutor(2);
try {
Future future = e.submit(new NoOpRunnable(), TEST_STRING);
String result = (String)future.get();
assertSame(TEST_STRING, result);
}
catch (ExecutionException ex) {
unexpectedException();
}
catch (InterruptedException ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(null) throws NPE
*/
public void testInvokeAny1() {
ExecutorService e = new CustomExecutor(2);
try {
e.invokeAny(null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(empty collection) throws IAE
*/
public void testInvokeAny2() {
ExecutorService e = new CustomExecutor(2);
try {
e.invokeAny(new ArrayList());
} catch (IllegalArgumentException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(c) throws NPE if c has null elements
*/
public void testInvokeAny3() {
ExecutorService e = new CustomExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAny(l);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(c) throws ExecutionException if no task completes
*/
public void testInvokeAny4() {
ExecutorService e = new CustomExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
e.invokeAny(l);
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(c) returns result of some task
*/
public void testInvokeAny5() {
ExecutorService e = new CustomExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
String result = (String)e.invokeAny(l);
assertSame(TEST_STRING, result);
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(null) throws NPE
*/
public void testInvokeAll1() {
ExecutorService e = new CustomExecutor(2);
try {
e.invokeAll(null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(empty collection) returns empty collection
*/
public void testInvokeAll2() {
ExecutorService e = new CustomExecutor(2);
try {
List r = e.invokeAll(new ArrayList());
assertTrue(r.isEmpty());
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(c) throws NPE if c has null elements
*/
public void testInvokeAll3() {
ExecutorService e = new CustomExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAll(l);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* get of invokeAll(c) throws exception on failed task
*/
public void testInvokeAll4() {
ExecutorService e = new CustomExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
List result = e.invokeAll(l);
assertEquals(1, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
((Future)it.next()).get();
} catch(ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(c) returns results of all completed tasks
*/
public void testInvokeAll5() {
ExecutorService e = new CustomExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
List result = e.invokeAll(l);
assertEquals(2, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
assertSame(TEST_STRING, ((Future)it.next()).get());
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(null) throws NPE
*/
public void testTimedInvokeAny1() {
ExecutorService e = new CustomExecutor(2);
try {
e.invokeAny(null, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(,,null) throws NPE
*/
public void testTimedInvokeAnyNullTimeUnit() {
ExecutorService e = new CustomExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
e.invokeAny(l, MEDIUM_DELAY_MS, null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(empty collection) throws IAE
*/
public void testTimedInvokeAny2() {
ExecutorService e = new CustomExecutor(2);
try {
e.invokeAny(new ArrayList(), MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (IllegalArgumentException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(c) throws NPE if c has null elements
*/
public void testTimedInvokeAny3() {
ExecutorService e = new CustomExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
ex.printStackTrace();
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(c) throws ExecutionException if no task completes
*/
public void testTimedInvokeAny4() {
ExecutorService e = new CustomExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch(ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(c) returns result of some task
*/
public void testTimedInvokeAny5() {
ExecutorService e = new CustomExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
String result = (String)e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertSame(TEST_STRING, result);
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(null) throws NPE
*/
public void testTimedInvokeAll1() {
ExecutorService e = new CustomExecutor(2);
try {
e.invokeAll(null, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(,,null) throws NPE
*/
public void testTimedInvokeAllNullTimeUnit() {
ExecutorService e = new CustomExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
e.invokeAll(l, MEDIUM_DELAY_MS, null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(empty collection) returns empty collection
*/
public void testTimedInvokeAll2() {
ExecutorService e = new CustomExecutor(2);
try {
List r = e.invokeAll(new ArrayList(), MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertTrue(r.isEmpty());
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(c) throws NPE if c has null elements
*/
public void testTimedInvokeAll3() {
ExecutorService e = new CustomExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* get of element of invokeAll(c) throws exception on failed task
*/
public void testTimedInvokeAll4() {
ExecutorService e = new CustomExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
List result = e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertEquals(1, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
((Future)it.next()).get();
} catch(ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(c) returns results of all completed tasks
*/
public void testTimedInvokeAll5() {
ExecutorService e = new CustomExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
List result = e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertEquals(2, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
assertSame(TEST_STRING, ((Future)it.next()).get());
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(c) cancels tasks not completed by timeout
*/
public void testTimedInvokeAll6() {
ExecutorService e = new CustomExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
l.add(new StringTask());
List result = e.invokeAll(l, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
assertEquals(3, result.size());
Iterator it = result.iterator();
Future f1 = (Future)it.next();
Future f2 = (Future)it.next();
Future f3 = (Future)it.next();
assertTrue(f1.isDone());
assertTrue(f2.isDone());
assertTrue(f3.isDone());
assertFalse(f1.isCancelled());
assertTrue(f2.isCancelled());
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/ScheduledExecutorTest.java 0000644 0017507 0003772 00000110115 10431260156 025354 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class ScheduledExecutorTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(ScheduledExecutorTest.class);
}
/**
* execute successfully executes a runnable
*/
public void testExecute() {
try {
TrackedShortRunnable runnable =new TrackedShortRunnable();
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
p1.execute(runnable);
assertFalse(runnable.done);
Thread.sleep(SHORT_DELAY_MS);
try { p1.shutdown(); } catch(SecurityException ok) { return; }
try {
Thread.sleep(MEDIUM_DELAY_MS);
} catch(InterruptedException e){
unexpectedException();
}
assertTrue(runnable.done);
try { p1.shutdown(); } catch(SecurityException ok) { return; }
joinPool(p1);
}
catch(Exception e){
unexpectedException();
}
}
/**
* delayed schedule of callable successfully executes after delay
*/
public void testSchedule1() {
try {
TrackedCallable callable = new TrackedCallable();
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
Future f = p1.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
assertFalse(callable.done);
Thread.sleep(MEDIUM_DELAY_MS);
assertTrue(callable.done);
assertEquals(Boolean.TRUE, f.get());
try { p1.shutdown(); } catch(SecurityException ok) { return; }
joinPool(p1);
} catch(RejectedExecutionException e){}
catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* delayed schedule of runnable successfully executes after delay
*/
public void testSchedule3() {
try {
TrackedShortRunnable runnable = new TrackedShortRunnable();
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
p1.schedule(runnable, SMALL_DELAY_MS, TimeUnit.MILLISECONDS);
Thread.sleep(SHORT_DELAY_MS);
assertFalse(runnable.done);
Thread.sleep(MEDIUM_DELAY_MS);
assertTrue(runnable.done);
try { p1.shutdown(); } catch(SecurityException ok) { return; }
joinPool(p1);
} catch(Exception e){
unexpectedException();
}
}
/**
* scheduleAtFixedRate executes runnable after given initial delay
*/
public void testSchedule4() {
try {
TrackedShortRunnable runnable = new TrackedShortRunnable();
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
ScheduledFuture h = p1.scheduleAtFixedRate(runnable, SHORT_DELAY_MS, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
assertFalse(runnable.done);
Thread.sleep(MEDIUM_DELAY_MS);
assertTrue(runnable.done);
h.cancel(true);
joinPool(p1);
} catch(Exception e){
unexpectedException();
}
}
static class RunnableCounter implements Runnable {
AtomicInteger count = new AtomicInteger(0);
public void run() { count.getAndIncrement(); }
}
/**
* scheduleWithFixedDelay executes runnable after given initial delay
*/
public void testSchedule5() {
try {
TrackedShortRunnable runnable = new TrackedShortRunnable();
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
ScheduledFuture h = p1.scheduleWithFixedDelay(runnable, SHORT_DELAY_MS, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
assertFalse(runnable.done);
Thread.sleep(MEDIUM_DELAY_MS);
assertTrue(runnable.done);
h.cancel(true);
joinPool(p1);
} catch(Exception e){
unexpectedException();
}
}
/**
* scheduleAtFixedRate executes series of tasks at given rate
*/
public void testFixedRateSequence() {
try {
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
RunnableCounter counter = new RunnableCounter();
ScheduledFuture h =
p1.scheduleAtFixedRate(counter, 0, 1, TimeUnit.MILLISECONDS);
Thread.sleep(SMALL_DELAY_MS);
h.cancel(true);
int c = counter.count.get();
// By time scaling conventions, we must have at least
// an execution per SHORT delay, but no more than one SHORT more
assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
joinPool(p1);
} catch(Exception e){
unexpectedException();
}
}
/**
* scheduleWithFixedDelay executes series of tasks with given period
*/
public void testFixedDelaySequence() {
try {
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
RunnableCounter counter = new RunnableCounter();
ScheduledFuture h =
p1.scheduleWithFixedDelay(counter, 0, 1, TimeUnit.MILLISECONDS);
Thread.sleep(SMALL_DELAY_MS);
h.cancel(true);
int c = counter.count.get();
assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
joinPool(p1);
} catch(Exception e){
unexpectedException();
}
}
/**
* execute (null) throws NPE
*/
public void testExecuteNull() {
ScheduledThreadPoolExecutor se = null;
try {
se = new ScheduledThreadPoolExecutor(1);
se.execute(null);
shouldThrow();
} catch(NullPointerException success){}
catch(Exception e){
unexpectedException();
}
joinPool(se);
}
/**
* schedule (null) throws NPE
*/
public void testScheduleNull() {
ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
try {
TrackedCallable callable = null;
Future f = se.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
shouldThrow();
} catch(NullPointerException success){}
catch(Exception e){
unexpectedException();
}
joinPool(se);
}
/**
* execute throws RejectedExecutionException if shutdown
*/
public void testSchedule1_RejectedExecutionException() {
ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
try {
se.shutdown();
se.schedule(new NoOpRunnable(),
MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
shouldThrow();
} catch(RejectedExecutionException success){
} catch (SecurityException ok) {
}
joinPool(se);
}
/**
* schedule throws RejectedExecutionException if shutdown
*/
public void testSchedule2_RejectedExecutionException() {
ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
try {
se.shutdown();
se.schedule(new NoOpCallable(),
MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
shouldThrow();
} catch(RejectedExecutionException success){
} catch (SecurityException ok) {
}
joinPool(se);
}
/**
* schedule callable throws RejectedExecutionException if shutdown
*/
public void testSchedule3_RejectedExecutionException() {
ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
try {
se.shutdown();
se.schedule(new NoOpCallable(),
MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
shouldThrow();
} catch(RejectedExecutionException success){
} catch (SecurityException ok) {
}
joinPool(se);
}
/**
* scheduleAtFixedRate throws RejectedExecutionException if shutdown
*/
public void testScheduleAtFixedRate1_RejectedExecutionException() {
ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
try {
se.shutdown();
se.scheduleAtFixedRate(new NoOpRunnable(),
MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
shouldThrow();
} catch(RejectedExecutionException success){
} catch (SecurityException ok) {
}
joinPool(se);
}
/**
* scheduleWithFixedDelay throws RejectedExecutionException if shutdown
*/
public void testScheduleWithFixedDelay1_RejectedExecutionException() {
ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
try {
se.shutdown();
se.scheduleWithFixedDelay(new NoOpRunnable(),
MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
shouldThrow();
} catch(RejectedExecutionException success){
} catch (SecurityException ok) {
}
joinPool(se);
}
/**
* getActiveCount increases but doesn't overestimate, when a
* thread becomes active
*/
public void testGetActiveCount() {
ScheduledThreadPoolExecutor p2 = new ScheduledThreadPoolExecutor(2);
assertEquals(0, p2.getActiveCount());
p2.execute(new SmallRunnable());
try {
Thread.sleep(SHORT_DELAY_MS);
} catch(Exception e){
unexpectedException();
}
assertEquals(1, p2.getActiveCount());
joinPool(p2);
}
/**
* getCompletedTaskCount increases, but doesn't overestimate,
* when tasks complete
*/
public void testGetCompletedTaskCount() {
ScheduledThreadPoolExecutor p2 = new ScheduledThreadPoolExecutor(2);
assertEquals(0, p2.getCompletedTaskCount());
p2.execute(new SmallRunnable());
try {
Thread.sleep(MEDIUM_DELAY_MS);
} catch(Exception e){
unexpectedException();
}
assertEquals(1, p2.getCompletedTaskCount());
joinPool(p2);
}
/**
* getCorePoolSize returns size given in constructor if not otherwise set
*/
public void testGetCorePoolSize() {
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
assertEquals(1, p1.getCorePoolSize());
joinPool(p1);
}
/**
* getLargestPoolSize increases, but doesn't overestimate, when
* multiple threads active
*/
public void testGetLargestPoolSize() {
ScheduledThreadPoolExecutor p2 = new ScheduledThreadPoolExecutor(2);
assertEquals(0, p2.getLargestPoolSize());
p2.execute(new SmallRunnable());
p2.execute(new SmallRunnable());
try {
Thread.sleep(SHORT_DELAY_MS);
} catch(Exception e){
unexpectedException();
}
assertEquals(2, p2.getLargestPoolSize());
joinPool(p2);
}
/**
* getPoolSize increases, but doesn't overestimate, when threads
* become active
*/
public void testGetPoolSize() {
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
assertEquals(0, p1.getPoolSize());
p1.execute(new SmallRunnable());
assertEquals(1, p1.getPoolSize());
joinPool(p1);
}
/**
* getTaskCount increases, but doesn't overestimate, when tasks
* submitted
*/
public void testGetTaskCount() {
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
assertEquals(0, p1.getTaskCount());
for(int i = 0; i < 5; i++)
p1.execute(new SmallRunnable());
try {
Thread.sleep(SHORT_DELAY_MS);
} catch(Exception e){
unexpectedException();
}
assertEquals(5, p1.getTaskCount());
joinPool(p1);
}
/**
* getThreadFactory returns factory in constructor if not set
*/
public void testGetThreadFactory() {
ThreadFactory tf = new SimpleThreadFactory();
ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1, tf);
assertSame(tf, p.getThreadFactory());
joinPool(p);
}
/**
* setThreadFactory sets the thread factory returned by getThreadFactory
*/
public void testSetThreadFactory() {
ThreadFactory tf = new SimpleThreadFactory();
ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
p.setThreadFactory(tf);
assertSame(tf, p.getThreadFactory());
joinPool(p);
}
/**
* setThreadFactory(null) throws NPE
*/
public void testSetThreadFactoryNull() {
ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
try {
p.setThreadFactory(null);
shouldThrow();
} catch (NullPointerException success) {
} finally {
joinPool(p);
}
}
/**
* is isShutDown is false before shutdown, true after
*/
public void testIsShutdown() {
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
try {
assertFalse(p1.isShutdown());
}
finally {
try { p1.shutdown(); } catch(SecurityException ok) { return; }
}
assertTrue(p1.isShutdown());
}
/**
* isTerminated is false before termination, true after
*/
public void testIsTerminated() {
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
try {
p1.execute(new SmallRunnable());
} finally {
try { p1.shutdown(); } catch(SecurityException ok) { return; }
}
try {
assertTrue(p1.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
assertTrue(p1.isTerminated());
} catch(Exception e){
unexpectedException();
}
}
/**
* isTerminating is not true when running or when terminated
*/
public void testIsTerminating() {
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
assertFalse(p1.isTerminating());
try {
p1.execute(new SmallRunnable());
assertFalse(p1.isTerminating());
} finally {
try { p1.shutdown(); } catch(SecurityException ok) { return; }
}
try {
assertTrue(p1.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
assertTrue(p1.isTerminated());
assertFalse(p1.isTerminating());
} catch(Exception e){
unexpectedException();
}
}
/**
* getQueue returns the work queue, which contains queued tasks
*/
public void testGetQueue() {
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
ScheduledFuture[] tasks = new ScheduledFuture[5];
for(int i = 0; i < 5; i++){
tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, TimeUnit.MILLISECONDS);
}
try {
Thread.sleep(SHORT_DELAY_MS);
BlockingQueue q = p1.getQueue();
assertTrue(q.contains(tasks[4]));
assertFalse(q.contains(tasks[0]));
} catch(Exception e) {
unexpectedException();
} finally {
joinPool(p1);
}
}
/**
* remove(task) removes queued task, and fails to remove active task
*/
public void testRemove() {
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
ScheduledFuture[] tasks = new ScheduledFuture[5];
for(int i = 0; i < 5; i++){
tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, TimeUnit.MILLISECONDS);
}
try {
Thread.sleep(SHORT_DELAY_MS);
BlockingQueue q = p1.getQueue();
assertFalse(p1.remove((Runnable)tasks[0]));
assertTrue(q.contains((Runnable)tasks[4]));
assertTrue(q.contains((Runnable)tasks[3]));
assertTrue(p1.remove((Runnable)tasks[4]));
assertFalse(p1.remove((Runnable)tasks[4]));
assertFalse(q.contains((Runnable)tasks[4]));
assertTrue(q.contains((Runnable)tasks[3]));
assertTrue(p1.remove((Runnable)tasks[3]));
assertFalse(q.contains((Runnable)tasks[3]));
} catch(Exception e) {
unexpectedException();
} finally {
joinPool(p1);
}
}
/**
* purge removes cancelled tasks from the queue
*/
public void testPurge() {
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
ScheduledFuture[] tasks = new ScheduledFuture[5];
for(int i = 0; i < 5; i++){
tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
}
try {
int max = 5;
if (tasks[4].cancel(true)) --max;
if (tasks[3].cancel(true)) --max;
// There must eventually be an interference-free point at
// which purge will not fail. (At worst, when queue is empty.)
int k;
for (k = 0; k < SMALL_DELAY_MS; ++k) {
p1.purge();
long count = p1.getTaskCount();
if (count >= 0 && count <= max)
break;
Thread.sleep(1);
}
assertTrue(k < SMALL_DELAY_MS);
} catch(Exception e) {
unexpectedException();
} finally {
joinPool(p1);
}
}
/**
* shutDownNow returns a list containing tasks that were not run
*/
public void testShutDownNow() {
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
for(int i = 0; i < 5; i++)
p1.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
List l;
try {
l = p1.shutdownNow();
} catch (SecurityException ok) {
return;
}
assertTrue(p1.isShutdown());
assertTrue(l.size() > 0 && l.size() <= 5);
joinPool(p1);
}
/**
* In default setting, shutdown cancels periodic but not delayed
* tasks at shutdown
*/
public void testShutDown1() {
try {
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
assertTrue(p1.getExecuteExistingDelayedTasksAfterShutdownPolicy());
assertFalse(p1.getContinueExistingPeriodicTasksAfterShutdownPolicy());
ScheduledFuture[] tasks = new ScheduledFuture[5];
for(int i = 0; i < 5; i++)
tasks[i] = p1.schedule(new NoOpRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
try { p1.shutdown(); } catch(SecurityException ok) { return; }
BlockingQueue q = p1.getQueue();
for (Iterator it = q.iterator(); it.hasNext();) {
ScheduledFuture t = (ScheduledFuture)it.next();
assertFalse(t.isCancelled());
}
assertTrue(p1.isShutdown());
Thread.sleep(SMALL_DELAY_MS);
for (int i = 0; i < 5; ++i) {
assertTrue(tasks[i].isDone());
assertFalse(tasks[i].isCancelled());
}
}
catch(Exception ex) {
unexpectedException();
}
}
/**
* If setExecuteExistingDelayedTasksAfterShutdownPolicy is false,
* delayed tasks are cancelled at shutdown
*/
public void testShutDown2() {
try {
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
p1.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
ScheduledFuture[] tasks = new ScheduledFuture[5];
for(int i = 0; i < 5; i++)
tasks[i] = p1.schedule(new NoOpRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
try { p1.shutdown(); } catch(SecurityException ok) { return; }
assertTrue(p1.isShutdown());
BlockingQueue q = p1.getQueue();
assertTrue(q.isEmpty());
Thread.sleep(SMALL_DELAY_MS);
assertTrue(p1.isTerminated());
}
catch(Exception ex) {
unexpectedException();
}
}
/**
* If setContinueExistingPeriodicTasksAfterShutdownPolicy is set false,
* periodic tasks are not cancelled at shutdown
*/
public void testShutDown3() {
try {
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
p1.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
ScheduledFuture task =
p1.scheduleAtFixedRate(new NoOpRunnable(), 5, 5, TimeUnit.MILLISECONDS);
try { p1.shutdown(); } catch(SecurityException ok) { return; }
assertTrue(p1.isShutdown());
BlockingQueue q = p1.getQueue();
assertTrue(q.isEmpty());
Thread.sleep(SHORT_DELAY_MS);
assertTrue(p1.isTerminated());
}
catch(Exception ex) {
unexpectedException();
}
}
/**
* if setContinueExistingPeriodicTasksAfterShutdownPolicy is true,
* periodic tasks are cancelled at shutdown
*/
public void testShutDown4() {
ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
try {
p1.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
ScheduledFuture task =
p1.scheduleAtFixedRate(new NoOpRunnable(), 1, 1, TimeUnit.MILLISECONDS);
assertFalse(task.isCancelled());
try { p1.shutdown(); } catch(SecurityException ok) { return; }
assertFalse(task.isCancelled());
assertFalse(p1.isTerminated());
assertTrue(p1.isShutdown());
Thread.sleep(SHORT_DELAY_MS);
assertFalse(task.isCancelled());
assertTrue(task.cancel(true));
assertTrue(task.isDone());
Thread.sleep(SHORT_DELAY_MS);
assertTrue(p1.isTerminated());
}
catch(Exception ex) {
unexpectedException();
}
finally {
joinPool(p1);
}
}
/**
* completed submit of callable returns result
*/
public void testSubmitCallable() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
Future future = e.submit(new StringTask());
String result = (String)future.get();
assertSame(TEST_STRING, result);
}
catch (ExecutionException ex) {
unexpectedException();
}
catch (InterruptedException ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* completed submit of runnable returns successfully
*/
public void testSubmitRunnable() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
Future future = e.submit(new NoOpRunnable());
future.get();
assertTrue(future.isDone());
}
catch (ExecutionException ex) {
unexpectedException();
}
catch (InterruptedException ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* completed submit of (runnable, result) returns result
*/
public void testSubmitRunnable2() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
Future future = e.submit(new NoOpRunnable(), TEST_STRING);
String result = (String)future.get();
assertSame(TEST_STRING, result);
}
catch (ExecutionException ex) {
unexpectedException();
}
catch (InterruptedException ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(null) throws NPE
*/
public void testInvokeAny1() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
e.invokeAny(null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(empty collection) throws IAE
*/
public void testInvokeAny2() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
e.invokeAny(new ArrayList());
} catch (IllegalArgumentException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(c) throws NPE if c has null elements
*/
public void testInvokeAny3() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAny(l);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(c) throws ExecutionException if no task completes
*/
public void testInvokeAny4() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
e.invokeAny(l);
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(c) returns result of some task
*/
public void testInvokeAny5() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
String result = (String)e.invokeAny(l);
assertSame(TEST_STRING, result);
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(null) throws NPE
*/
public void testInvokeAll1() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
e.invokeAll(null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(empty collection) returns empty collection
*/
public void testInvokeAll2() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
List r = e.invokeAll(new ArrayList());
assertTrue(r.isEmpty());
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(c) throws NPE if c has null elements
*/
public void testInvokeAll3() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAll(l);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* get of invokeAll(c) throws exception on failed task
*/
public void testInvokeAll4() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
List result = e.invokeAll(l);
assertEquals(1, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
((Future)it.next()).get();
} catch(ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(c) returns results of all completed tasks
*/
public void testInvokeAll5() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
List result = e.invokeAll(l);
assertEquals(2, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
assertSame(TEST_STRING, ((Future)it.next()).get());
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(null) throws NPE
*/
public void testTimedInvokeAny1() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
e.invokeAny(null, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(,,null) throws NPE
*/
public void testTimedInvokeAnyNullTimeUnit() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
e.invokeAny(l, MEDIUM_DELAY_MS, null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(empty collection) throws IAE
*/
public void testTimedInvokeAny2() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
e.invokeAny(new ArrayList(), MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (IllegalArgumentException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(c) throws NPE if c has null elements
*/
public void testTimedInvokeAny3() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
ex.printStackTrace();
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(c) throws ExecutionException if no task completes
*/
public void testTimedInvokeAny4() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch(ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(c) returns result of some task
*/
public void testTimedInvokeAny5() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
String result = (String)e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertSame(TEST_STRING, result);
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(null) throws NPE
*/
public void testTimedInvokeAll1() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
e.invokeAll(null, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(,,null) throws NPE
*/
public void testTimedInvokeAllNullTimeUnit() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
e.invokeAll(l, MEDIUM_DELAY_MS, null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(empty collection) returns empty collection
*/
public void testTimedInvokeAll2() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
List r = e.invokeAll(new ArrayList(), MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertTrue(r.isEmpty());
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(c) throws NPE if c has null elements
*/
public void testTimedInvokeAll3() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* get of element of invokeAll(c) throws exception on failed task
*/
public void testTimedInvokeAll4() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
List result = e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertEquals(1, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
((Future)it.next()).get();
} catch(ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(c) returns results of all completed tasks
*/
public void testTimedInvokeAll5() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
List result = e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertEquals(2, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
assertSame(TEST_STRING, (String)((Future)it.next()).get());
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(c) cancels tasks not completed by timeout
*/
public void testTimedInvokeAll6() {
ExecutorService e = new ScheduledThreadPoolExecutor(2);
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
l.add(new StringTask());
List result = e.invokeAll(l, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
assertEquals(3, result.size());
Iterator it = result.iterator();
Future f1 = (Future)it.next();
Future f2 = (Future)it.next();
Future f3 = (Future)it.next();
assertTrue(f1.isDone());
assertTrue(f2.isDone());
assertTrue(f3.isDone());
assertFalse(f1.isCancelled());
assertTrue(f2.isCancelled());
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/ReentrantReadWriteLockTest.java 0000644 0017507 0003772 00000154377 10434507235 026346 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import edu.emory.mathcs.backport.java.util.concurrent.helpers.Utils;
import java.io.*;
import java.util.Collection;
public class ReentrantReadWriteLockTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(ReentrantReadWriteLockTest.class);
}
/**
* A runnable calling lockInterruptibly
*/
class InterruptibleLockRunnable implements Runnable {
final ReentrantReadWriteLock lock;
InterruptibleLockRunnable(ReentrantReadWriteLock l) { lock = l; }
public void run() {
try {
lock.writeLock().lockInterruptibly();
} catch(InterruptedException success){}
}
}
/**
* A runnable calling lockInterruptibly that expects to be
* interrupted
*/
class InterruptedLockRunnable implements Runnable {
final ReentrantReadWriteLock lock;
InterruptedLockRunnable(ReentrantReadWriteLock l) { lock = l; }
public void run() {
try {
lock.writeLock().lockInterruptibly();
threadShouldThrow();
} catch(InterruptedException success){}
}
}
/**
* Subclass to expose protected methods
*/
static class PublicReentrantReadWriteLock extends ReentrantReadWriteLock {
PublicReentrantReadWriteLock() { super(); }
// public Collection getQueuedThreads() {
// return super.getQueuedThreads();
// }
// public Collection getWaitingThreads(Condition c) {
// return super.getWaitingThreads(c);
// }
}
/**
* Constructor sets given fairness, and is in unlocked state
*/
public void testConstructor() {
ReentrantReadWriteLock rl = new ReentrantReadWriteLock();
assertFalse(rl.isFair());
assertFalse(rl.isWriteLocked());
assertEquals(0, rl.getReadLockCount());
// ReentrantReadWriteLock r2 = new ReentrantReadWriteLock(true);
// assertTrue(r2.isFair());
// assertFalse(r2.isWriteLocked());
// assertEquals(0, r2.getReadLockCount());
}
/**
* write-locking and read-locking an unlocked lock succeed
*/
public void testLock() {
ReentrantReadWriteLock rl = new ReentrantReadWriteLock();
rl.writeLock().lock();
assertTrue(rl.isWriteLocked());
assertTrue(rl.isWriteLockedByCurrentThread());
assertTrue(((ReentrantReadWriteLock.WriteLock)rl.writeLock()).isHeldByCurrentThread());
assertEquals(0, rl.getReadLockCount());
rl.writeLock().unlock();
assertFalse(rl.isWriteLocked());
assertFalse(rl.isWriteLockedByCurrentThread());
assertFalse(((ReentrantReadWriteLock.WriteLock)rl.writeLock()).isHeldByCurrentThread());
assertEquals(0, rl.getReadLockCount());
rl.readLock().lock();
assertFalse(rl.isWriteLocked());
assertFalse(rl.isWriteLockedByCurrentThread());
assertFalse(((ReentrantReadWriteLock.WriteLock)rl.writeLock()).isHeldByCurrentThread());
assertEquals(1, rl.getReadLockCount());
rl.readLock().unlock();
assertFalse(rl.isWriteLocked());
assertFalse(rl.isWriteLockedByCurrentThread());
assertFalse(((ReentrantReadWriteLock.WriteLock)rl.writeLock()).isHeldByCurrentThread());
assertEquals(0, rl.getReadLockCount());
}
// /**
// * locking an unlocked fair lock succeeds
// */
// public void testFairLock() {
// ReentrantReadWriteLock rl = new ReentrantReadWriteLock(true);
// rl.writeLock().lock();
// assertTrue(rl.isWriteLocked());
// assertTrue(rl.isWriteLockedByCurrentThread());
// assertTrue(rl.writeLock().isHeldByCurrentThread());
// assertEquals(0, rl.getReadLockCount());
// rl.writeLock().unlock();
// assertFalse(rl.isWriteLocked());
// assertFalse(rl.isWriteLockedByCurrentThread());
// assertFalse(rl.writeLock().isHeldByCurrentThread());
// assertEquals(0, rl.getReadLockCount());
// rl.readLock().lock();
// assertFalse(rl.isWriteLocked());
// assertFalse(rl.isWriteLockedByCurrentThread());
// assertFalse(rl.writeLock().isHeldByCurrentThread());
// assertEquals(1, rl.getReadLockCount());
// rl.readLock().unlock();
// assertFalse(rl.isWriteLocked());
// assertFalse(rl.isWriteLockedByCurrentThread());
// assertFalse(rl.writeLock().isHeldByCurrentThread());
// assertEquals(0, rl.getReadLockCount());
// }
/**
* getWriteHoldCount returns number of recursive holds
*/
public void testGetWriteHoldCount() {
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
for(int i = 1; i <= SIZE; i++) {
lock.writeLock().lock();
assertEquals(i,lock.getWriteHoldCount());
}
for(int i = SIZE; i > 0; i--) {
lock.writeLock().unlock();
assertEquals(i-1,lock.getWriteHoldCount());
}
}
/**
* WriteLock.getHoldCount returns number of recursive holds
*/
public void testGetHoldCount() {
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
for(int i = 1; i <= SIZE; i++) {
lock.writeLock().lock();
assertEquals(i,((ReentrantReadWriteLock.WriteLock)lock.writeLock()).getHoldCount());
}
for(int i = SIZE; i > 0; i--) {
lock.writeLock().unlock();
assertEquals(i-1,((ReentrantReadWriteLock.WriteLock)lock.writeLock()).getHoldCount());
}
}
/**
* getReadHoldCount returns number of recursive holds
*/
public void testGetReadHoldCount() {
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
for(int i = 1; i <= SIZE; i++) {
lock.readLock().lock();
assertEquals(i,lock.getReadHoldCount());
}
for(int i = SIZE; i > 0; i--) {
lock.readLock().unlock();
assertEquals(i-1,lock.getReadHoldCount());
}
}
/**
* write-unlocking an unlocked lock throws IllegalMonitorStateException
*/
public void testUnlock_IllegalMonitorStateException() {
ReentrantReadWriteLock rl = new ReentrantReadWriteLock();
try {
rl.writeLock().unlock();
shouldThrow();
} catch(IllegalMonitorStateException success){}
}
/**
* write-lockInterruptibly is interruptible
*/
public void testWriteLockInterruptibly_Interrupted() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
Thread t = new Thread(new Runnable() {
public void run() {
try {
lock.writeLock().lockInterruptibly();
lock.writeLock().unlock();
lock.writeLock().lockInterruptibly();
lock.writeLock().unlock();
} catch(InterruptedException success){}
}
});
try {
lock.writeLock().lock();
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
Thread.sleep(SHORT_DELAY_MS);
lock.writeLock().unlock();
t.join();
} catch(Exception e){
unexpectedException();
}
}
/**
* timed write-tryLock is interruptible
*/
public void testWriteTryLock_Interrupted() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
lock.writeLock().lock();
Thread t = new Thread(new Runnable() {
public void run() {
try {
lock.writeLock().tryLock(1000,TimeUnit.MILLISECONDS);
} catch(InterruptedException success){}
}
});
try {
t.start();
t.interrupt();
lock.writeLock().unlock();
t.join();
} catch(Exception e){
unexpectedException();
}
}
/**
* read-lockInterruptibly is interruptible
*/
public void testReadLockInterruptibly_Interrupted() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
lock.writeLock().lock();
Thread t = new Thread(new Runnable() {
public void run() {
try {
lock.readLock().lockInterruptibly();
} catch(InterruptedException success){}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
Thread.sleep(SHORT_DELAY_MS);
lock.writeLock().unlock();
t.join();
} catch(Exception e){
unexpectedException();
}
}
/**
* timed read-tryLock is interruptible
*/
public void testReadTryLock_Interrupted() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
lock.writeLock().lock();
Thread t = new Thread(new Runnable() {
public void run() {
try {
lock.readLock().tryLock(1000,TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch(InterruptedException success){}
}
});
try {
t.start();
t.interrupt();
t.join();
} catch(Exception e){
unexpectedException();
}
}
/**
* write-tryLock fails if locked
*/
public void testWriteTryLockWhenLocked() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
lock.writeLock().lock();
Thread t = new Thread(new Runnable() {
public void run() {
threadAssertFalse(lock.writeLock().tryLock());
}
});
try {
t.start();
t.join();
lock.writeLock().unlock();
} catch(Exception e){
unexpectedException();
}
}
/**
* read-tryLock fails if locked
*/
public void testReadTryLockWhenLocked() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
lock.writeLock().lock();
Thread t = new Thread(new Runnable() {
public void run() {
threadAssertFalse(lock.readLock().tryLock());
}
});
try {
t.start();
t.join();
lock.writeLock().unlock();
} catch(Exception e){
unexpectedException();
}
}
/**
* Multiple threads can hold a read lock when not write-locked
*/
public void testMultipleReadLocks() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
lock.readLock().lock();
Thread t = new Thread(new Runnable() {
public void run() {
threadAssertTrue(lock.readLock().tryLock());
lock.readLock().unlock();
}
});
try {
t.start();
t.join();
lock.readLock().unlock();
} catch(Exception e){
unexpectedException();
}
}
/**
* A writelock succeeds after reading threads unlock
*/
public void testWriteAfterMultipleReadLocks() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
lock.readLock().lock();
Thread t1 = new Thread(new Runnable() {
public void run() {
lock.readLock().lock();
lock.readLock().unlock();
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
lock.writeLock().lock();
lock.writeLock().unlock();
}
});
try {
t1.start();
t2.start();
Thread.sleep(SHORT_DELAY_MS);
lock.readLock().unlock();
t1.join(MEDIUM_DELAY_MS);
t2.join(MEDIUM_DELAY_MS);
assertTrue(!t1.isAlive());
assertTrue(!t2.isAlive());
} catch(Exception e){
unexpectedException();
}
}
/**
* Readlocks succeed after a writing thread unlocks
*/
public void testReadAfterWriteLock() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
lock.writeLock().lock();
Thread t1 = new Thread(new Runnable() {
public void run() {
lock.readLock().lock();
lock.readLock().unlock();
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
lock.readLock().lock();
lock.readLock().unlock();
}
});
try {
t1.start();
t2.start();
Thread.sleep(SHORT_DELAY_MS);
lock.writeLock().unlock();
t1.join(MEDIUM_DELAY_MS);
t2.join(MEDIUM_DELAY_MS);
assertTrue(!t1.isAlive());
assertTrue(!t2.isAlive());
} catch(Exception e){
unexpectedException();
}
}
/**
* Read trylock succeeds if write locked by current thread
*/
public void testReadHoldingWriteLock() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
lock.writeLock().lock();
assertTrue(lock.readLock().tryLock());
lock.readLock().unlock();
lock.writeLock().unlock();
}
/**
* Read lock succeeds if write locked by current thread even if
* other threads are waiting for readlock
*/
public void testReadHoldingWriteLock2() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
lock.writeLock().lock();
Thread t1 = new Thread(new Runnable() {
public void run() {
lock.readLock().lock();
lock.readLock().unlock();
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
lock.readLock().lock();
lock.readLock().unlock();
}
});
try {
t1.start();
t2.start();
lock.readLock().lock();
lock.readLock().unlock();
Thread.sleep(SHORT_DELAY_MS);
lock.readLock().lock();
lock.readLock().unlock();
lock.writeLock().unlock();
t1.join(MEDIUM_DELAY_MS);
t2.join(MEDIUM_DELAY_MS);
assertTrue(!t1.isAlive());
assertTrue(!t2.isAlive());
} catch(Exception e){
unexpectedException();
}
}
/**
* Read lock succeeds if write locked by current thread even if
* other threads are waiting for writelock
*/
public void testReadHoldingWriteLock3() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
lock.writeLock().lock();
Thread t1 = new Thread(new Runnable() {
public void run() {
lock.writeLock().lock();
lock.writeLock().unlock();
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
lock.writeLock().lock();
lock.writeLock().unlock();
}
});
try {
t1.start();
t2.start();
lock.readLock().lock();
lock.readLock().unlock();
Thread.sleep(SHORT_DELAY_MS);
lock.readLock().lock();
lock.readLock().unlock();
lock.writeLock().unlock();
t1.join(MEDIUM_DELAY_MS);
t2.join(MEDIUM_DELAY_MS);
assertTrue(!t1.isAlive());
assertTrue(!t2.isAlive());
} catch(Exception e){
unexpectedException();
}
}
/**
* Write lock succeeds if write locked by current thread even if
* other threads are waiting for writelock
*/
public void testWriteHoldingWriteLock4() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
lock.writeLock().lock();
Thread t1 = new Thread(new Runnable() {
public void run() {
lock.writeLock().lock();
lock.writeLock().unlock();
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
lock.writeLock().lock();
lock.writeLock().unlock();
}
});
try {
t1.start();
t2.start();
lock.writeLock().lock();
lock.writeLock().unlock();
Thread.sleep(SHORT_DELAY_MS);
lock.writeLock().lock();
lock.writeLock().unlock();
lock.writeLock().unlock();
t1.join(MEDIUM_DELAY_MS);
t2.join(MEDIUM_DELAY_MS);
assertTrue(!t1.isAlive());
assertTrue(!t2.isAlive());
} catch(Exception e){
unexpectedException();
}
}
// /**
// * Fair Read trylock succeeds if write locked by current thread
// */
// public void testReadHoldingWriteLockFair() {
// final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
// lock.writeLock().lock();
// assertTrue(lock.readLock().tryLock());
// lock.readLock().unlock();
// lock.writeLock().unlock();
// }
// /**
// * Fair Read lock succeeds if write locked by current thread even if
// * other threads are waiting for readlock
// */
// public void testReadHoldingWriteLockFair2() {
// final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
// lock.writeLock().lock();
// Thread t1 = new Thread(new Runnable() {
// public void run() {
// lock.readLock().lock();
// lock.readLock().unlock();
// }
// });
// Thread t2 = new Thread(new Runnable() {
// public void run() {
// lock.readLock().lock();
// lock.readLock().unlock();
// }
// });
//
// try {
// t1.start();
// t2.start();
// lock.readLock().lock();
// lock.readLock().unlock();
// Thread.sleep(SHORT_DELAY_MS);
// lock.readLock().lock();
// lock.readLock().unlock();
// lock.writeLock().unlock();
// t1.join(MEDIUM_DELAY_MS);
// t2.join(MEDIUM_DELAY_MS);
// assertTrue(!t1.isAlive());
// assertTrue(!t2.isAlive());
//
// } catch(Exception e){
// unexpectedException();
// }
// }
// /**
// * Fair Read lock succeeds if write locked by current thread even if
// * other threads are waiting for writelock
// */
// public void testReadHoldingWriteLockFair3() {
// final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
// lock.writeLock().lock();
// Thread t1 = new Thread(new Runnable() {
// public void run() {
// lock.writeLock().lock();
// lock.writeLock().unlock();
// }
// });
// Thread t2 = new Thread(new Runnable() {
// public void run() {
// lock.writeLock().lock();
// lock.writeLock().unlock();
// }
// });
//
// try {
// t1.start();
// t2.start();
// lock.readLock().lock();
// lock.readLock().unlock();
// Thread.sleep(SHORT_DELAY_MS);
// lock.readLock().lock();
// lock.readLock().unlock();
// lock.writeLock().unlock();
// t1.join(MEDIUM_DELAY_MS);
// t2.join(MEDIUM_DELAY_MS);
// assertTrue(!t1.isAlive());
// assertTrue(!t2.isAlive());
//
// } catch(Exception e){
// unexpectedException();
// }
// }
// /**
// * Fair Write lock succeeds if write locked by current thread even if
// * other threads are waiting for writelock
// */
// public void testWriteHoldingWriteLockFair4() {
// final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
// lock.writeLock().lock();
// Thread t1 = new Thread(new Runnable() {
// public void run() {
// lock.writeLock().lock();
// lock.writeLock().unlock();
// }
// });
// Thread t2 = new Thread(new Runnable() {
// public void run() {
// lock.writeLock().lock();
// lock.writeLock().unlock();
// }
// });
//
// try {
// t1.start();
// t2.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(lock.isWriteLockedByCurrentThread());
// assertTrue(lock.getWriteHoldCount() == 1);
// lock.writeLock().lock();
// assertTrue(lock.getWriteHoldCount() == 2);
// lock.writeLock().unlock();
// lock.writeLock().lock();
// lock.writeLock().unlock();
// lock.writeLock().unlock();
// t1.join(MEDIUM_DELAY_MS);
// t2.join(MEDIUM_DELAY_MS);
// assertTrue(!t1.isAlive());
// assertTrue(!t2.isAlive());
//
// } catch(Exception e){
// unexpectedException();
// }
// }
/**
* Read tryLock succeeds if readlocked but not writelocked
*/
public void testTryLockWhenReadLocked() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
lock.readLock().lock();
Thread t = new Thread(new Runnable() {
public void run() {
threadAssertTrue(lock.readLock().tryLock());
lock.readLock().unlock();
}
});
try {
t.start();
t.join();
lock.readLock().unlock();
} catch(Exception e){
unexpectedException();
}
}
/**
* write tryLock fails when readlocked
*/
public void testWriteTryLockWhenReadLocked() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
lock.readLock().lock();
Thread t = new Thread(new Runnable() {
public void run() {
threadAssertFalse(lock.writeLock().tryLock());
}
});
try {
t.start();
t.join();
lock.readLock().unlock();
} catch(Exception e){
unexpectedException();
}
}
// /**
// * Fair Read tryLock succeeds if readlocked but not writelocked
// */
// public void testTryLockWhenReadLockedFair() {
// final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
// lock.readLock().lock();
// Thread t = new Thread(new Runnable() {
// public void run() {
// threadAssertTrue(lock.readLock().tryLock());
// lock.readLock().unlock();
// }
// });
// try {
// t.start();
// t.join();
// lock.readLock().unlock();
// } catch(Exception e){
// unexpectedException();
// }
// }
// /**
// * Fair write tryLock fails when readlocked
// */
// public void testWriteTryLockWhenReadLockedFair() {
// final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
// lock.readLock().lock();
// Thread t = new Thread(new Runnable() {
// public void run() {
// threadAssertFalse(lock.writeLock().tryLock());
// }
// });
// try {
// t.start();
// t.join();
// lock.readLock().unlock();
// } catch(Exception e){
// unexpectedException();
// }
// }
/**
* write timed tryLock times out if locked
*/
public void testWriteTryLock_Timeout() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
lock.writeLock().lock();
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertFalse(lock.writeLock().tryLock(1, TimeUnit.MILLISECONDS));
} catch (Exception ex) {
threadUnexpectedException();
}
}
});
try {
t.start();
t.join();
lock.writeLock().unlock();
} catch(Exception e){
unexpectedException();
}
}
/**
* read timed tryLock times out if write-locked
*/
public void testReadTryLock_Timeout() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
lock.writeLock().lock();
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertFalse(lock.readLock().tryLock(1, TimeUnit.MILLISECONDS));
} catch (Exception ex) {
threadUnexpectedException();
}
}
});
try {
t.start();
t.join();
lock.writeLock().unlock();
} catch(Exception e){
unexpectedException();
}
}
/**
* write lockInterruptibly succeeds if lock free else is interruptible
*/
public void testWriteLockInterruptibly() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
try {
lock.writeLock().lockInterruptibly();
} catch(Exception e) {
unexpectedException();
}
Thread t = new Thread(new Runnable() {
public void run() {
try {
lock.writeLock().lockInterruptibly();
threadShouldThrow();
}
catch(InterruptedException success) {
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
Thread.sleep(SHORT_DELAY_MS);
t.join();
lock.writeLock().unlock();
} catch(Exception e){
unexpectedException();
}
}
/**
* read lockInterruptibly succeeds if lock free else is interruptible
*/
public void testReadLockInterruptibly() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
try {
lock.writeLock().lockInterruptibly();
} catch(Exception e) {
unexpectedException();
}
Thread t = new Thread(new Runnable() {
public void run() {
try {
lock.readLock().lockInterruptibly();
threadShouldThrow();
}
catch(InterruptedException success) {
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
lock.writeLock().unlock();
} catch(Exception e){
unexpectedException();
}
}
/**
* Calling await without holding lock throws IllegalMonitorStateException
*/
public void testAwait_IllegalMonitor() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
final Condition c = lock.writeLock().newCondition();
try {
c.await();
shouldThrow();
}
catch (IllegalMonitorStateException success) {
}
catch (Exception ex) {
shouldThrow();
}
}
/**
* Calling signal without holding lock throws IllegalMonitorStateException
*/
public void testSignal_IllegalMonitor() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
final Condition c = lock.writeLock().newCondition();
try {
c.signal();
shouldThrow();
}
catch (IllegalMonitorStateException success) {
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* awaitNanos without a signal times out
*/
public void testAwaitNanos_Timeout() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
final Condition c = lock.writeLock().newCondition();
try {
lock.writeLock().lock();
long t = Utils.awaitNanos(c, 100);
assertTrue(t <= 0);
lock.writeLock().unlock();
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* timed await without a signal times out
*/
public void testAwait_Timeout() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
final Condition c = lock.writeLock().newCondition();
try {
lock.writeLock().lock();
lock.writeLock().unlock();
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* awaitUntil without a signal times out
*/
public void testAwaitUntil_Timeout() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
final Condition c = lock.writeLock().newCondition();
try {
lock.writeLock().lock();
java.util.Date d = new java.util.Date();
lock.writeLock().unlock();
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* await returns when signalled
*/
public void testAwait() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
final Condition c = lock.writeLock().newCondition();
Thread t = new Thread(new Runnable() {
public void run() {
try {
lock.writeLock().lock();
c.await();
lock.writeLock().unlock();
}
catch(InterruptedException e) {
threadUnexpectedException();
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
lock.writeLock().lock();
c.signal();
lock.writeLock().unlock();
t.join(SHORT_DELAY_MS);
assertFalse(t.isAlive());
}
catch (Exception ex) {
unexpectedException();
}
}
/** A helper class for uninterruptible wait tests */
class UninterruptableThread extends Thread {
private Lock lock;
private Condition c;
public volatile boolean canAwake = false;
public volatile boolean interrupted = false;
public volatile boolean lockStarted = false;
public UninterruptableThread(Lock lock, Condition c) {
this.lock = lock;
this.c = c;
}
public synchronized void run() {
lock.lock();
lockStarted = true;
while (!canAwake) {
c.awaitUninterruptibly();
}
interrupted = isInterrupted();
lock.unlock();
}
}
/**
* awaitUninterruptibly doesn't abort on interrupt
*/
public void testAwaitUninterruptibly() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
final Condition c = lock.writeLock().newCondition();
UninterruptableThread thread = new UninterruptableThread(lock.writeLock(), c);
try {
thread.start();
while (!thread.lockStarted) {
Thread.sleep(100);
}
lock.writeLock().lock();
try {
thread.interrupt();
thread.canAwake = true;
c.signal();
} finally {
lock.writeLock().unlock();
}
thread.join();
assertTrue(thread.interrupted);
assertFalse(thread.isAlive());
} catch (Exception ex) {
unexpectedException();
}
}
/**
* await is interruptible
*/
public void testAwait_Interrupt() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
final Condition c = lock.writeLock().newCondition();
Thread t = new Thread(new Runnable() {
public void run() {
try {
lock.writeLock().lock();
c.await();
lock.writeLock().unlock();
threadShouldThrow();
}
catch(InterruptedException success) {
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join(SHORT_DELAY_MS);
assertFalse(t.isAlive());
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* awaitNanos is interruptible
*/
public void testAwaitNanos_Interrupt() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
final Condition c = lock.writeLock().newCondition();
Thread t = new Thread(new Runnable() {
public void run() {
try {
lock.writeLock().lock();
Utils.awaitNanos(c, SHORT_DELAY_MS * 2 * 1000000);
lock.writeLock().unlock();
threadShouldThrow();
}
catch(InterruptedException success) {
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join(SHORT_DELAY_MS);
assertFalse(t.isAlive());
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* awaitUntil is interruptible
*/
public void testAwaitUntil_Interrupt() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
final Condition c = lock.writeLock().newCondition();
Thread t = new Thread(new Runnable() {
public void run() {
try {
lock.writeLock().lock();
java.util.Date d = new java.util.Date();
c.awaitUntil(new java.util.Date(d.getTime() + 10000));
lock.writeLock().unlock();
threadShouldThrow();
}
catch(InterruptedException success) {
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join(SHORT_DELAY_MS);
assertFalse(t.isAlive());
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* signalAll wakes up all threads
*/
public void testSignalAll() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
final Condition c = lock.writeLock().newCondition();
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
lock.writeLock().lock();
c.await();
lock.writeLock().unlock();
}
catch(InterruptedException e) {
threadUnexpectedException();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
lock.writeLock().lock();
c.await();
lock.writeLock().unlock();
}
catch(InterruptedException e) {
threadUnexpectedException();
}
}
});
try {
t1.start();
t2.start();
Thread.sleep(SHORT_DELAY_MS);
lock.writeLock().lock();
c.signalAll();
lock.writeLock().unlock();
t1.join(SHORT_DELAY_MS);
t2.join(SHORT_DELAY_MS);
assertFalse(t1.isAlive());
assertFalse(t2.isAlive());
}
catch (Exception ex) {
unexpectedException();
}
}
/**
* A serialized lock deserializes as unlocked
*/
public void testSerialization() {
ReentrantReadWriteLock l = new ReentrantReadWriteLock();
l.readLock().lock();
l.readLock().unlock();
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(l);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
ReentrantReadWriteLock r = (ReentrantReadWriteLock) in.readObject();
r.readLock().lock();
r.readLock().unlock();
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* hasQueuedThreads reports whether there are waiting threads
*/
public void testhasQueuedThreads() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
Thread t1 = new Thread(new InterruptedLockRunnable(lock));
Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
try {
assertFalse(lock.hasQueuedThreads());
lock.writeLock().lock();
t1.start();
Thread.sleep(SHORT_DELAY_MS);
assertTrue(lock.hasQueuedThreads());
t2.start();
Thread.sleep(SHORT_DELAY_MS);
assertTrue(lock.hasQueuedThreads());
t1.interrupt();
Thread.sleep(SHORT_DELAY_MS);
assertTrue(lock.hasQueuedThreads());
lock.writeLock().unlock();
Thread.sleep(SHORT_DELAY_MS);
assertFalse(lock.hasQueuedThreads());
t1.join();
t2.join();
} catch(Exception e){
unexpectedException();
}
}
// /**
// * hasQueuedThread(null) throws NPE
// */
// public void testHasQueuedThreadNPE() {
// final ReentrantReadWriteLock sync = new ReentrantReadWriteLock();
// try {
// sync.hasQueuedThread(null);
// shouldThrow();
// } catch (NullPointerException success) {
// }
// }
//
// /**
// * hasQueuedThread reports whether a thread is queued.
// */
// public void testHasQueuedThread() {
// final ReentrantReadWriteLock sync = new ReentrantReadWriteLock();
// Thread t1 = new Thread(new InterruptedLockRunnable(sync));
// Thread t2 = new Thread(new InterruptibleLockRunnable(sync));
// try {
// assertFalse(sync.hasQueuedThread(t1));
// assertFalse(sync.hasQueuedThread(t2));
// sync.writeLock().lock();
// t1.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.hasQueuedThread(t1));
// t2.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(sync.hasQueuedThread(t1));
// assertTrue(sync.hasQueuedThread(t2));
// t1.interrupt();
// Thread.sleep(SHORT_DELAY_MS);
// assertFalse(sync.hasQueuedThread(t1));
// assertTrue(sync.hasQueuedThread(t2));
// sync.writeLock().unlock();
// Thread.sleep(SHORT_DELAY_MS);
// assertFalse(sync.hasQueuedThread(t1));
// Thread.sleep(SHORT_DELAY_MS);
// assertFalse(sync.hasQueuedThread(t2));
// t1.join();
// t2.join();
// } catch(Exception e){
// unexpectedException();
// }
// }
/**
* getQueueLength reports number of waiting threads
*/
public void testGetQueueLength() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
Thread t1 = new Thread(new InterruptedLockRunnable(lock));
Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
try {
assertEquals(0, lock.getQueueLength());
lock.writeLock().lock();
t1.start();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(1, lock.getQueueLength());
t2.start();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(2, lock.getQueueLength());
t1.interrupt();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(1, lock.getQueueLength());
lock.writeLock().unlock();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(0, lock.getQueueLength());
t1.join();
t2.join();
} catch(Exception e){
unexpectedException();
}
}
// /**
// * getQueuedThreads includes waiting threads
// */
// public void testGetQueuedThreads() {
// final PublicReentrantReadWriteLock lock = new PublicReentrantReadWriteLock();
// Thread t1 = new Thread(new InterruptedLockRunnable(lock));
// Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
// try {
// assertTrue(lock.getQueuedThreads().isEmpty());
// lock.writeLock().lock();
// assertTrue(lock.getQueuedThreads().isEmpty());
// t1.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(lock.getQueuedThreads().contains(t1));
// t2.start();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(lock.getQueuedThreads().contains(t1));
// assertTrue(lock.getQueuedThreads().contains(t2));
// t1.interrupt();
// Thread.sleep(SHORT_DELAY_MS);
// assertFalse(lock.getQueuedThreads().contains(t1));
// assertTrue(lock.getQueuedThreads().contains(t2));
// lock.writeLock().unlock();
// Thread.sleep(SHORT_DELAY_MS);
// assertTrue(lock.getQueuedThreads().isEmpty());
// t1.join();
// t2.join();
// } catch(Exception e){
// unexpectedException();
// }
// }
//
// /**
// * hasWaiters throws NPE if null
// */
// public void testHasWaitersNPE() {
// final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
// try {
// lock.hasWaiters(null);
// shouldThrow();
// } catch (NullPointerException success) {
// } catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * getWaitQueueLength throws NPE if null
// */
// public void testGetWaitQueueLengthNPE() {
// final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
// try {
// lock.getWaitQueueLength(null);
// shouldThrow();
// } catch (NullPointerException success) {
// } catch (Exception ex) {
// unexpectedException();
// }
// }
//
//
// /**
// * getWaitingThreads throws NPE if null
// */
// public void testGetWaitingThreadsNPE() {
// final PublicReentrantReadWriteLock lock = new PublicReentrantReadWriteLock();
// try {
// lock.getWaitingThreads(null);
// shouldThrow();
// } catch (NullPointerException success) {
// } catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * hasWaiters throws IAE if not owned
// */
// public void testHasWaitersIAE() {
// final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
// final Condition c = (lock.writeLock().newCondition());
// final ReentrantReadWriteLock lock2 = new ReentrantReadWriteLock();
// try {
// lock2.hasWaiters(c);
// shouldThrow();
// } catch (IllegalArgumentException success) {
// } catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * hasWaiters throws IMSE if not locked
// */
// public void testHasWaitersIMSE() {
// final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
// final Condition c = (lock.writeLock().newCondition());
// try {
// lock.hasWaiters(c);
// shouldThrow();
// } catch (IllegalMonitorStateException success) {
// } catch (Exception ex) {
// unexpectedException();
// }
// }
//
//
// /**
// * getWaitQueueLength throws IAE if not owned
// */
// public void testGetWaitQueueLengthIAE() {
// final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
// final Condition c = (lock.writeLock().newCondition());
// final ReentrantReadWriteLock lock2 = new ReentrantReadWriteLock();
// try {
// lock2.getWaitQueueLength(c);
// shouldThrow();
// } catch (IllegalArgumentException success) {
// } catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * getWaitQueueLength throws IMSE if not locked
// */
// public void testGetWaitQueueLengthIMSE() {
// final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
// final Condition c = (lock.writeLock().newCondition());
// try {
// lock.getWaitQueueLength(c);
// shouldThrow();
// } catch (IllegalMonitorStateException success) {
// } catch (Exception ex) {
// unexpectedException();
// }
// }
//
//
// /**
// * getWaitingThreads throws IAE if not owned
// */
// public void testGetWaitingThreadsIAE() {
// final PublicReentrantReadWriteLock lock = new PublicReentrantReadWriteLock();
// final Condition c = (lock.writeLock().newCondition());
// final PublicReentrantReadWriteLock lock2 = new PublicReentrantReadWriteLock();
// try {
// lock2.getWaitingThreads(c);
// shouldThrow();
// } catch (IllegalArgumentException success) {
// } catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * getWaitingThreads throws IMSE if not locked
// */
// public void testGetWaitingThreadsIMSE() {
// final PublicReentrantReadWriteLock lock = new PublicReentrantReadWriteLock();
// final Condition c = (lock.writeLock().newCondition());
// try {
// lock.getWaitingThreads(c);
// shouldThrow();
// } catch (IllegalMonitorStateException success) {
// } catch (Exception ex) {
// unexpectedException();
// }
// }
//
//
// /**
// * hasWaiters returns true when a thread is waiting, else false
// */
// public void testHasWaiters() {
// final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
// final Condition c = (lock.writeLock().newCondition());
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// lock.writeLock().lock();
// threadAssertFalse(lock.hasWaiters(c));
// threadAssertEquals(0, lock.getWaitQueueLength(c));
// c.await();
// lock.writeLock().unlock();
// }
// catch(InterruptedException e) {
// threadUnexpectedException();
// }
// }
// });
//
// try {
// t.start();
// Thread.sleep(SHORT_DELAY_MS);
// lock.writeLock().lock();
// assertTrue(lock.hasWaiters(c));
// assertEquals(1, lock.getWaitQueueLength(c));
// c.signal();
// lock.writeLock().unlock();
// Thread.sleep(SHORT_DELAY_MS);
// lock.writeLock().lock();
// assertFalse(lock.hasWaiters(c));
// assertEquals(0, lock.getWaitQueueLength(c));
// lock.writeLock().unlock();
// t.join(SHORT_DELAY_MS);
// assertFalse(t.isAlive());
// }
// catch (Exception ex) {
// unexpectedException();
// }
// }
//
// /**
// * getWaitQueueLength returns number of waiting threads
// */
// public void testGetWaitQueueLength() {
// final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
// final Condition c = (lock.writeLock().newCondition());
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// lock.writeLock().lock();
// threadAssertFalse(lock.hasWaiters(c));
// threadAssertEquals(0, lock.getWaitQueueLength(c));
// c.await();
// lock.writeLock().unlock();
// }
// catch(InterruptedException e) {
// threadUnexpectedException();
// }
// }
// });
//
// try {
// t.start();
// Thread.sleep(SHORT_DELAY_MS);
// lock.writeLock().lock();
// assertTrue(lock.hasWaiters(c));
// assertEquals(1, lock.getWaitQueueLength(c));
// c.signal();
// lock.writeLock().unlock();
// Thread.sleep(SHORT_DELAY_MS);
// lock.writeLock().lock();
// assertFalse(lock.hasWaiters(c));
// assertEquals(0, lock.getWaitQueueLength(c));
// lock.writeLock().unlock();
// t.join(SHORT_DELAY_MS);
// assertFalse(t.isAlive());
// }
// catch (Exception ex) {
// unexpectedException();
// }
// }
//
//
// /**
// * getWaitingThreads returns only and all waiting threads
// */
// public void testGetWaitingThreads() {
// final PublicReentrantReadWriteLock lock = new PublicReentrantReadWriteLock();
// final Condition c = lock.writeLock().newCondition();
// Thread t1 = new Thread(new Runnable() {
// public void run() {
// try {
// lock.writeLock().lock();
// threadAssertTrue(lock.getWaitingThreads(c).isEmpty());
// c.await();
// lock.writeLock().unlock();
// }
// catch(InterruptedException e) {
// threadUnexpectedException();
// }
// }
// });
//
// Thread t2 = new Thread(new Runnable() {
// public void run() {
// try {
// lock.writeLock().lock();
// threadAssertFalse(lock.getWaitingThreads(c).isEmpty());
// c.await();
// lock.writeLock().unlock();
// }
// catch(InterruptedException e) {
// threadUnexpectedException();
// }
// }
// });
//
// try {
// lock.writeLock().lock();
// assertTrue(lock.getWaitingThreads(c).isEmpty());
// lock.writeLock().unlock();
// t1.start();
// Thread.sleep(SHORT_DELAY_MS);
// t2.start();
// Thread.sleep(SHORT_DELAY_MS);
// lock.writeLock().lock();
// assertTrue(lock.hasWaiters(c));
// assertTrue(lock.getWaitingThreads(c).contains(t1));
// assertTrue(lock.getWaitingThreads(c).contains(t2));
// c.signalAll();
// lock.writeLock().unlock();
// Thread.sleep(SHORT_DELAY_MS);
// lock.writeLock().lock();
// assertFalse(lock.hasWaiters(c));
// assertTrue(lock.getWaitingThreads(c).isEmpty());
// lock.writeLock().unlock();
// t1.join(SHORT_DELAY_MS);
// t2.join(SHORT_DELAY_MS);
// assertFalse(t1.isAlive());
// assertFalse(t2.isAlive());
// }
// catch (Exception ex) {
// unexpectedException();
// }
// }
/**
* toString indicates current lock state
*/
public void testToString() {
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
String us = lock.toString();
assertTrue(us.indexOf("Write locks = 0") >= 0);
assertTrue(us.indexOf("Read locks = 0") >= 0);
lock.writeLock().lock();
String ws = lock.toString();
assertTrue(ws.indexOf("Write locks = 1") >= 0);
assertTrue(ws.indexOf("Read locks = 0") >= 0);
lock.writeLock().unlock();
lock.readLock().lock();
lock.readLock().lock();
String rs = lock.toString();
assertTrue(rs.indexOf("Write locks = 0") >= 0);
assertTrue(rs.indexOf("Read locks = 2") >= 0);
}
/**
* readLock.toString indicates current lock state
*/
public void testReadLockToString() {
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
String us = lock.readLock().toString();
assertTrue(us.indexOf("Read locks = 0") >= 0);
lock.readLock().lock();
lock.readLock().lock();
String rs = lock.readLock().toString();
assertTrue(rs.indexOf("Read locks = 2") >= 0);
}
/**
* writeLock.toString indicates current lock state
*/
public void testWriteLockToString() {
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
String us = lock.writeLock().toString();
assertTrue(us.indexOf("Unlocked") >= 0);
lock.writeLock().lock();
String ls = lock.writeLock().toString();
assertTrue(ls.indexOf("Locked") >= 0);
}
}
backport-util-concurrent-3.1-src/test/tck/src/ThreadPoolExecutorTest.java 0000644 0017507 0003772 00000151131 10431260156 025520 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import junit.framework.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class ThreadPoolExecutorTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(ThreadPoolExecutorTest.class);
}
static class ExtendedTPE extends ThreadPoolExecutor {
volatile boolean beforeCalled = false;
volatile boolean afterCalled = false;
volatile boolean terminatedCalled = false;
public ExtendedTPE() {
super(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new SynchronousQueue());
}
protected void beforeExecute(Thread t, Runnable r) {
beforeCalled = true;
}
protected void afterExecute(Runnable r, Throwable t) {
afterCalled = true;
}
protected void terminated() {
terminatedCalled = true;
}
}
static class FailingThreadFactory implements ThreadFactory{
int calls = 0;
public Thread newThread(Runnable r){
if (++calls > 1) return null;
return new Thread(r);
}
}
/**
* execute successfully executes a runnable
*/
public void testExecute() {
ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
p1.execute(new Runnable() {
public void run() {
try {
Thread.sleep(SHORT_DELAY_MS);
} catch(InterruptedException e){
threadUnexpectedException();
}
}
});
Thread.sleep(SMALL_DELAY_MS);
} catch(InterruptedException e){
unexpectedException();
}
joinPool(p1);
}
/**
* getActiveCount increases but doesn't overestimate, when a
* thread becomes active
*/
public void testGetActiveCount() {
ThreadPoolExecutor p2 = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertEquals(0, p2.getActiveCount());
p2.execute(new MediumRunnable());
try {
Thread.sleep(SHORT_DELAY_MS);
} catch(Exception e){
unexpectedException();
}
assertEquals(1, p2.getActiveCount());
joinPool(p2);
}
/**
* prestartCoreThread starts a thread if under corePoolSize, else doesn't
*/
public void testPrestartCoreThread() {
ThreadPoolExecutor p2 = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertEquals(0, p2.getPoolSize());
assertTrue(p2.prestartCoreThread());
assertEquals(1, p2.getPoolSize());
assertTrue(p2.prestartCoreThread());
assertEquals(2, p2.getPoolSize());
assertFalse(p2.prestartCoreThread());
assertEquals(2, p2.getPoolSize());
joinPool(p2);
}
/**
* prestartAllCoreThreads starts all corePoolSize threads
*/
public void testPrestartAllCoreThreads() {
ThreadPoolExecutor p2 = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertEquals(0, p2.getPoolSize());
p2.prestartAllCoreThreads();
assertEquals(2, p2.getPoolSize());
p2.prestartAllCoreThreads();
assertEquals(2, p2.getPoolSize());
joinPool(p2);
}
/**
* getCompletedTaskCount increases, but doesn't overestimate,
* when tasks complete
*/
public void testGetCompletedTaskCount() {
ThreadPoolExecutor p2 = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertEquals(0, p2.getCompletedTaskCount());
p2.execute(new ShortRunnable());
try {
Thread.sleep(SMALL_DELAY_MS);
} catch(Exception e){
unexpectedException();
}
assertEquals(1, p2.getCompletedTaskCount());
try { p2.shutdown(); } catch(SecurityException ok) { return; }
joinPool(p2);
}
/**
* getCorePoolSize returns size given in constructor if not otherwise set
*/
public void testGetCorePoolSize() {
ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertEquals(1, p1.getCorePoolSize());
joinPool(p1);
}
/**
* getKeepAliveTime returns value given in constructor if not otherwise set
*/
public void testGetKeepAliveTime() {
ThreadPoolExecutor p2 = new ThreadPoolExecutor(2, 2, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertEquals(1, p2.getKeepAliveTime(TimeUnit.SECONDS));
joinPool(p2);
}
/**
* getThreadFactory returns factory in constructor if not set
*/
public void testGetThreadFactory() {
ThreadFactory tf = new SimpleThreadFactory();
ThreadPoolExecutor p = new ThreadPoolExecutor(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10), tf, new NoOpREHandler());
assertSame(tf, p.getThreadFactory());
joinPool(p);
}
/**
* setThreadFactory sets the thread factory returned by getThreadFactory
*/
public void testSetThreadFactory() {
ThreadPoolExecutor p = new ThreadPoolExecutor(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
ThreadFactory tf = new SimpleThreadFactory();
p.setThreadFactory(tf);
assertSame(tf, p.getThreadFactory());
joinPool(p);
}
/**
* setThreadFactory(null) throws NPE
*/
public void testSetThreadFactoryNull() {
ThreadPoolExecutor p = new ThreadPoolExecutor(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
p.setThreadFactory(null);
shouldThrow();
} catch (NullPointerException success) {
} finally {
joinPool(p);
}
}
/**
* getRejectedExecutionHandler returns handler in constructor if not set
*/
public void testGetRejectedExecutionHandler() {
RejectedExecutionHandler h = new NoOpREHandler();
ThreadPoolExecutor p = new ThreadPoolExecutor(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10), h);
assertSame(h, p.getRejectedExecutionHandler());
joinPool(p);
}
/**
* setRejectedExecutionHandler sets the handler returned by
* getRejectedExecutionHandler
*/
public void testSetRejectedExecutionHandler() {
ThreadPoolExecutor p = new ThreadPoolExecutor(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
RejectedExecutionHandler h = new NoOpREHandler();
p.setRejectedExecutionHandler(h);
assertSame(h, p.getRejectedExecutionHandler());
joinPool(p);
}
/**
* setRejectedExecutionHandler(null) throws NPE
*/
public void testSetRejectedExecutionHandlerNull() {
ThreadPoolExecutor p = new ThreadPoolExecutor(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
p.setRejectedExecutionHandler(null);
shouldThrow();
} catch (NullPointerException success) {
} finally {
joinPool(p);
}
}
/**
* getLargestPoolSize increases, but doesn't overestimate, when
* multiple threads active
*/
public void testGetLargestPoolSize() {
ThreadPoolExecutor p2 = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
assertEquals(0, p2.getLargestPoolSize());
p2.execute(new MediumRunnable());
p2.execute(new MediumRunnable());
Thread.sleep(SHORT_DELAY_MS);
assertEquals(2, p2.getLargestPoolSize());
} catch(Exception e){
unexpectedException();
}
joinPool(p2);
}
/**
* getMaximumPoolSize returns value given in constructor if not
* otherwise set
*/
public void testGetMaximumPoolSize() {
ThreadPoolExecutor p2 = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertEquals(2, p2.getMaximumPoolSize());
joinPool(p2);
}
/**
* getPoolSize increases, but doesn't overestimate, when threads
* become active
*/
public void testGetPoolSize() {
ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertEquals(0, p1.getPoolSize());
p1.execute(new MediumRunnable());
assertEquals(1, p1.getPoolSize());
joinPool(p1);
}
/**
* getTaskCount increases, but doesn't overestimate, when tasks submitted
*/
public void testGetTaskCount() {
ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
assertEquals(0, p1.getTaskCount());
p1.execute(new MediumRunnable());
Thread.sleep(SHORT_DELAY_MS);
assertEquals(1, p1.getTaskCount());
} catch(Exception e){
unexpectedException();
}
joinPool(p1);
}
/**
* isShutDown is false before shutdown, true after
*/
public void testIsShutdown() {
ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertFalse(p1.isShutdown());
try { p1.shutdown(); } catch(SecurityException ok) { return; }
assertTrue(p1.isShutdown());
joinPool(p1);
}
/**
* isTerminated is false before termination, true after
*/
public void testIsTerminated() {
ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertFalse(p1.isTerminated());
try {
p1.execute(new MediumRunnable());
} finally {
try { p1.shutdown(); } catch(SecurityException ok) { return; }
}
try {
assertTrue(p1.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
assertTrue(p1.isTerminated());
} catch(Exception e){
unexpectedException();
}
}
/**
* isTerminating is not true when running or when terminated
*/
public void testIsTerminating() {
ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertFalse(p1.isTerminating());
try {
p1.execute(new SmallRunnable());
assertFalse(p1.isTerminating());
} finally {
try { p1.shutdown(); } catch(SecurityException ok) { return; }
}
try {
assertTrue(p1.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
assertTrue(p1.isTerminated());
assertFalse(p1.isTerminating());
} catch(Exception e){
unexpectedException();
}
}
/**
* getQueue returns the work queue, which contains queued tasks
*/
public void testGetQueue() {
BlockingQueue q = new ArrayBlockingQueue(10);
ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, q);
FutureTask[] tasks = new FutureTask[5];
for(int i = 0; i < 5; i++){
tasks[i] = new FutureTask(new MediumPossiblyInterruptedRunnable(), Boolean.TRUE);
p1.execute(tasks[i]);
}
try {
Thread.sleep(SHORT_DELAY_MS);
BlockingQueue wq = p1.getQueue();
assertSame(q, wq);
assertFalse(wq.contains(tasks[0]));
assertTrue(wq.contains(tasks[4]));
for (int i = 1; i < 5; ++i)
tasks[i].cancel(true);
p1.shutdownNow();
} catch(Exception e) {
unexpectedException();
} finally {
joinPool(p1);
}
}
/**
* remove(task) removes queued task, and fails to remove active task
*/
public void testRemove() {
BlockingQueue q = new ArrayBlockingQueue(10);
ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, q);
FutureTask[] tasks = new FutureTask[5];
for(int i = 0; i < 5; i++){
tasks[i] = new FutureTask(new MediumPossiblyInterruptedRunnable(), Boolean.TRUE);
p1.execute(tasks[i]);
}
try {
Thread.sleep(SHORT_DELAY_MS);
assertFalse(p1.remove(tasks[0]));
assertTrue(q.contains(tasks[4]));
assertTrue(q.contains(tasks[3]));
assertTrue(p1.remove(tasks[4]));
assertFalse(p1.remove(tasks[4]));
assertFalse(q.contains(tasks[4]));
assertTrue(q.contains(tasks[3]));
assertTrue(p1.remove(tasks[3]));
assertFalse(q.contains(tasks[3]));
} catch(Exception e) {
unexpectedException();
} finally {
joinPool(p1);
}
}
/**
* purge removes cancelled tasks from the queue
*/
public void testPurge() {
ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
FutureTask[] tasks = new FutureTask[5];
for(int i = 0; i < 5; i++){
tasks[i] = new FutureTask(new MediumPossiblyInterruptedRunnable(), Boolean.TRUE);
p1.execute(tasks[i]);
}
tasks[4].cancel(true);
tasks[3].cancel(true);
p1.purge();
long count = p1.getTaskCount();
assertTrue(count >= 2 && count < 5);
joinPool(p1);
}
/**
* shutDownNow returns a list containing tasks that were not run
*/
public void testShutDownNow() {
ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
List l;
try {
for(int i = 0; i < 5; i++)
p1.execute(new MediumPossiblyInterruptedRunnable());
}
finally {
try {
l = p1.shutdownNow();
} catch (SecurityException ok) { return; }
}
assertTrue(p1.isShutdown());
assertTrue(l.size() <= 4);
}
// Exception Tests
/**
* Constructor throws if corePoolSize argument is less than zero
*/
public void testConstructor1() {
try {
new ThreadPoolExecutor(-1,1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if maximumPoolSize is less than zero
*/
public void testConstructor2() {
try {
new ThreadPoolExecutor(1,-1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if maximumPoolSize is equal to zero
*/
public void testConstructor3() {
try {
new ThreadPoolExecutor(1,0,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if keepAliveTime is less than zero
*/
public void testConstructor4() {
try {
new ThreadPoolExecutor(1,2,-1L,TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if corePoolSize is greater than the maximumPoolSize
*/
public void testConstructor5() {
try {
new ThreadPoolExecutor(2,1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if workQueue is set to null
*/
public void testConstructorNullPointerException() {
try {
new ThreadPoolExecutor(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,null);
shouldThrow();
}
catch (NullPointerException success){}
}
/**
* Constructor throws if corePoolSize argument is less than zero
*/
public void testConstructor6() {
try {
new ThreadPoolExecutor(-1,1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory());
shouldThrow();
} catch (IllegalArgumentException success){}
}
/**
* Constructor throws if maximumPoolSize is less than zero
*/
public void testConstructor7() {
try {
new ThreadPoolExecutor(1,-1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if maximumPoolSize is equal to zero
*/
public void testConstructor8() {
try {
new ThreadPoolExecutor(1,0,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if keepAliveTime is less than zero
*/
public void testConstructor9() {
try {
new ThreadPoolExecutor(1,2,-1L,TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if corePoolSize is greater than the maximumPoolSize
*/
public void testConstructor10() {
try {
new ThreadPoolExecutor(2,1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if workQueue is set to null
*/
public void testConstructorNullPointerException2() {
try {
new ThreadPoolExecutor(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,null,new SimpleThreadFactory());
shouldThrow();
}
catch (NullPointerException success){}
}
/**
* Constructor throws if threadFactory is set to null
*/
public void testConstructorNullPointerException3() {
try {
ThreadFactory f = null;
new ThreadPoolExecutor(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(10),f);
shouldThrow();
}
catch (NullPointerException success){}
}
/**
* Constructor throws if corePoolSize argument is less than zero
*/
public void testConstructor11() {
try {
new ThreadPoolExecutor(-1,1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if maximumPoolSize is less than zero
*/
public void testConstructor12() {
try {
new ThreadPoolExecutor(1,-1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if maximumPoolSize is equal to zero
*/
public void testConstructor13() {
try {
new ThreadPoolExecutor(1,0,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if keepAliveTime is less than zero
*/
public void testConstructor14() {
try {
new ThreadPoolExecutor(1,2,-1L,TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if corePoolSize is greater than the maximumPoolSize
*/
public void testConstructor15() {
try {
new ThreadPoolExecutor(2,1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if workQueue is set to null
*/
public void testConstructorNullPointerException4() {
try {
new ThreadPoolExecutor(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,null,new NoOpREHandler());
shouldThrow();
}
catch (NullPointerException success){}
}
/**
* Constructor throws if handler is set to null
*/
public void testConstructorNullPointerException5() {
try {
RejectedExecutionHandler r = null;
new ThreadPoolExecutor(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(10),r);
shouldThrow();
}
catch (NullPointerException success){}
}
/**
* Constructor throws if corePoolSize argument is less than zero
*/
public void testConstructor16() {
try {
new ThreadPoolExecutor(-1,1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if maximumPoolSize is less than zero
*/
public void testConstructor17() {
try {
new ThreadPoolExecutor(1,-1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if maximumPoolSize is equal to zero
*/
public void testConstructor18() {
try {
new ThreadPoolExecutor(1,0,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if keepAliveTime is less than zero
*/
public void testConstructor19() {
try {
new ThreadPoolExecutor(1,2,-1L,TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if corePoolSize is greater than the maximumPoolSize
*/
public void testConstructor20() {
try {
new ThreadPoolExecutor(2,1,LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler());
shouldThrow();
}
catch (IllegalArgumentException success){}
}
/**
* Constructor throws if workQueue is set to null
*/
public void testConstructorNullPointerException6() {
try {
new ThreadPoolExecutor(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,null,new SimpleThreadFactory(),new NoOpREHandler());
shouldThrow();
}
catch (NullPointerException success){}
}
/**
* Constructor throws if handler is set to null
*/
public void testConstructorNullPointerException7() {
try {
RejectedExecutionHandler r = null;
new ThreadPoolExecutor(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(10),new SimpleThreadFactory(),r);
shouldThrow();
}
catch (NullPointerException success){}
}
/**
* Constructor throws if ThreadFactory is set top null
*/
public void testConstructorNullPointerException8() {
try {
ThreadFactory f = null;
new ThreadPoolExecutor(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(10),f,new NoOpREHandler());
shouldThrow();
}
catch (NullPointerException successdn8){}
}
/**
* execute throws RejectedExecutionException
* if saturated.
*/
public void testSaturatedExecute() {
ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1));
try {
for(int i = 0; i < 5; ++i){
p.execute(new MediumRunnable());
}
shouldThrow();
} catch(RejectedExecutionException success){}
joinPool(p);
}
/**
* executor using CallerRunsPolicy runs task if saturated.
*/
public void testSaturatedExecute2() {
RejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy();
ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1), h);
try {
TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
for(int i = 0; i < 5; ++i){
tasks[i] = new TrackedNoOpRunnable();
}
TrackedLongRunnable mr = new TrackedLongRunnable();
p.execute(mr);
for(int i = 0; i < 5; ++i){
p.execute(tasks[i]);
}
for(int i = 1; i < 5; ++i) {
assertTrue(tasks[i].done);
}
try { p.shutdownNow(); } catch(SecurityException ok) { return; }
} catch(RejectedExecutionException ex){
unexpectedException();
} finally {
joinPool(p);
}
}
/**
* executor using DiscardPolicy drops task if saturated.
*/
public void testSaturatedExecute3() {
RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardPolicy();
ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1), h);
try {
TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
for(int i = 0; i < 5; ++i){
tasks[i] = new TrackedNoOpRunnable();
}
p.execute(new TrackedLongRunnable());
for(int i = 0; i < 5; ++i){
p.execute(tasks[i]);
}
for(int i = 0; i < 5; ++i){
assertFalse(tasks[i].done);
}
try { p.shutdownNow(); } catch(SecurityException ok) { return; }
} catch(RejectedExecutionException ex){
unexpectedException();
} finally {
joinPool(p);
}
}
/**
* executor using DiscardOldestPolicy drops oldest task if saturated.
*/
public void testSaturatedExecute4() {
RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardOldestPolicy();
ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1), h);
try {
p.execute(new TrackedLongRunnable());
TrackedLongRunnable r2 = new TrackedLongRunnable();
p.execute(r2);
assertTrue(p.getQueue().contains(r2));
TrackedNoOpRunnable r3 = new TrackedNoOpRunnable();
p.execute(r3);
assertFalse(p.getQueue().contains(r2));
assertTrue(p.getQueue().contains(r3));
try { p.shutdownNow(); } catch(SecurityException ok) { return; }
} catch(RejectedExecutionException ex){
unexpectedException();
} finally {
joinPool(p);
}
}
/**
* execute throws RejectedExecutionException if shutdown
*/
public void testRejectedExecutionExceptionOnShutdown() {
ThreadPoolExecutor tpe =
new ThreadPoolExecutor(1,1,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(1));
try { tpe.shutdown(); } catch(SecurityException ok) { return; }
try {
tpe.execute(new NoOpRunnable());
shouldThrow();
} catch(RejectedExecutionException success){}
joinPool(tpe);
}
/**
* execute using CallerRunsPolicy drops task on shutdown
*/
public void testCallerRunsOnShutdown() {
RejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy();
ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1), h);
try { p.shutdown(); } catch(SecurityException ok) { return; }
try {
TrackedNoOpRunnable r = new TrackedNoOpRunnable();
p.execute(r);
assertFalse(r.done);
} catch(RejectedExecutionException success){
unexpectedException();
} finally {
joinPool(p);
}
}
/**
* execute using DiscardPolicy drops task on shutdown
*/
public void testDiscardOnShutdown() {
RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardPolicy();
ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1), h);
try { p.shutdown(); } catch(SecurityException ok) { return; }
try {
TrackedNoOpRunnable r = new TrackedNoOpRunnable();
p.execute(r);
assertFalse(r.done);
} catch(RejectedExecutionException success){
unexpectedException();
} finally {
joinPool(p);
}
}
/**
* execute using DiscardOldestPolicy drops task on shutdown
*/
public void testDiscardOldestOnShutdown() {
RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardOldestPolicy();
ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1), h);
try { p.shutdown(); } catch(SecurityException ok) { return; }
try {
TrackedNoOpRunnable r = new TrackedNoOpRunnable();
p.execute(r);
assertFalse(r.done);
} catch(RejectedExecutionException success){
unexpectedException();
} finally {
joinPool(p);
}
}
/**
* execute (null) throws NPE
*/
public void testExecuteNull() {
ThreadPoolExecutor tpe = null;
try {
tpe = new ThreadPoolExecutor(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(10));
tpe.execute(null);
shouldThrow();
} catch(NullPointerException success){}
joinPool(tpe);
}
/**
* setCorePoolSize of negative value throws IllegalArgumentException
*/
public void testCorePoolSizeIllegalArgumentException() {
ThreadPoolExecutor tpe = null;
try {
tpe = new ThreadPoolExecutor(1,2,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(10));
} catch(Exception e){}
try {
tpe.setCorePoolSize(-1);
shouldThrow();
} catch(IllegalArgumentException success){
} finally {
try { tpe.shutdown(); } catch(SecurityException ok) { return; }
}
joinPool(tpe);
}
/**
* setMaximumPoolSize(int) throws IllegalArgumentException if
* given a value less the core pool size
*/
public void testMaximumPoolSizeIllegalArgumentException() {
ThreadPoolExecutor tpe = null;
try {
tpe = new ThreadPoolExecutor(2,3,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(10));
} catch(Exception e){}
try {
tpe.setMaximumPoolSize(1);
shouldThrow();
} catch(IllegalArgumentException success){
} finally {
try { tpe.shutdown(); } catch(SecurityException ok) { return; }
}
joinPool(tpe);
}
/**
* setMaximumPoolSize throws IllegalArgumentException
* if given a negative value
*/
public void testMaximumPoolSizeIllegalArgumentException2() {
ThreadPoolExecutor tpe = null;
try {
tpe = new ThreadPoolExecutor(2,3,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(10));
} catch(Exception e){}
try {
tpe.setMaximumPoolSize(-1);
shouldThrow();
} catch(IllegalArgumentException success){
} finally {
try { tpe.shutdown(); } catch(SecurityException ok) { return; }
}
joinPool(tpe);
}
/**
* setKeepAliveTime throws IllegalArgumentException
* when given a negative value
*/
public void testKeepAliveTimeIllegalArgumentException() {
ThreadPoolExecutor tpe = null;
try {
tpe = new ThreadPoolExecutor(2,3,LONG_DELAY_MS, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(10));
} catch(Exception e){}
try {
tpe.setKeepAliveTime(-1,TimeUnit.MILLISECONDS);
shouldThrow();
} catch(IllegalArgumentException success){
} finally {
try { tpe.shutdown(); } catch(SecurityException ok) { return; }
}
joinPool(tpe);
}
/**
* terminated() is called on termination
*/
public void testTerminated() {
ExtendedTPE tpe = new ExtendedTPE();
try { tpe.shutdown(); } catch(SecurityException ok) { return; }
assertTrue(tpe.terminatedCalled);
joinPool(tpe);
}
/**
* beforeExecute and afterExecute are called when executing task
*/
public void testBeforeAfter() {
ExtendedTPE tpe = new ExtendedTPE();
try {
TrackedNoOpRunnable r = new TrackedNoOpRunnable();
tpe.execute(r);
Thread.sleep(SHORT_DELAY_MS);
assertTrue(r.done);
assertTrue(tpe.beforeCalled);
assertTrue(tpe.afterCalled);
try { tpe.shutdown(); } catch(SecurityException ok) { return; }
}
catch(Exception ex) {
unexpectedException();
} finally {
joinPool(tpe);
}
}
/**
* completed submit of callable returns result
*/
public void testSubmitCallable() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
Future future = e.submit(new StringTask());
String result = (String)future.get();
assertSame(TEST_STRING, result);
}
catch (ExecutionException ex) {
unexpectedException();
}
catch (InterruptedException ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* completed submit of runnable returns successfully
*/
public void testSubmitRunnable() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
Future future = e.submit(new NoOpRunnable());
future.get();
assertTrue(future.isDone());
}
catch (ExecutionException ex) {
unexpectedException();
}
catch (InterruptedException ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* completed submit of (runnable, result) returns result
*/
public void testSubmitRunnable2() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
Future future = e.submit(new NoOpRunnable(), TEST_STRING);
String result = (String)future.get();
assertSame(TEST_STRING, result);
}
catch (ExecutionException ex) {
unexpectedException();
}
catch (InterruptedException ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(null) throws NPE
*/
public void testInvokeAny1() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
e.invokeAny(null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(empty collection) throws IAE
*/
public void testInvokeAny2() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
e.invokeAny(new ArrayList());
} catch (IllegalArgumentException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(c) throws NPE if c has null elements
*/
public void testInvokeAny3() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAny(l);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(c) throws ExecutionException if no task completes
*/
public void testInvokeAny4() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
e.invokeAny(l);
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAny(c) returns result of some task
*/
public void testInvokeAny5() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
String result = (String)e.invokeAny(l);
assertSame(TEST_STRING, result);
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(null) throws NPE
*/
public void testInvokeAll1() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
e.invokeAll(null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(empty collection) returns empty collection
*/
public void testInvokeAll2() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
List r = e.invokeAll(new ArrayList());
assertTrue(r.isEmpty());
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(c) throws NPE if c has null elements
*/
public void testInvokeAll3() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAll(l);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* get of element of invokeAll(c) throws exception on failed task
*/
public void testInvokeAll4() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
List result = e.invokeAll(l);
assertEquals(1, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
((Future)it.next()).get();
} catch(ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* invokeAll(c) returns results of all completed tasks
*/
public void testInvokeAll5() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
List result = e.invokeAll(l);
assertEquals(2, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
assertSame(TEST_STRING, ((Future)it.next()).get());
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(null) throws NPE
*/
public void testTimedInvokeAny1() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
e.invokeAny(null, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(,,null) throws NPE
*/
public void testTimedInvokeAnyNullTimeUnit() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
e.invokeAny(l, MEDIUM_DELAY_MS, null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(empty collection) throws IAE
*/
public void testTimedInvokeAny2() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
e.invokeAny(new ArrayList(), MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (IllegalArgumentException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(c) throws NPE if c has null elements
*/
public void testTimedInvokeAny3() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
ex.printStackTrace();
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(c) throws ExecutionException if no task completes
*/
public void testTimedInvokeAny4() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch(ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAny(c) returns result of some task
*/
public void testTimedInvokeAny5() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
String result = (String)e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertSame(TEST_STRING, result);
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(null) throws NPE
*/
public void testTimedInvokeAll1() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
e.invokeAll(null, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(,,null) throws NPE
*/
public void testTimedInvokeAllNullTimeUnit() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
e.invokeAll(l, MEDIUM_DELAY_MS, null);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(empty collection) returns empty collection
*/
public void testTimedInvokeAll2() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
List r = e.invokeAll(new ArrayList(), MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertTrue(r.isEmpty());
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(c) throws NPE if c has null elements
*/
public void testTimedInvokeAll3() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(null);
e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (NullPointerException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* get of element of invokeAll(c) throws exception on failed task
*/
public void testTimedInvokeAll4() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new NPETask());
List result = e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertEquals(1, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
((Future)it.next()).get();
} catch(ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(c) returns results of all completed tasks
*/
public void testTimedInvokeAll5() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(new StringTask());
List result = e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
assertEquals(2, result.size());
for (Iterator it = result.iterator(); it.hasNext();)
assertSame(TEST_STRING, ((Future)it.next()).get());
} catch (ExecutionException success) {
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* timed invokeAll(c) cancels tasks not completed by timeout
*/
public void testTimedInvokeAll6() {
ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
try {
ArrayList l = new ArrayList();
l.add(new StringTask());
l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
l.add(new StringTask());
List result = e.invokeAll(l, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
assertEquals(3, result.size());
Iterator it = result.iterator();
Future f1 = (Future)it.next();
Future f2 = (Future)it.next();
Future f3 = (Future)it.next();
assertTrue(f1.isDone());
assertTrue(f2.isDone());
assertTrue(f3.isDone());
assertFalse(f1.isCancelled());
assertTrue(f2.isCancelled());
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* Execution continues if there is at least one thread even if
* thread factory fails to create more
*/
public void testFailingThreadFactory() {
ExecutorService e = new ThreadPoolExecutor(100, 100, LONG_DELAY_MS, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), new FailingThreadFactory());
try {
ArrayList l = new ArrayList();
for (int k = 0; k < 100; ++k) {
e.execute(new NoOpRunnable());
}
Thread.sleep(LONG_DELAY_MS);
} catch(Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* allowsCoreThreadTimeOut is by default false.
*/
public void testAllowsCoreThreadTimeOut() {
ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 2, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
assertFalse(tpe.allowsCoreThreadTimeOut());
joinPool(tpe);
}
/**
* allowCoreThreadTimeOut(true) causes idle threads to time out
*/
public void testAllowCoreThreadTimeOut_true() {
ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 10, 10, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
tpe.allowCoreThreadTimeOut(true);
tpe.execute(new NoOpRunnable());
try {
Thread.sleep(MEDIUM_DELAY_MS);
assertEquals(0, tpe.getPoolSize());
} catch(InterruptedException e){
unexpectedException();
} finally {
joinPool(tpe);
}
}
/**
* allowCoreThreadTimeOut(false) causes idle threads not to time out
*/
public void testAllowCoreThreadTimeOut_false() {
ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 10, 10, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
tpe.allowCoreThreadTimeOut(false);
tpe.execute(new NoOpRunnable());
try {
Thread.sleep(MEDIUM_DELAY_MS);
assertTrue(tpe.getPoolSize() >= 1);
} catch(InterruptedException e){
unexpectedException();
} finally {
joinPool(tpe);
}
}
/**
* execute allows the same task to be submitted multiple times, even
* if rejected
*/
public void testRejectedRecycledTask() {
final int nTasks = 1000;
final AtomicInteger nRun = new AtomicInteger(0);
final Runnable recycledTask = new Runnable() {
public void run() {
nRun.getAndIncrement();
} };
final ThreadPoolExecutor p =
new ThreadPoolExecutor(1, 30, 60, TimeUnit.SECONDS,
new ArrayBlockingQueue(30));
try {
for (int i = 0; i < nTasks; ++i) {
for (;;) {
try {
p.execute(recycledTask);
break;
}
catch (RejectedExecutionException ignore) {
}
}
}
Thread.sleep(5000); // enough time to run all tasks
assertEquals(nRun.get(), nTasks);
} catch(Exception ex) {
ex.printStackTrace();
unexpectedException();
} finally {
p.shutdown();
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/ExecutorsTest.java 0000644 0017507 0003772 00000050032 10431777323 023730 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.math.BigInteger;
import java.security.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ExecutorsTest extends JSR166TestCase{
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(ExecutorsTest.class);
}
static class TimedCallable implements Callable {
private final ExecutorService exec;
private final Callable func;
private final long msecs;
TimedCallable(ExecutorService exec, Callable func, long msecs) {
this.exec = exec;
this.func = func;
this.msecs = msecs;
}
public Object call() throws Exception {
Future ftask = exec.submit(func);
try {
return ftask.get(msecs, TimeUnit.MILLISECONDS);
} finally {
ftask.cancel(true);
}
}
}
private static class Fib implements Callable {
private final BigInteger n;
Fib(long n) {
if (n < 0) throw new IllegalArgumentException("need non-negative arg, but got " + n);
this.n = BigInteger.valueOf(n);
}
public Object call() {
BigInteger f1 = BigInteger.ONE;
BigInteger f2 = f1;
for (BigInteger i = BigInteger.ZERO; i.compareTo(n) < 0; i = i.add(BigInteger.ONE)) {
BigInteger t = f1.add(f2);
f1 = f2;
f2 = t;
}
return f1;
}
};
/**
* A newCachedThreadPool can execute runnables
*/
public void testNewCachedThreadPool1() {
ExecutorService e = Executors.newCachedThreadPool();
e.execute(new NoOpRunnable());
e.execute(new NoOpRunnable());
e.execute(new NoOpRunnable());
joinPool(e);
}
/**
* A newCachedThreadPool with given ThreadFactory can execute runnables
*/
public void testNewCachedThreadPool2() {
ExecutorService e = Executors.newCachedThreadPool(new SimpleThreadFactory());
e.execute(new NoOpRunnable());
e.execute(new NoOpRunnable());
e.execute(new NoOpRunnable());
joinPool(e);
}
/**
* A newCachedThreadPool with null ThreadFactory throws NPE
*/
public void testNewCachedThreadPool3() {
try {
ExecutorService e = Executors.newCachedThreadPool(null);
shouldThrow();
}
catch(NullPointerException success) {
}
}
/**
* A new SingleThreadExecutor can execute runnables
*/
public void testNewSingleThreadExecutor1() {
ExecutorService e = Executors.newSingleThreadExecutor();
e.execute(new NoOpRunnable());
e.execute(new NoOpRunnable());
e.execute(new NoOpRunnable());
joinPool(e);
}
/**
* A new SingleThreadExecutor with given ThreadFactory can execute runnables
*/
public void testNewSingleThreadExecutor2() {
ExecutorService e = Executors.newSingleThreadExecutor(new SimpleThreadFactory());
e.execute(new NoOpRunnable());
e.execute(new NoOpRunnable());
e.execute(new NoOpRunnable());
joinPool(e);
}
/**
* A new SingleThreadExecutor with null ThreadFactory throws NPE
*/
public void testNewSingleThreadExecutor3() {
try {
ExecutorService e = Executors.newSingleThreadExecutor(null);
shouldThrow();
}
catch(NullPointerException success) {
}
}
/**
* A new SingleThreadExecutor cannot be casted to concrete implementation
*/
public void testCastNewSingleThreadExecutor() {
ExecutorService e = Executors.newSingleThreadExecutor();
try {
ThreadPoolExecutor tpe = (ThreadPoolExecutor)e;
} catch (ClassCastException success) {
} finally {
joinPool(e);
}
}
/**
* A new newFixedThreadPool can execute runnables
*/
public void testNewFixedThreadPool1() {
ExecutorService e = Executors.newFixedThreadPool(2);
e.execute(new NoOpRunnable());
e.execute(new NoOpRunnable());
e.execute(new NoOpRunnable());
joinPool(e);
}
/**
* A new newFixedThreadPool with given ThreadFactory can execute runnables
*/
public void testNewFixedThreadPool2() {
ExecutorService e = Executors.newFixedThreadPool(2, new SimpleThreadFactory());
e.execute(new NoOpRunnable());
e.execute(new NoOpRunnable());
e.execute(new NoOpRunnable());
joinPool(e);
}
/**
* A new newFixedThreadPool with null ThreadFactory throws NPE
*/
public void testNewFixedThreadPool3() {
try {
ExecutorService e = Executors.newFixedThreadPool(2, null);
shouldThrow();
}
catch(NullPointerException success) {
}
}
/**
* A new newFixedThreadPool with 0 threads throws IAE
*/
public void testNewFixedThreadPool4() {
try {
ExecutorService e = Executors.newFixedThreadPool(0);
shouldThrow();
}
catch(IllegalArgumentException success) {
}
}
/**
* An unconfigurable newFixedThreadPool can execute runnables
*/
public void testunconfigurableExecutorService() {
ExecutorService e = Executors.unconfigurableExecutorService(Executors.newFixedThreadPool(2));
e.execute(new NoOpRunnable());
e.execute(new NoOpRunnable());
e.execute(new NoOpRunnable());
joinPool(e);
}
/**
* unconfigurableExecutorService(null) throws NPE
*/
public void testunconfigurableExecutorServiceNPE() {
try {
ExecutorService e = Executors.unconfigurableExecutorService(null);
}
catch (NullPointerException success) {
}
}
/**
* unconfigurableScheduledExecutorService(null) throws NPE
*/
public void testunconfigurableScheduledExecutorServiceNPE() {
try {
ExecutorService e = Executors.unconfigurableScheduledExecutorService(null);
}
catch (NullPointerException success) {
}
}
/**
* a newSingleThreadScheduledExecutor successfully runs delayed task
*/
public void testNewSingleThreadScheduledExecutor() {
try {
TrackedCallable callable = new TrackedCallable();
ScheduledExecutorService p1 = Executors.newSingleThreadScheduledExecutor();
Future f = p1.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
assertFalse(callable.done);
Thread.sleep(MEDIUM_DELAY_MS);
assertTrue(callable.done);
assertEquals(Boolean.TRUE, f.get());
joinPool(p1);
} catch(RejectedExecutionException e){}
catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* a newScheduledThreadPool successfully runs delayed task
*/
public void testnewScheduledThreadPool() {
try {
TrackedCallable callable = new TrackedCallable();
ScheduledExecutorService p1 = Executors.newScheduledThreadPool(2);
Future f = p1.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
assertFalse(callable.done);
Thread.sleep(MEDIUM_DELAY_MS);
assertTrue(callable.done);
assertEquals(Boolean.TRUE, f.get());
joinPool(p1);
} catch(RejectedExecutionException e){}
catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* an unconfigurable newScheduledThreadPool successfully runs delayed task
*/
public void testunconfigurableScheduledExecutorService() {
try {
TrackedCallable callable = new TrackedCallable();
ScheduledExecutorService p1 = Executors.unconfigurableScheduledExecutorService(Executors.newScheduledThreadPool(2));
Future f = p1.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
assertFalse(callable.done);
Thread.sleep(MEDIUM_DELAY_MS);
assertTrue(callable.done);
assertEquals(Boolean.TRUE, f.get());
joinPool(p1);
} catch(RejectedExecutionException e){}
catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* timeouts from execute will time out if they compute too long.
*/
public void testTimedCallable() {
int N = 10000;
ExecutorService executor = Executors.newSingleThreadExecutor();
List tasks = new ArrayList(N);
try {
long startTime = System.currentTimeMillis();
long i = 0;
while (tasks.size() < N) {
tasks.add(new TimedCallable(executor, new Fib(i), 1));
i += 10;
}
int iters = 0;
BigInteger sum = BigInteger.ZERO;
for (Iterator it = tasks.iterator(); it.hasNext();) {
try {
++iters;
sum = sum.add((BigInteger)((Callable)it.next()).call());
}
catch (TimeoutException success) {
assertTrue(iters > 0);
return;
}
catch (Exception e) {
unexpectedException();
}
}
// if by chance we didn't ever time out, total time must be small
long elapsed = System.currentTimeMillis() - startTime;
assertTrue(elapsed < N);
}
finally {
joinPool(executor);
}
}
/**
* ThreadPoolExecutor using defaultThreadFactory has
* specified group, priority, daemon status, and name
*/
public void testDefaultThreadFactory() {
final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
Runnable r = new Runnable() {
public void run() {
try {
Thread current = Thread.currentThread();
threadAssertTrue(!current.isDaemon());
threadAssertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
ThreadGroup g = current.getThreadGroup();
SecurityManager s = System.getSecurityManager();
if (s != null)
threadAssertTrue(g == s.getThreadGroup());
else
threadAssertTrue(g == egroup);
String name = current.getName();
threadAssertTrue(name.endsWith("thread-1"));
} catch (SecurityException ok) {
// Also pass if not allowed to change setting
}
}
};
ExecutorService e = Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
e.execute(r);
try {
e.shutdown();
} catch(SecurityException ok) {
}
try {
Thread.sleep(SHORT_DELAY_MS);
} catch (Exception eX) {
unexpectedException();
} finally {
joinPool(e);
}
}
/**
* ThreadPoolExecutor using privilegedThreadFactory has
* specified group, priority, daemon status, name,
* access control context and context class loader
*/
public void testPrivilegedThreadFactory() {
Policy savedPolicy = null;
try {
savedPolicy = Policy.getPolicy();
AdjustablePolicy policy = new AdjustablePolicy();
policy.addPermission(new RuntimePermission("getContextClassLoader"));
policy.addPermission(new RuntimePermission("setContextClassLoader"));
Policy.setPolicy(policy);
} catch (AccessControlException ok) {
return;
}
final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
final ClassLoader thisccl = Thread.currentThread().getContextClassLoader();
final AccessControlContext thisacc = AccessController.getContext();
Runnable r = new Runnable() {
public void run() {
try {
Thread current = Thread.currentThread();
threadAssertTrue(!current.isDaemon());
threadAssertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
ThreadGroup g = current.getThreadGroup();
SecurityManager s = System.getSecurityManager();
if (s != null)
threadAssertTrue(g == s.getThreadGroup());
else
threadAssertTrue(g == egroup);
String name = current.getName();
threadAssertTrue(name.endsWith("thread-1"));
threadAssertTrue(thisccl == current.getContextClassLoader());
threadAssertTrue(thisacc.equals(AccessController.getContext()));
} catch(SecurityException ok) {
// Also pass if not allowed to change settings
}
}
};
ExecutorService e = Executors.newSingleThreadExecutor(Executors.privilegedThreadFactory());
Policy.setPolicy(savedPolicy);
e.execute(r);
try {
e.shutdown();
} catch(SecurityException ok) {
}
try {
Thread.sleep(SHORT_DELAY_MS);
} catch (Exception ex) {
unexpectedException();
} finally {
joinPool(e);
}
}
void checkCCL() {
AccessController.getContext().checkPermission(new RuntimePermission("getContextClassLoader"));
}
class CheckCCL implements Callable {
public Object call() {
checkCCL();
return null;
}
}
/**
* Without class loader permissions, creating
* privilegedCallableUsingCurrentClassLoader throws ACE
*/
public void testCreatePrivilegedCallableUsingCCLWithNoPrivs() {
Policy savedPolicy = null;
try {
savedPolicy = Policy.getPolicy();
AdjustablePolicy policy = new AdjustablePolicy();
Policy.setPolicy(policy);
} catch (AccessControlException ok) {
return;
}
// Check if program still has too many permissions to run test
try {
checkCCL();
// too many privileges to test; so return
Policy.setPolicy(savedPolicy);
return;
} catch(AccessControlException ok) {
}
try {
Callable task = Executors.privilegedCallableUsingCurrentClassLoader(new NoOpCallable());
shouldThrow();
} catch(AccessControlException success) {
} catch(Exception ex) {
unexpectedException();
}
finally {
Policy.setPolicy(savedPolicy);
}
}
/**
* With class loader permissions, calling
* privilegedCallableUsingCurrentClassLoader does not throw ACE
*/
public void testprivilegedCallableUsingCCLWithPrivs() {
Policy savedPolicy = null;
try {
savedPolicy = Policy.getPolicy();
AdjustablePolicy policy = new AdjustablePolicy();
policy.addPermission(new RuntimePermission("getContextClassLoader"));
policy.addPermission(new RuntimePermission("setContextClassLoader"));
Policy.setPolicy(policy);
} catch (AccessControlException ok) {
return;
}
try {
Callable task = Executors.privilegedCallableUsingCurrentClassLoader(new NoOpCallable());
task.call();
} catch(Exception ex) {
unexpectedException();
}
finally {
Policy.setPolicy(savedPolicy);
}
}
/**
* Without permissions, calling privilegedCallable throws ACE
*/
public void testprivilegedCallableWithNoPrivs() {
Callable task;
Policy savedPolicy = null;
AdjustablePolicy policy = null;
AccessControlContext noprivAcc = null;
try {
savedPolicy = Policy.getPolicy();
policy = new AdjustablePolicy();
Policy.setPolicy(policy);
noprivAcc = AccessController.getContext();
task = Executors.privilegedCallable(new CheckCCL());
Policy.setPolicy(savedPolicy);
} catch (AccessControlException ok) {
return; // program has too few permissions to set up test
}
// Make sure that program doesn't have too many permissions
try {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
checkCCL();
return null;
}}, noprivAcc);
// too many permssions; skip test
return;
} catch(AccessControlException ok) {
}
try {
task.call();
shouldThrow();
} catch(AccessControlException success) {
} catch(Exception ex) {
unexpectedException();
}
}
/**
* With permissions, calling privilegedCallable succeeds
*/
public void testprivilegedCallableWithPrivs() {
Policy savedPolicy = null;
try {
savedPolicy = Policy.getPolicy();
AdjustablePolicy policy = new AdjustablePolicy();
policy.addPermission(new RuntimePermission("getContextClassLoader"));
policy.addPermission(new RuntimePermission("setContextClassLoader"));
Policy.setPolicy(policy);
} catch (AccessControlException ok) {
return;
}
Callable task = Executors.privilegedCallable(new CheckCCL());
try {
task.call();
} catch(Exception ex) {
unexpectedException();
} finally {
Policy.setPolicy(savedPolicy);
}
}
/**
* callable(Runnable) returns null when called
*/
public void testCallable1() {
try {
Callable c = Executors.callable(new NoOpRunnable());
assertNull(c.call());
} catch(Exception ex) {
unexpectedException();
}
}
/**
* callable(Runnable, result) returns result when called
*/
public void testCallable2() {
try {
Callable c = Executors.callable(new NoOpRunnable(), one);
assertEquals(one, c.call());
} catch(Exception ex) {
unexpectedException();
}
}
/**
* callable(PrivilegedAction) returns its result when called
*/
public void testCallable3() {
try {
Callable c = Executors.callable(new PrivilegedAction() {
public Object run() { return one; }});
assertEquals(one, c.call());
} catch(Exception ex) {
unexpectedException();
}
}
/**
* callable(PrivilegedExceptionAction) returns its result when called
*/
public void testCallable4() {
try {
Callable c = Executors.callable(new PrivilegedExceptionAction() {
public Object run() { return one; }});
assertEquals(one, c.call());
} catch(Exception ex) {
unexpectedException();
}
}
/**
* callable(null Runnable) throws NPE
*/
public void testCallableNPE1() {
try {
Runnable r = null;
Callable c = Executors.callable(r);
} catch (NullPointerException success) {
}
}
/**
* callable(null, result) throws NPE
*/
public void testCallableNPE2() {
try {
Runnable r = null;
Callable c = Executors.callable(r, one);
} catch (NullPointerException success) {
}
}
/**
* callable(null PrivilegedAction) throws NPE
*/
public void testCallableNPE3() {
try {
PrivilegedAction r = null;
Callable c = Executors.callable(r);
} catch (NullPointerException success) {
}
}
/**
* callable(null PrivilegedExceptionAction) throws NPE
*/
public void testCallableNPE4() {
try {
PrivilegedExceptionAction r = null;
Callable c = Executors.callable(r);
} catch (NullPointerException success) {
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/LockSupportTest.java 0000644 0017507 0003772 00000010110 10431260156 024214 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
public class LockSupportTest extends JSR166TestCase{
// public static void main(String[] args) {
// junit.textui.TestRunner.run (suite());
// }
// public static Test suite() {
// return new TestSuite(LockSupportTest.class);
// }
//
// /**
// * park is released by unpark occurring after park
// */
// public void testPark() {
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// LockSupport.park();
// } catch(Exception e){
// threadUnexpectedException();
// }
// }
// });
// try {
// t.start();
// Thread.sleep(SHORT_DELAY_MS);
// LockSupport.unpark(t);
// t.join();
// }
// catch(Exception e) {
// unexpectedException();
// }
// }
//
// /**
// * park is released by unpark occurring before park
// */
// public void testPark2() {
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// Thread.sleep(SHORT_DELAY_MS);
// LockSupport.park();
// } catch(Exception e){
// threadUnexpectedException();
// }
// }
// });
// try {
// t.start();
// LockSupport.unpark(t);
// t.join();
// }
// catch(Exception e) {
// unexpectedException();
// }
// }
//
// /**
// * park is released by interrupt
// */
// public void testPark3() {
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// LockSupport.park();
// threadAssertTrue(Thread.interrupted());
// } catch(Exception e){
// threadUnexpectedException();
// }
// }
// });
// try {
// t.start();
// Thread.sleep(SHORT_DELAY_MS);
// t.interrupt();
// t.join();
// }
// catch(Exception e) {
// unexpectedException();
// }
// }
//
// /**
// * park returns if interrupted before park
// */
// public void testPark4() {
// final ReentrantLock lock = new ReentrantLock();
// lock.lock();
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// lock.lock();
// LockSupport.park();
// } catch(Exception e){
// threadUnexpectedException();
// }
// }
// });
// try {
// t.start();
// t.interrupt();
// lock.unlock();
// t.join();
// }
// catch(Exception e) {
// unexpectedException();
// }
// }
//
// /**
// * parkNanos times out if not unparked
// */
// public void testParkNanos() {
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// LockSupport.parkNanos(1000);
// } catch(Exception e){
// threadUnexpectedException();
// }
// }
// });
// try {
// t.start();
// t.join();
// }
// catch(Exception e) {
// unexpectedException();
// }
// }
//
//
// /**
// * parkUntil times out if not unparked
// */
// public void testParkUntil() {
// Thread t = new Thread(new Runnable() {
// public void run() {
// try {
// long d = new Date().getTime() + 100;
// LockSupport.parkUntil(d);
// } catch(Exception e){
// threadUnexpectedException();
// }
// }
// });
// try {
// t.start();
// t.join();
// }
// catch(Exception e) {
// unexpectedException();
// }
// }
}
backport-util-concurrent-3.1-src/test/tck/src/SemaphoreTest.java 0000644 0017507 0003772 00000071725 10431405567 023704 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.io.*;
import java.util.Collection;
public class SemaphoreTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(SemaphoreTest.class);
}
/**
* Subclass to expose protected methods
*/
static class PublicSemaphore extends Semaphore {
PublicSemaphore(int p, boolean f) { super(p, f); }
public Collection getQueuedThreads() {
return super.getQueuedThreads();
}
public void reducePermits(int p) {
super.reducePermits(p);
}
}
/**
* A runnable calling acquire
*/
class InterruptibleLockRunnable implements Runnable {
final Semaphore lock;
InterruptibleLockRunnable(Semaphore l) { lock = l; }
public void run() {
try {
lock.acquire();
} catch(InterruptedException success){}
}
}
/**
* A runnable calling acquire that expects to be
* interrupted
*/
class InterruptedLockRunnable implements Runnable {
final Semaphore lock;
InterruptedLockRunnable(Semaphore l) { lock = l; }
public void run() {
try {
lock.acquire();
threadShouldThrow();
} catch(InterruptedException success){}
}
}
/**
* Zero, negative, and positive initial values are allowed in constructor
*/
public void testConstructor() {
Semaphore s0 = new Semaphore(0, false);
assertEquals(0, s0.availablePermits());
assertFalse(s0.isFair());
Semaphore s1 = new Semaphore(-1, false);
assertEquals(-1, s1.availablePermits());
assertFalse(s1.isFair());
Semaphore s2 = new Semaphore(-1, false);
assertEquals(-1, s2.availablePermits());
assertFalse(s2.isFair());
}
/**
* Constructor without fairness argument behaves as nonfair
*/
public void testConstructor2() {
Semaphore s0 = new Semaphore(0);
assertEquals(0, s0.availablePermits());
assertFalse(s0.isFair());
Semaphore s1 = new Semaphore(-1);
assertEquals(-1, s1.availablePermits());
assertFalse(s1.isFair());
Semaphore s2 = new Semaphore(-1);
assertEquals(-1, s2.availablePermits());
assertFalse(s2.isFair());
}
/**
* tryAcquire succeeds when sufficient permits, else fails
*/
public void testTryAcquireInSameThread() {
Semaphore s = new Semaphore(2, false);
assertEquals(2, s.availablePermits());
assertTrue(s.tryAcquire());
assertTrue(s.tryAcquire());
assertEquals(0, s.availablePermits());
assertFalse(s.tryAcquire());
}
/**
* Acquire and release of semaphore succeed if initially available
*/
public void testAcquireReleaseInSameThread() {
Semaphore s = new Semaphore(1, false);
try {
s.acquire();
s.release();
s.acquire();
s.release();
s.acquire();
s.release();
s.acquire();
s.release();
s.acquire();
s.release();
assertEquals(1, s.availablePermits());
} catch( InterruptedException e){
unexpectedException();
}
}
/**
* Uninterruptible acquire and release of semaphore succeed if
* initially available
*/
public void testAcquireUninterruptiblyReleaseInSameThread() {
Semaphore s = new Semaphore(1, false);
try {
s.acquireUninterruptibly();
s.release();
s.acquireUninterruptibly();
s.release();
s.acquireUninterruptibly();
s.release();
s.acquireUninterruptibly();
s.release();
s.acquireUninterruptibly();
s.release();
assertEquals(1, s.availablePermits());
} finally {
}
}
/**
* Timed Acquire and release of semaphore succeed if
* initially available
*/
public void testTimedAcquireReleaseInSameThread() {
Semaphore s = new Semaphore(1, false);
try {
assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release();
assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release();
assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release();
assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release();
assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release();
assertEquals(1, s.availablePermits());
} catch( InterruptedException e){
unexpectedException();
}
}
/**
* A release in one thread enables an acquire in another thread
*/
public void testAcquireReleaseInDifferentThreads() {
final Semaphore s = new Semaphore(0, false);
Thread t = new Thread(new Runnable() {
public void run() {
try {
s.acquire();
s.release();
s.release();
s.acquire();
} catch(InterruptedException ie){
threadUnexpectedException();
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
s.release();
s.release();
s.acquire();
s.acquire();
s.release();
t.join();
} catch( InterruptedException e){
unexpectedException();
}
}
/**
* A release in one thread enables an uninterruptible acquire in another thread
*/
public void testUninterruptibleAcquireReleaseInDifferentThreads() {
final Semaphore s = new Semaphore(0, false);
Thread t = new Thread(new Runnable() {
public void run() {
s.acquireUninterruptibly();
s.release();
s.release();
s.acquireUninterruptibly();
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
s.release();
s.release();
s.acquireUninterruptibly();
s.acquireUninterruptibly();
s.release();
t.join();
} catch( InterruptedException e){
unexpectedException();
}
}
/**
* A release in one thread enables a timed acquire in another thread
*/
public void testTimedAcquireReleaseInDifferentThreads() {
final Semaphore s = new Semaphore(1, false);
Thread t = new Thread(new Runnable() {
public void run() {
try {
s.release();
threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release();
threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch(InterruptedException ie){
threadUnexpectedException();
}
}
});
try {
t.start();
assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release();
assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release();
s.release();
t.join();
} catch( InterruptedException e){
unexpectedException();
}
}
/**
* A waiting acquire blocks interruptibly
*/
public void testAcquire_InterruptedException() {
final Semaphore s = new Semaphore(0, false);
Thread t = new Thread(new Runnable() {
public void run() {
try {
s.acquire();
threadShouldThrow();
} catch(InterruptedException success){}
}
});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch(InterruptedException e){
unexpectedException();
}
}
/**
* A waiting timed acquire blocks interruptibly
*/
public void testTryAcquire_InterruptedException() {
final Semaphore s = new Semaphore(0, false);
Thread t = new Thread(new Runnable() {
public void run() {
try {
s.tryAcquire(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch(InterruptedException success){
}
}
});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch(InterruptedException e){
unexpectedException();
}
}
/**
* hasQueuedThreads reports whether there are waiting threads
*/
public void testHasQueuedThreads() {
// final Semaphore lock = new Semaphore(1, false);
final Semaphore lock = new Semaphore(1, true);
Thread t1 = new Thread(new InterruptedLockRunnable(lock));
Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
try {
assertFalse(lock.hasQueuedThreads());
lock.acquireUninterruptibly();
t1.start();
Thread.sleep(SHORT_DELAY_MS);
assertTrue(lock.hasQueuedThreads());
t2.start();
Thread.sleep(SHORT_DELAY_MS);
assertTrue(lock.hasQueuedThreads());
t1.interrupt();
Thread.sleep(SHORT_DELAY_MS);
assertTrue(lock.hasQueuedThreads());
lock.release();
Thread.sleep(SHORT_DELAY_MS);
assertFalse(lock.hasQueuedThreads());
t1.join();
t2.join();
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* getQueueLength reports number of waiting threads
*/
public void testGetQueueLength() {
// final Semaphore lock = new Semaphore(1, false);
final Semaphore lock = new Semaphore(1, true);
Thread t1 = new Thread(new InterruptedLockRunnable(lock));
Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
try {
assertEquals(0, lock.getQueueLength());
lock.acquireUninterruptibly();
t1.start();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(1, lock.getQueueLength());
t2.start();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(2, lock.getQueueLength());
t1.interrupt();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(1, lock.getQueueLength());
lock.release();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(0, lock.getQueueLength());
t1.join();
t2.join();
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* getQueuedThreads includes waiting threads
*/
public void testGetQueuedThreads() {
// final PublicSemaphore lock = new PublicSemaphore(1, false);
final PublicSemaphore lock = new PublicSemaphore(1, true);
Thread t1 = new Thread(new InterruptedLockRunnable(lock));
Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
try {
assertTrue(lock.getQueuedThreads().isEmpty());
lock.acquireUninterruptibly();
assertTrue(lock.getQueuedThreads().isEmpty());
t1.start();
Thread.sleep(SHORT_DELAY_MS);
assertTrue(lock.getQueuedThreads().contains(t1));
t2.start();
Thread.sleep(SHORT_DELAY_MS);
assertTrue(lock.getQueuedThreads().contains(t1));
assertTrue(lock.getQueuedThreads().contains(t2));
t1.interrupt();
Thread.sleep(SHORT_DELAY_MS);
assertFalse(lock.getQueuedThreads().contains(t1));
assertTrue(lock.getQueuedThreads().contains(t2));
lock.release();
Thread.sleep(SHORT_DELAY_MS);
assertTrue(lock.getQueuedThreads().isEmpty());
t1.join();
t2.join();
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* drainPermits reports and removes given number of permits
*/
public void testDrainPermits() {
Semaphore s = new Semaphore(0, false);
assertEquals(0, s.availablePermits());
assertEquals(0, s.drainPermits());
s.release(10);
assertEquals(10, s.availablePermits());
assertEquals(10, s.drainPermits());
assertEquals(0, s.availablePermits());
assertEquals(0, s.drainPermits());
}
/**
* reducePermits reduces number of permits
*/
public void testReducePermits() {
PublicSemaphore s = new PublicSemaphore(10, false);
assertEquals(10, s.availablePermits());
s.reducePermits(1);
assertEquals(9, s.availablePermits());
s.reducePermits(10);
assertEquals(-1, s.availablePermits());
}
/**
* a deserialized serialized semaphore has same number of permits
*/
public void testSerialization() {
Semaphore l = new Semaphore(3, false);
try {
l.acquire();
l.release();
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(l);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
Semaphore r = (Semaphore) in.readObject();
assertEquals(3, r.availablePermits());
assertFalse(r.isFair());
r.acquire();
r.release();
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* Zero, negative, and positive initial values are allowed in constructor
*/
public void testConstructor_fair() {
Semaphore s0 = new Semaphore(0, true);
assertEquals(0, s0.availablePermits());
assertTrue(s0.isFair());
Semaphore s1 = new Semaphore(-1, true);
assertEquals(-1, s1.availablePermits());
Semaphore s2 = new Semaphore(-1, true);
assertEquals(-1, s2.availablePermits());
}
/**
* tryAcquire succeeds when sufficient permits, else fails
*/
public void testTryAcquireInSameThread_fair() {
Semaphore s = new Semaphore(2, true);
assertEquals(2, s.availablePermits());
assertTrue(s.tryAcquire());
assertTrue(s.tryAcquire());
assertEquals(0, s.availablePermits());
assertFalse(s.tryAcquire());
}
/**
* tryAcquire(n) succeeds when sufficient permits, else fails
*/
public void testTryAcquireNInSameThread_fair() {
Semaphore s = new Semaphore(2, true);
assertEquals(2, s.availablePermits());
assertTrue(s.tryAcquire(2));
assertEquals(0, s.availablePermits());
assertFalse(s.tryAcquire());
}
/**
* Acquire and release of semaphore succeed if initially available
*/
public void testAcquireReleaseInSameThread_fair() {
Semaphore s = new Semaphore(1, true);
try {
s.acquire();
s.release();
s.acquire();
s.release();
s.acquire();
s.release();
s.acquire();
s.release();
s.acquire();
s.release();
assertEquals(1, s.availablePermits());
} catch( InterruptedException e){
unexpectedException();
}
}
/**
* Acquire(n) and release(n) of semaphore succeed if initially available
*/
public void testAcquireReleaseNInSameThread_fair() {
Semaphore s = new Semaphore(1, true);
try {
s.release(1);
s.acquire(1);
s.release(2);
s.acquire(2);
s.release(3);
s.acquire(3);
s.release(4);
s.acquire(4);
s.release(5);
s.acquire(5);
assertEquals(1, s.availablePermits());
} catch( InterruptedException e){
unexpectedException();
}
}
/**
* Acquire(n) and release(n) of semaphore succeed if initially available
*/
public void testAcquireUninterruptiblyReleaseNInSameThread_fair() {
Semaphore s = new Semaphore(1, true);
try {
s.release(1);
s.acquireUninterruptibly(1);
s.release(2);
s.acquireUninterruptibly(2);
s.release(3);
s.acquireUninterruptibly(3);
s.release(4);
s.acquireUninterruptibly(4);
s.release(5);
s.acquireUninterruptibly(5);
assertEquals(1, s.availablePermits());
} finally {
}
}
/**
* release(n) in one thread enables timed acquire(n) in another thread
*/
public void testTimedAcquireReleaseNInSameThread_fair() {
Semaphore s = new Semaphore(1, true);
try {
s.release(1);
assertTrue(s.tryAcquire(1, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release(2);
assertTrue(s.tryAcquire(2, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release(3);
assertTrue(s.tryAcquire(3, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release(4);
assertTrue(s.tryAcquire(4, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release(5);
assertTrue(s.tryAcquire(5, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
assertEquals(1, s.availablePermits());
} catch( InterruptedException e){
unexpectedException();
}
}
/**
* release in one thread enables timed acquire in another thread
*/
public void testTimedAcquireReleaseInSameThread_fair() {
Semaphore s = new Semaphore(1, true);
try {
assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release();
assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release();
assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release();
assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release();
assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release();
assertEquals(1, s.availablePermits());
} catch( InterruptedException e){
unexpectedException();
}
}
/**
* A release in one thread enables an acquire in another thread
*/
public void testAcquireReleaseInDifferentThreads_fair() {
final Semaphore s = new Semaphore(0, true);
Thread t = new Thread(new Runnable() {
public void run() {
try {
s.acquire();
s.acquire();
s.acquire();
s.acquire();
} catch(InterruptedException ie){
threadUnexpectedException();
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
s.release();
s.release();
s.release();
s.release();
s.release();
s.release();
t.join();
assertEquals(2, s.availablePermits());
} catch( InterruptedException e){
unexpectedException();
}
}
/**
* release(n) in one thread enables acquire(n) in another thread
*/
public void testAcquireReleaseNInDifferentThreads_fair() {
final Semaphore s = new Semaphore(0, true);
Thread t = new Thread(new Runnable() {
public void run() {
try {
s.acquire();
s.release(2);
s.acquire();
} catch(InterruptedException ie){
threadUnexpectedException();
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
s.release(2);
s.acquire(2);
s.release(1);
t.join();
} catch( InterruptedException e){
unexpectedException();
}
}
/**
* release(n) in one thread enables acquire(n) in another thread
*/
public void testAcquireReleaseNInDifferentThreads_fair2() {
final Semaphore s = new Semaphore(0, true);
Thread t = new Thread(new Runnable() {
public void run() {
try {
s.acquire(2);
s.acquire(2);
s.release(4);
} catch(InterruptedException ie){
threadUnexpectedException();
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
s.release(6);
s.acquire(2);
s.acquire(2);
s.release(2);
t.join();
} catch( InterruptedException e){
unexpectedException();
}
}
/**
* release in one thread enables timed acquire in another thread
*/
public void testTimedAcquireReleaseInDifferentThreads_fair() {
final Semaphore s = new Semaphore(1, true);
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch(InterruptedException ie){
threadUnexpectedException();
}
}
});
t.start();
try {
s.release();
s.release();
s.release();
s.release();
s.release();
t.join();
} catch( InterruptedException e){
unexpectedException();
}
}
/**
* release(n) in one thread enables timed acquire(n) in another thread
*/
public void testTimedAcquireReleaseNInDifferentThreads_fair() {
final Semaphore s = new Semaphore(2, true);
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertTrue(s.tryAcquire(2, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release(2);
threadAssertTrue(s.tryAcquire(2, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release(2);
} catch(InterruptedException ie){
threadUnexpectedException();
}
}
});
t.start();
try {
assertTrue(s.tryAcquire(2, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release(2);
assertTrue(s.tryAcquire(2, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
s.release(2);
t.join();
} catch( InterruptedException e){
unexpectedException();
}
}
/**
* A waiting acquire blocks interruptibly
*/
public void testAcquire_InterruptedException_fair() {
final Semaphore s = new Semaphore(0, true);
Thread t = new Thread(new Runnable() {
public void run() {
try {
s.acquire();
threadShouldThrow();
} catch(InterruptedException success){}
}
});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch(InterruptedException e){
unexpectedException();
}
}
/**
* A waiting acquire(n) blocks interruptibly
*/
public void testAcquireN_InterruptedException_fair() {
final Semaphore s = new Semaphore(2, true);
Thread t = new Thread(new Runnable() {
public void run() {
try {
s.acquire(3);
threadShouldThrow();
} catch(InterruptedException success){}
}
});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch(InterruptedException e){
unexpectedException();
}
}
/**
* A waiting tryAcquire blocks interruptibly
*/
public void testTryAcquire_InterruptedException_fair() {
final Semaphore s = new Semaphore(0, true);
Thread t = new Thread(new Runnable() {
public void run() {
try {
s.tryAcquire(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch(InterruptedException success){
}
}
});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch(InterruptedException e){
unexpectedException();
}
}
/**
* A waiting tryAcquire(n) blocks interruptibly
*/
public void testTryAcquireN_InterruptedException_fair() {
final Semaphore s = new Semaphore(1, true);
Thread t = new Thread(new Runnable() {
public void run() {
try {
s.tryAcquire(4, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch(InterruptedException success){
}
}
});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch(InterruptedException e){
unexpectedException();
}
}
/**
* getQueueLength reports number of waiting threads
*/
public void testGetQueueLength_fair() {
final Semaphore lock = new Semaphore(1, true);
Thread t1 = new Thread(new InterruptedLockRunnable(lock));
Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
try {
assertEquals(0, lock.getQueueLength());
lock.acquireUninterruptibly();
t1.start();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(1, lock.getQueueLength());
t2.start();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(2, lock.getQueueLength());
t1.interrupt();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(1, lock.getQueueLength());
lock.release();
Thread.sleep(SHORT_DELAY_MS);
assertEquals(0, lock.getQueueLength());
t1.join();
t2.join();
} catch(Exception e){
unexpectedException();
}
}
/**
* a deserialized serialized semaphore has same number of permits
*/
public void testSerialization_fair() {
Semaphore l = new Semaphore(3, true);
try {
l.acquire();
l.release();
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(l);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
Semaphore r = (Semaphore) in.readObject();
assertEquals(3, r.availablePermits());
assertTrue(r.isFair());
r.acquire();
r.release();
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* toString indicates current number of permits
*/
public void testToString() {
Semaphore s = new Semaphore(0);
String us = s.toString();
assertTrue(us.indexOf("Permits = 0") >= 0);
s.release();
String s1 = s.toString();
assertTrue(s1.indexOf("Permits = 1") >= 0);
s.release();
String s2 = s.toString();
assertTrue(s2.indexOf("Permits = 2") >= 0);
}
}
backport-util-concurrent-3.1-src/test/tck/src/AtomicReferenceFieldUpdaterTest.java 0000644 0017507 0003772 00000013661 10253674160 027277 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
public class AtomicReferenceFieldUpdaterTest extends JSR166TestCase{
// volatile Integer x = null;
// Object z;
// Integer w;
//
// public static void main(String[] args){
// junit.textui.TestRunner.run(suite());
// }
// public static Test suite() {
// return new TestSuite(AtomicReferenceFieldUpdaterTest.class);
// }
//
// /**
// * Construction with non-existent field throws RuntimeException
// */
// public void testConstructor(){
// try{
// AtomicReferenceFieldUpdater
// a = AtomicReferenceFieldUpdater.newUpdater
// (AtomicReferenceFieldUpdaterTest.class, Integer.class, "y");
// shouldThrow();
// }
// catch (RuntimeException rt) {}
// }
//
//
// /**
// * construction with field not of given type throws RuntimeException
// */
// public void testConstructor2(){
// try{
// AtomicReferenceFieldUpdater
// a = AtomicReferenceFieldUpdater.newUpdater
// (AtomicReferenceFieldUpdaterTest.class, Integer.class, "z");
// shouldThrow();
// }
// catch (RuntimeException rt) {}
// }
//
// /**
// * Constructor with non-volatile field throws exception
// */
// public void testConstructor3(){
// try{
// AtomicReferenceFieldUpdater
// a = AtomicReferenceFieldUpdater.newUpdater
// (AtomicReferenceFieldUpdaterTest.class, Integer.class, "w");
// shouldThrow();
// }
// catch (RuntimeException rt) {}
// }
//
// /**
// * get returns the last value set or assigned
// */
// public void testGetSet(){
// AtomicReferenceFieldUpdater a;
// try {
// a = AtomicReferenceFieldUpdater.newUpdater(AtomicReferenceFieldUpdaterTest.class, Integer.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = one;
// assertEquals(one,a.get(this));
// a.set(this,two);
// assertEquals(two,a.get(this));
// a.set(this,-3);
// assertEquals(-3,a.get(this));
// }
//
// /**
// * get returns the last value lazySet by same thread
// */
// public void testGetLazySet(){
// AtomicReferenceFieldUpdatera;
// try {
// a = AtomicReferenceFieldUpdater.newUpdater(AtomicReferenceFieldUpdaterTest.class, Integer.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = one;
// assertEquals(one,a.get(this));
// a.lazySet(this,two);
// assertEquals(two,a.get(this));
// a.lazySet(this,m3);
// assertEquals(m3,a.get(this));
// }
//
// /**
// * compareAndSet succeeds in changing value if equal to expected else fails
// */
// public void testCompareAndSet(){
// AtomicReferenceFieldUpdater a;
// try {
// a = AtomicReferenceFieldUpdater.newUpdater(AtomicReferenceFieldUpdaterTest.class, Integer.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = one;
// assertTrue(a.compareAndSet(this,one,two));
// assertTrue(a.compareAndSet(this,two,m4));
// assertEquals(m4,a.get(this));
// assertFalse(a.compareAndSet(this,m5,seven));
// assertFalse((seven == a.get(this)));
// assertTrue(a.compareAndSet(this,m4,seven));
// assertEquals(seven,a.get(this));
// }
//
// /**
// * compareAndSet in one thread enables another waiting for value
// * to succeed
// */
// public void testCompareAndSetInMultipleThreads() {
// x = one;
// final AtomicReferenceFieldUpdater a;
// try {
// a = AtomicReferenceFieldUpdater.newUpdater(AtomicReferenceFieldUpdaterTest.class, Integer.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
//
// Thread t = new Thread(new Runnable() {
// public void run() {
// while(!a.compareAndSet(AtomicReferenceFieldUpdaterTest.this, two, three)) Thread.yield();
// }});
// try {
// t.start();
// assertTrue(a.compareAndSet(this, one, two));
// t.join(LONG_DELAY_MS);
// assertFalse(t.isAlive());
// assertEquals(a.get(this), three);
// }
// catch(Exception e) {
// unexpectedException();
// }
// }
//
// /**
// * repeated weakCompareAndSet succeeds in changing value when equal
// * to expected
// */
// public void testWeakCompareAndSet(){
// AtomicReferenceFieldUpdater a;
// try {
// a = AtomicReferenceFieldUpdater.newUpdater(AtomicReferenceFieldUpdaterTest.class, Integer.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = one;
// while(!a.weakCompareAndSet(this,one,two));
// while(!a.weakCompareAndSet(this,two,m4));
// assertEquals(m4,a.get(this));
// while(!a.weakCompareAndSet(this,m4,seven));
// assertEquals(seven,a.get(this));
// }
//
// /**
// * getAndSet returns previous value and sets to given value
// */
// public void testGetAndSet(){
// AtomicReferenceFieldUpdater a;
// try {
// a = AtomicReferenceFieldUpdater.newUpdater(AtomicReferenceFieldUpdaterTest.class, Integer.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = one;
// assertEquals(one,a.getAndSet(this, zero));
// assertEquals(zero,a.getAndSet(this,m10));
// assertEquals(m10,a.getAndSet(this,1));
// }
//
}
backport-util-concurrent-3.1-src/test/tck/src/AtomicLongFieldUpdaterTest.java 0000644 0017507 0003772 00000021515 10253674160 026275 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
public class AtomicLongFieldUpdaterTest extends JSR166TestCase {
// volatile long x = 0;
// int z;
// long w;
//
// public static void main(String[] args){
// junit.textui.TestRunner.run(suite());
// }
// public static Test suite() {
// return new TestSuite(AtomicLongFieldUpdaterTest.class);
// }
//
// /**
// * Construction with non-existent field throws RuntimeException
// */
// public void testConstructor(){
// try{
// AtomicLongFieldUpdater
// a = AtomicLongFieldUpdater.newUpdater
// (AtomicLongFieldUpdaterTest.class, "y");
// shouldThrow();
// }
// catch (RuntimeException rt) {}
// }
//
// /**
// * construction with field not of given type throws RuntimeException
// */
// public void testConstructor2(){
// try{
// AtomicLongFieldUpdater
// a = AtomicLongFieldUpdater.newUpdater
// (AtomicLongFieldUpdaterTest.class, "z");
// shouldThrow();
// }
// catch (RuntimeException rt) {}
// }
//
// /**
// * construction with non-volatile field throws RuntimeException
// */
// public void testConstructor3(){
// try{
// AtomicLongFieldUpdater
// a = AtomicLongFieldUpdater.newUpdater
// (AtomicLongFieldUpdaterTest.class, "w");
// shouldThrow();
// }
//
// catch (RuntimeException rt) {}
// }
//
// /**
// * get returns the last value set or assigned
// */
// public void testGetSet(){
// AtomicLongFieldUpdater a;
// try {
// a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertEquals(1,a.get(this));
// a.set(this,2);
// assertEquals(2,a.get(this));
// a.set(this,-3);
// assertEquals(-3,a.get(this));
// }
//
// /**
// * get returns the last value lazySet by same thread
// */
// public void testGetLazySet(){
// AtomicLongFieldUpdater a;
// try {
// a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertEquals(1,a.get(this));
// a.lazySet(this,2);
// assertEquals(2,a.get(this));
// a.lazySet(this,-3);
// assertEquals(-3,a.get(this));
// }
//
// /**
// * compareAndSet succeeds in changing value if equal to expected else fails
// */
// public void testCompareAndSet(){
// AtomicLongFieldUpdater a;
// try {
// a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertTrue(a.compareAndSet(this,1,2));
// assertTrue(a.compareAndSet(this,2,-4));
// assertEquals(-4,a.get(this));
// assertFalse(a.compareAndSet(this,-5,7));
// assertFalse((7 == a.get(this)));
// assertTrue(a.compareAndSet(this,-4,7));
// assertEquals(7,a.get(this));
// }
//
//
// /**
// * compareAndSet in one thread enables another waiting for value
// * to succeed
// */
// public void testCompareAndSetInMultipleThreads() {
// x = 1;
// final AtomicLongFieldUpdater a;
// try {
// a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
//
// Thread t = new Thread(new Runnable() {
// public void run() {
// while(!a.compareAndSet(AtomicLongFieldUpdaterTest.this, 2, 3)) Thread.yield();
// }});
// try {
// t.start();
// assertTrue(a.compareAndSet(this, 1, 2));
// t.join(LONG_DELAY_MS);
// assertFalse(t.isAlive());
// assertEquals(a.get(this), 3);
// }
// catch(Exception e) {
// unexpectedException();
// }
// }
//
// /**
// * repeated weakCompareAndSet succeeds in changing value when equal
// * to expected
// */
// public void testWeakCompareAndSet(){
// AtomicLongFieldUpdater a;
// try {
// a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// while(!a.weakCompareAndSet(this,1,2));
// while(!a.weakCompareAndSet(this,2,-4));
// assertEquals(-4,a.get(this));
// while(!a.weakCompareAndSet(this,-4,7));
// assertEquals(7,a.get(this));
// }
//
// /**
// * getAndSet returns previous value and sets to given value
// */
// public void testGetAndSet(){
// AtomicLongFieldUpdater a;
// try {
// a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertEquals(1,a.getAndSet(this, 0));
// assertEquals(0,a.getAndSet(this,-10));
// assertEquals(-10,a.getAndSet(this,1));
// }
//
// /**
// * getAndAdd returns previous value and adds given value
// */
// public void testGetAndAdd(){
// AtomicLongFieldUpdater a;
// try {
// a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertEquals(1,a.getAndAdd(this,2));
// assertEquals(3,a.get(this));
// assertEquals(3,a.getAndAdd(this,-4));
// assertEquals(-1,a.get(this));
// }
//
// /**
// * getAndDecrement returns previous value and decrements
// */
// public void testGetAndDecrement(){
// AtomicLongFieldUpdater a;
// try {
// a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertEquals(1,a.getAndDecrement(this));
// assertEquals(0,a.getAndDecrement(this));
// assertEquals(-1,a.getAndDecrement(this));
// }
//
// /**
// * getAndIncrement returns previous value and increments
// */
// public void testGetAndIncrement(){
// AtomicLongFieldUpdater a;
// try {
// a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertEquals(1,a.getAndIncrement(this));
// assertEquals(2,a.get(this));
// a.set(this,-2);
// assertEquals(-2,a.getAndIncrement(this));
// assertEquals(-1,a.getAndIncrement(this));
// assertEquals(0,a.getAndIncrement(this));
// assertEquals(1,a.get(this));
// }
//
// /**
// * addAndGet adds given value to current, and returns current value
// */
// public void testAddAndGet(){
// AtomicLongFieldUpdater a;
// try {
// a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertEquals(3,a.addAndGet(this,2));
// assertEquals(3,a.get(this));
// assertEquals(-1,a.addAndGet(this,-4));
// assertEquals(-1,a.get(this));
// }
//
// /**
// * decrementAndGet decrements and returns current value
// */
// public void testDecrementAndGet(){
// AtomicLongFieldUpdater a;
// try {
// a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertEquals(0,a.decrementAndGet(this));
// assertEquals(-1,a.decrementAndGet(this));
// assertEquals(-2,a.decrementAndGet(this));
// assertEquals(-2,a.get(this));
// }
//
// /**
// * incrementAndGet increments and returns current value
// */
// public void testIncrementAndGet(){
// AtomicLongFieldUpdater a;
// try {
// a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
// } catch (RuntimeException ok) {
// return;
// }
// x = 1;
// assertEquals(2,a.incrementAndGet(this));
// assertEquals(2,a.get(this));
// a.set(this,-2);
// assertEquals(-1,a.incrementAndGet(this));
// assertEquals(0,a.incrementAndGet(this));
// assertEquals(1,a.incrementAndGet(this));
// assertEquals(1,a.get(this));
// }
//
}
backport-util-concurrent-3.1-src/test/tck/src/PriorityQueueTest.java 0000644 0017507 0003772 00000034465 10431260156 024600 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.PriorityQueue;
import java.io.*;
import java.util.Comparator;
import java.util.Arrays;
import java.util.Collection;
import java.util.NoSuchElementException;
import java.util.Iterator;
public class PriorityQueueTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(PriorityQueueTest.class);
}
static class MyReverseComparator implements Comparator {
public int compare(Object x, Object y) {
int i = ((Integer)x).intValue();
int j = ((Integer)y).intValue();
if (i < j) return 1;
if (i > j) return -1;
return 0;
}
}
/**
* Create a queue of given size containing consecutive
* Integers 0 ... n.
*/
private PriorityQueue populatedQueue(int n) {
PriorityQueue q = new PriorityQueue(n);
assertTrue(q.isEmpty());
for(int i = n-1; i >= 0; i-=2)
assertTrue(q.offer(new Integer(i)));
for(int i = (n & 1); i < n; i+=2)
assertTrue(q.offer(new Integer(i)));
assertFalse(q.isEmpty());
assertEquals(n, q.size());
return q;
}
/**
* A new queue has unbounded capacity
*/
public void testConstructor1() {
assertEquals(0, new PriorityQueue(SIZE).size());
}
/**
* Constructor throws IAE if capacity argument nonpositive
*/
public void testConstructor2() {
try {
PriorityQueue q = new PriorityQueue(0);
shouldThrow();
}
catch (IllegalArgumentException success) {}
}
/**
* Initializing from null Collection throws NPE
*/
public void testConstructor3() {
try {
PriorityQueue q = new PriorityQueue((Collection)null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from Collection of null elements throws NPE
*/
public void testConstructor4() {
try {
Integer[] ints = new Integer[SIZE];
PriorityQueue q = new PriorityQueue(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from Collection with some null elements throws NPE
*/
public void testConstructor5() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
PriorityQueue q = new PriorityQueue(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Queue contains all elements of collection used to initialize
*/
public void testConstructor6() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
PriorityQueue q = new PriorityQueue(Arrays.asList(ints));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* The comparator used in constructor is used
*/
public void testConstructor7() {
try {
MyReverseComparator cmp = new MyReverseComparator();
PriorityQueue q = new PriorityQueue(SIZE, cmp);
assertEquals(cmp, q.comparator());
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
for (int i = SIZE-1; i >= 0; --i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* isEmpty is true before add, false after
*/
public void testEmpty() {
PriorityQueue q = new PriorityQueue(2);
assertTrue(q.isEmpty());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.add(new Integer(2));
q.remove();
q.remove();
assertTrue(q.isEmpty());
}
/**
* size changes when elements added and removed
*/
public void testSize() {
PriorityQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i, q.size());
q.remove();
}
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
q.add(new Integer(i));
}
}
/**
* offer(null) throws NPE
*/
public void testOfferNull() {
try {
PriorityQueue q = new PriorityQueue(1);
q.offer(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* add(null) throws NPE
*/
public void testAddNull() {
try {
PriorityQueue q = new PriorityQueue(1);
q.add(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* Offer of comparable element succeeds
*/
public void testOffer() {
PriorityQueue q = new PriorityQueue(1);
assertTrue(q.offer(zero));
assertTrue(q.offer(one));
}
/**
* Offer of non-Comparable throws CCE
*/
public void testOfferNonComparable() {
try {
PriorityQueue q = new PriorityQueue(1);
q.offer(new Object());
q.offer(new Object());
q.offer(new Object());
shouldThrow();
}
catch(ClassCastException success) {}
}
/**
* add of comparable succeeds
*/
public void testAdd() {
PriorityQueue q = new PriorityQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
assertTrue(q.add(new Integer(i)));
}
}
/**
* addAll(null) throws NPE
*/
public void testAddAll1() {
try {
PriorityQueue q = new PriorityQueue(1);
q.addAll(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with null elements throws NPE
*/
public void testAddAll2() {
try {
PriorityQueue q = new PriorityQueue(SIZE);
Integer[] ints = new Integer[SIZE];
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with any null elements throws NPE after
* possibly adding some elements
*/
public void testAddAll3() {
try {
PriorityQueue q = new PriorityQueue(SIZE);
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Queue contains all elements of successful addAll
*/
public void testAddAll5() {
try {
Integer[] empty = new Integer[0];
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(SIZE-1-i);
PriorityQueue q = new PriorityQueue(SIZE);
assertFalse(q.addAll(Arrays.asList(empty)));
assertTrue(q.addAll(Arrays.asList(ints)));
for (int i = 0; i < SIZE; ++i)
assertEquals(new Integer(i), q.poll());
}
finally {}
}
/**
* poll succeeds unless empty
*/
public void testPoll() {
PriorityQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.poll()).intValue());
}
assertNull(q.poll());
}
/**
* peek returns next element, or null if empty
*/
public void testPeek() {
PriorityQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.peek()).intValue());
q.poll();
assertTrue(q.peek() == null ||
i != ((Integer)q.peek()).intValue());
}
assertNull(q.peek());
}
/**
* element returns next element, or throws NSEE if empty
*/
public void testElement() {
PriorityQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.element()).intValue());
q.poll();
}
try {
q.element();
shouldThrow();
}
catch (NoSuchElementException success) {}
}
/**
* remove removes next element, or throws NSEE if empty
*/
public void testRemove() {
PriorityQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.remove()).intValue());
}
try {
q.remove();
shouldThrow();
} catch (NoSuchElementException success){
}
}
/**
* remove(x) removes x and returns true if present
*/
public void testRemoveElement() {
PriorityQueue q = populatedQueue(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
assertFalse(q.remove(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* contains(x) reports true when elements added but not yet removed
*/
public void testContains() {
PriorityQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.contains(new Integer(i)));
q.poll();
assertFalse(q.contains(new Integer(i)));
}
}
/**
* clear removes all elements
*/
public void testClear() {
PriorityQueue q = populatedQueue(SIZE);
q.clear();
assertTrue(q.isEmpty());
assertEquals(0, q.size());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.clear();
assertTrue(q.isEmpty());
}
/**
* containsAll(c) is true when c contains a subset of elements
*/
public void testContainsAll() {
PriorityQueue q = populatedQueue(SIZE);
PriorityQueue p = new PriorityQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.containsAll(p));
assertFalse(p.containsAll(q));
p.add(new Integer(i));
}
assertTrue(p.containsAll(q));
}
/**
* retainAll(c) retains only those elements of c and reports true if changed
*/
public void testRetainAll() {
PriorityQueue q = populatedQueue(SIZE);
PriorityQueue p = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
boolean changed = q.retainAll(p);
if (i == 0)
assertFalse(changed);
else
assertTrue(changed);
assertTrue(q.containsAll(p));
assertEquals(SIZE-i, q.size());
p.remove();
}
}
/**
* removeAll(c) removes only those elements of c and reports true if changed
*/
public void testRemoveAll() {
for (int i = 1; i < SIZE; ++i) {
PriorityQueue q = populatedQueue(SIZE);
PriorityQueue p = populatedQueue(i);
assertTrue(q.removeAll(p));
assertEquals(SIZE-i, q.size());
for (int j = 0; j < i; ++j) {
Integer I = (Integer)(p.remove());
assertFalse(q.contains(I));
}
}
}
/**
* toArray contains all elements
*/
public void testToArray() {
PriorityQueue q = populatedQueue(SIZE);
Object[] o = q.toArray();
Arrays.sort(o);
for(int i = 0; i < o.length; i++)
assertEquals(o[i], q.poll());
}
/**
* toArray(a) contains all elements
*/
public void testToArray2() {
PriorityQueue q = populatedQueue(SIZE);
Integer[] ints = new Integer[SIZE];
ints = (Integer[])q.toArray(ints);
Arrays.sort(ints);
for(int i = 0; i < ints.length; i++)
assertEquals(ints[i], q.poll());
}
/**
* iterator iterates through all elements
*/
public void testIterator() {
PriorityQueue q = populatedQueue(SIZE);
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, SIZE);
}
/**
* iterator.remove removes current element
*/
public void testIteratorRemove () {
final PriorityQueue q = new PriorityQueue(3);
q.add(new Integer(2));
q.add(new Integer(1));
q.add(new Integer(3));
Iterator it = q.iterator();
it.next();
it.remove();
it = q.iterator();
assertEquals(it.next(), new Integer(2));
assertEquals(it.next(), new Integer(3));
assertFalse(it.hasNext());
}
/**
* toString contains toStrings of elements
*/
public void testToString() {
PriorityQueue q = populatedQueue(SIZE);
String s = q.toString();
for (int i = 0; i < SIZE; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
/**
* A deserialized serialized queue has same elements
*/
public void testSerialization() {
PriorityQueue q = populatedQueue(SIZE);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
PriorityQueue r = (PriorityQueue)in.readObject();
assertEquals(q.size(), r.size());
while (!q.isEmpty())
assertEquals(q.remove(), r.remove());
} catch(Exception e){
unexpectedException();
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/AtomicIntegerArrayTest.java 0000644 0017507 0003772 00000026074 10431260156 025500 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import java.io.*;
public class AtomicIntegerArrayTest extends JSR166TestCase {
public static void main (String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(AtomicIntegerArrayTest.class);
}
/**
* constructor creates array of given size with all elements zero
*/
public void testConstructor() {
AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
for (int i = 0; i < SIZE; ++i)
assertEquals(0,ai.get(i));
}
/**
* constructor with null array throws NPE
*/
public void testConstructor2NPE() {
try {
int[] a = null;
AtomicIntegerArray ai = new AtomicIntegerArray(a);
} catch (NullPointerException success) {
} catch (Exception ex) {
unexpectedException();
}
}
/**
* constructor with array is of same size and has all elements
*/
public void testConstructor2() {
int[] a = { 17, 3, -42, 99, -7};
AtomicIntegerArray ai = new AtomicIntegerArray(a);
assertEquals(a.length, ai.length());
for (int i = 0; i < a.length; ++i)
assertEquals(a[i], ai.get(i));
}
/**
* get and set for out of bound indices throw IndexOutOfBoundsException
*/
public void testIndexing(){
AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
try {
ai.get(SIZE);
} catch(IndexOutOfBoundsException success){
}
try {
ai.get(-1);
} catch(IndexOutOfBoundsException success){
}
try {
ai.set(SIZE, 0);
} catch(IndexOutOfBoundsException success){
}
try {
ai.set(-1, 0);
} catch(IndexOutOfBoundsException success){
}
}
/**
* get returns the last value set at index
*/
public void testGetSet() {
AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
assertEquals(1,ai.get(i));
ai.set(i, 2);
assertEquals(2,ai.get(i));
ai.set(i, -3);
assertEquals(-3,ai.get(i));
}
}
/**
* get returns the last value lazySet at index by same thread
*/
public void testGetLazySet() {
AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.lazySet(i, 1);
assertEquals(1,ai.get(i));
ai.lazySet(i, 2);
assertEquals(2,ai.get(i));
ai.lazySet(i, -3);
assertEquals(-3,ai.get(i));
}
}
/**
* compareAndSet succeeds in changing value if equal to expected else fails
*/
public void testCompareAndSet() {
AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
assertTrue(ai.compareAndSet(i, 1,2));
assertTrue(ai.compareAndSet(i, 2,-4));
assertEquals(-4,ai.get(i));
assertFalse(ai.compareAndSet(i, -5,7));
assertFalse((7 == ai.get(i)));
assertTrue(ai.compareAndSet(i, -4,7));
assertEquals(7,ai.get(i));
}
}
/**
* compareAndSet in one thread enables another waiting for value
* to succeed
*/
public void testCompareAndSetInMultipleThreads() {
final AtomicIntegerArray a = new AtomicIntegerArray(1);
a.set(0, 1);
Thread t = new Thread(new Runnable() {
public void run() {
while(!a.compareAndSet(0, 2, 3)) Thread.yield();
}});
try {
t.start();
assertTrue(a.compareAndSet(0, 1, 2));
t.join(LONG_DELAY_MS);
assertFalse(t.isAlive());
assertEquals(a.get(0), 3);
}
catch(Exception e) {
unexpectedException();
}
}
/**
* repeated weakCompareAndSet succeeds in changing value when equal
* to expected
*/
public void testWeakCompareAndSet() {
AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
while(!ai.weakCompareAndSet(i, 1,2));
while(!ai.weakCompareAndSet(i, 2,-4));
assertEquals(-4,ai.get(i));
while(!ai.weakCompareAndSet(i, -4,7));
assertEquals(7,ai.get(i));
}
}
/**
* getAndSet returns previous value and sets to given value at given index
*/
public void testGetAndSet() {
AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
assertEquals(1,ai.getAndSet(i,0));
assertEquals(0,ai.getAndSet(i,-10));
assertEquals(-10,ai.getAndSet(i,1));
}
}
/**
* getAndAdd returns previous value and adds given value
*/
public void testGetAndAdd() {
AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
assertEquals(1,ai.getAndAdd(i,2));
assertEquals(3,ai.get(i));
assertEquals(3,ai.getAndAdd(i,-4));
assertEquals(-1,ai.get(i));
}
}
/**
* getAndDecrement returns previous value and decrements
*/
public void testGetAndDecrement() {
AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
assertEquals(1,ai.getAndDecrement(i));
assertEquals(0,ai.getAndDecrement(i));
assertEquals(-1,ai.getAndDecrement(i));
}
}
/**
* getAndIncrement returns previous value and increments
*/
public void testGetAndIncrement() {
AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
assertEquals(1,ai.getAndIncrement(i));
assertEquals(2,ai.get(i));
ai.set(i,-2);
assertEquals(-2,ai.getAndIncrement(i));
assertEquals(-1,ai.getAndIncrement(i));
assertEquals(0,ai.getAndIncrement(i));
assertEquals(1,ai.get(i));
}
}
/**
* addAndGet adds given value to current, and returns current value
*/
public void testAddAndGet() {
AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
assertEquals(3,ai.addAndGet(i,2));
assertEquals(3,ai.get(i));
assertEquals(-1,ai.addAndGet(i,-4));
assertEquals(-1,ai.get(i));
}
}
/**
* decrementAndGet decrements and returns current value
*/
public void testDecrementAndGet() {
AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
assertEquals(0,ai.decrementAndGet(i));
assertEquals(-1,ai.decrementAndGet(i));
assertEquals(-2,ai.decrementAndGet(i));
assertEquals(-2,ai.get(i));
}
}
/**
* incrementAndGet increments and returns current value
*/
public void testIncrementAndGet() {
AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, 1);
assertEquals(2,ai.incrementAndGet(i));
assertEquals(2,ai.get(i));
ai.set(i, -2);
assertEquals(-1,ai.incrementAndGet(i));
assertEquals(0,ai.incrementAndGet(i));
assertEquals(1,ai.incrementAndGet(i));
assertEquals(1,ai.get(i));
}
}
static final int COUNTDOWN = 100000;
class Counter implements Runnable {
final AtomicIntegerArray ai;
volatile int counts;
Counter(AtomicIntegerArray a) { ai = a; }
public void run() {
for (;;) {
boolean done = true;
for (int i = 0; i < ai.length(); ++i) {
int v = ai.get(i);
threadAssertTrue(v >= 0);
if (v != 0) {
done = false;
if (ai.compareAndSet(i, v, v-1))
++counts;
}
}
if (done)
break;
}
}
}
/**
* Multiple threads using same array of counters successfully
* update a number of times equal to total count
*/
public void testCountingInMultipleThreads() {
try {
final AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
for (int i = 0; i < SIZE; ++i)
ai.set(i, COUNTDOWN);
Counter c1 = new Counter(ai);
Counter c2 = new Counter(ai);
Thread t1 = new Thread(c1);
Thread t2 = new Thread(c2);
t1.start();
t2.start();
t1.join();
t2.join();
assertEquals(c1.counts+c2.counts, SIZE * COUNTDOWN);
}
catch(InterruptedException ie) {
unexpectedException();
}
}
/**
* a deserialized serialized array holds same values
*/
public void testSerialization() {
AtomicIntegerArray l = new AtomicIntegerArray(SIZE);
for (int i = 0; i < SIZE; ++i)
l.set(i, -i);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(l);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
AtomicIntegerArray r = (AtomicIntegerArray) in.readObject();
for (int i = 0; i < SIZE; ++i) {
assertEquals(l.get(i), r.get(i));
}
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* toString returns current value.
*/
public void testToString() {
int[] a = { 17, 3, -42, 99, -7};
AtomicIntegerArray ai = new AtomicIntegerArray(a);
assertEquals(toString(a), ai.toString());
}
private static String toString(int[] array) {
if (array.length == 0)
return "[]";
StringBuffer buf = new StringBuffer();
buf.append('[');
buf.append(array[0]);
for (int i = 1; i < array.length; i++) {
buf.append(", ");
buf.append(array[i]);
}
buf.append("]");
return buf.toString();
}
}
backport-util-concurrent-3.1-src/test/tck/src/AtomicReferenceArrayTest.java 0000644 0017507 0003772 00000016070 10253674160 026002 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import java.io.*;
import edu.emory.mathcs.backport.java.util.*;
public class AtomicReferenceArrayTest extends JSR166TestCase
{
public static void main (String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(AtomicReferenceArrayTest.class);
}
/**
* constructor creates array of given size with all elements null
*/
public void testConstructor(){
AtomicReferenceArray ai = new AtomicReferenceArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertNull(ai.get(i));
}
}
/**
* constructor with null array throws NPE
*/
public void testConstructor2NPE() {
try {
Integer[] a = null;
AtomicReferenceArray ai = new AtomicReferenceArray(a);
} catch (NullPointerException success) {
} catch (Exception ex) {
unexpectedException();
}
}
/**
* constructor with array is of same size and has all elements
*/
public void testConstructor2() {
Integer[] a = { two, one, three, four, seven};
AtomicReferenceArray ai = new AtomicReferenceArray(a);
assertEquals(a.length, ai.length());
for (int i = 0; i < a.length; ++i)
assertEquals(a[i], ai.get(i));
}
/**
* get and set for out of bound indices throw IndexOutOfBoundsException
*/
public void testIndexing(){
AtomicReferenceArray ai = new AtomicReferenceArray(SIZE);
try {
ai.get(SIZE);
} catch(IndexOutOfBoundsException success){
}
try {
ai.get(-1);
} catch(IndexOutOfBoundsException success){
}
try {
ai.set(SIZE, null);
} catch(IndexOutOfBoundsException success){
}
try {
ai.set(-1, null);
} catch(IndexOutOfBoundsException success){
}
}
/**
* get returns the last value set at index
*/
public void testGetSet(){
AtomicReferenceArray ai = new AtomicReferenceArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, one);
assertEquals(one,ai.get(i));
ai.set(i, two);
assertEquals(two,ai.get(i));
ai.set(i, m3);
assertEquals(m3,ai.get(i));
}
}
/**
* get returns the last value lazySet at index by same thread
*/
public void testGetLazySet(){
AtomicReferenceArray ai = new AtomicReferenceArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.lazySet(i, one);
assertEquals(one,ai.get(i));
ai.lazySet(i, two);
assertEquals(two,ai.get(i));
ai.lazySet(i, m3);
assertEquals(m3,ai.get(i));
}
}
/**
* compareAndSet succeeds in changing value if equal to expected else fails
*/
public void testCompareAndSet(){
AtomicReferenceArray ai = new AtomicReferenceArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, one);
assertTrue(ai.compareAndSet(i, one,two));
assertTrue(ai.compareAndSet(i, two,m4));
assertEquals(m4,ai.get(i));
assertFalse(ai.compareAndSet(i, m5,seven));
assertFalse((seven.equals(ai.get(i))));
assertTrue(ai.compareAndSet(i, m4,seven));
assertEquals(seven,ai.get(i));
}
}
/**
* compareAndSet in one thread enables another waiting for value
* to succeed
*/
public void testCompareAndSetInMultipleThreads() {
final AtomicReferenceArray a = new AtomicReferenceArray(1);
a.set(0, one);
Thread t = new Thread(new Runnable() {
public void run() {
while(!a.compareAndSet(0, two, three)) Thread.yield();
}});
try {
t.start();
assertTrue(a.compareAndSet(0, one, two));
t.join(LONG_DELAY_MS);
assertFalse(t.isAlive());
assertEquals(a.get(0), three);
}
catch(Exception e) {
unexpectedException();
}
}
/**
* repeated weakCompareAndSet succeeds in changing value when equal
* to expected
*/
public void testWeakCompareAndSet(){
AtomicReferenceArray ai = new AtomicReferenceArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, one);
while(!ai.weakCompareAndSet(i, one,two));
while(!ai.weakCompareAndSet(i, two,m4));
assertEquals(m4,ai.get(i));
while(!ai.weakCompareAndSet(i, m4,seven));
assertEquals(seven,ai.get(i));
}
}
/**
* getAndSet returns previous value and sets to given value at given index
*/
public void testGetAndSet(){
AtomicReferenceArray ai = new AtomicReferenceArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
ai.set(i, one);
assertEquals(one,ai.getAndSet(i,zero));
assertEquals(0,((Integer)ai.getAndSet(i,m10)).intValue());
assertEquals(m10,ai.getAndSet(i,one));
}
}
/**
* a deserialized serialized array holds same values
*/
public void testSerialization() {
AtomicReferenceArray l = new AtomicReferenceArray(SIZE);
for (int i = 0; i < SIZE; ++i) {
l.set(i, new Integer(-i));
}
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(l);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
AtomicReferenceArray r = (AtomicReferenceArray) in.readObject();
assertEquals(l.length(), r.length());
for (int i = 0; i < SIZE; ++i) {
assertEquals(r.get(i), l.get(i));
}
} catch(Exception e){
unexpectedException();
}
}
/**
* toString returns current value.
*/
public void testToString() {
Integer[] a = { two, one, three, four, seven};
AtomicReferenceArray ai = new AtomicReferenceArray(a);
assertEquals(toString(a), ai.toString());
}
private static String toString(Integer[] array) {
if (array.length == 0)
return "[]";
StringBuffer buf = new StringBuffer();
buf.append('[');
buf.append(array[0]);
for (int i = 1; i < array.length; i++) {
buf.append(", ");
buf.append(array[i]);
}
buf.append("]");
return buf.toString();
}
}
backport-util-concurrent-3.1-src/test/tck/src/AtomicReferenceTest.java 0000644 0017507 0003772 00000010631 10253674160 025000 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import java.io.*;
public class AtomicReferenceTest extends JSR166TestCase {
public static void main (String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(AtomicReferenceTest.class);
}
/**
* constructor initializes to given value
*/
public void testConstructor(){
AtomicReference ai = new AtomicReference(one);
assertEquals(one,ai.get());
}
/**
* default constructed initializes to null
*/
public void testConstructor2(){
AtomicReference ai = new AtomicReference();
assertNull(ai.get());
}
/**
* get returns the last value set
*/
public void testGetSet(){
AtomicReference ai = new AtomicReference(one);
assertEquals(one,ai.get());
ai.set(two);
assertEquals(two,ai.get());
ai.set(m3);
assertEquals(m3,ai.get());
}
/**
* get returns the last value lazySet in same thread
*/
public void testGetLazySet(){
AtomicReference ai = new AtomicReference(one);
assertEquals(one,ai.get());
ai.lazySet(two);
assertEquals(two,ai.get());
ai.lazySet(m3);
assertEquals(m3,ai.get());
}
/**
* compareAndSet succeeds in changing value if equal to expected else fails
*/
public void testCompareAndSet(){
AtomicReference ai = new AtomicReference(one);
assertTrue(ai.compareAndSet(one,two));
assertTrue(ai.compareAndSet(two,m4));
assertEquals(m4,ai.get());
assertFalse(ai.compareAndSet(m5,seven));
assertFalse((seven.equals(ai.get())));
assertTrue(ai.compareAndSet(m4,seven));
assertEquals(seven,ai.get());
}
/**
* compareAndSet in one thread enables another waiting for value
* to succeed
*/
public void testCompareAndSetInMultipleThreads() {
final AtomicReference ai = new AtomicReference(one);
Thread t = new Thread(new Runnable() {
public void run() {
while(!ai.compareAndSet(two, three)) Thread.yield();
}});
try {
t.start();
assertTrue(ai.compareAndSet(one, two));
t.join(LONG_DELAY_MS);
assertFalse(t.isAlive());
assertEquals(ai.get(), three);
}
catch(Exception e) {
unexpectedException();
}
}
/**
* repeated weakCompareAndSet succeeds in changing value when equal
* to expected
*/
public void testWeakCompareAndSet(){
AtomicReference ai = new AtomicReference(one);
while(!ai.weakCompareAndSet(one,two));
while(!ai.weakCompareAndSet(two,m4));
assertEquals(m4,ai.get());
while(!ai.weakCompareAndSet(m4,seven));
assertEquals(seven,ai.get());
}
/**
* getAndSet returns previous value and sets to given value
*/
public void testGetAndSet(){
AtomicReference ai = new AtomicReference(one);
assertEquals(one,ai.getAndSet(zero));
assertEquals(zero,ai.getAndSet(m10));
assertEquals(m10,ai.getAndSet(one));
}
/**
* a deserialized serialized atomic holds same value
*/
public void testSerialization() {
AtomicReference l = new AtomicReference();
try {
l.set(one);
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(l);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
AtomicReference r = (AtomicReference) in.readObject();
assertEquals(l.get(), r.get());
} catch(Exception e){
unexpectedException();
}
}
/**
* toString returns current value.
*/
public void testToString() {
AtomicReference ai = new AtomicReference(one);
assertEquals(ai.toString(), one.toString());
ai.set(two);
assertEquals(ai.toString(), two.toString());
}
}
backport-util-concurrent-3.1-src/test/tck/src/ArrayBlockingQueueTest.java 0000644 0017507 0003772 00000075706 10365510635 025517 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.io.*;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.Iterator;
import java.util.ConcurrentModificationException;
public class ArrayBlockingQueueTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(ArrayBlockingQueueTest.class);
}
/**
* Create a queue of given size containing consecutive
* Integers 0 ... n.
*/
private ArrayBlockingQueue populatedQueue(int n) {
ArrayBlockingQueue q = new ArrayBlockingQueue(n);
assertTrue(q.isEmpty());
for(int i = 0; i < n; i++)
assertTrue(q.offer(new Integer(i)));
assertFalse(q.isEmpty());
assertEquals(0, q.remainingCapacity());
assertEquals(n, q.size());
return q;
}
/**
* A new queue has the indicated capacity
*/
public void testConstructor1() {
assertEquals(SIZE, new ArrayBlockingQueue(SIZE).remainingCapacity());
}
/**
* Constructor throws IAE if capacity argument nonpositive
*/
public void testConstructor2() {
try {
ArrayBlockingQueue q = new ArrayBlockingQueue(0);
shouldThrow();
}
catch (IllegalArgumentException success) {}
}
/**
* Initializing from null Collection throws NPE
*/
public void testConstructor3() {
try {
ArrayBlockingQueue q = new ArrayBlockingQueue(1, true, null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from Collection of null elements throws NPE
*/
public void testConstructor4() {
try {
Integer[] ints = new Integer[SIZE];
ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, false, Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from Collection with some null elements throws NPE
*/
public void testConstructor5() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, false, Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Initializing from too large collection throws IAE
*/
public void testConstructor6() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
ArrayBlockingQueue q = new ArrayBlockingQueue(1, false, Arrays.asList(ints));
shouldThrow();
}
catch (IllegalArgumentException success) {}
}
/**
* Queue contains all elements of collection used to initialize
*/
public void testConstructor7() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, true, Arrays.asList(ints));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* Queue transitions from empty to full when elements added
*/
public void testEmptyFull() {
ArrayBlockingQueue q = new ArrayBlockingQueue(2);
assertTrue(q.isEmpty());
assertEquals(2, q.remainingCapacity());
q.add(one);
assertFalse(q.isEmpty());
q.add(two);
assertFalse(q.isEmpty());
assertEquals(0, q.remainingCapacity());
assertFalse(q.offer(three));
}
/**
* remainingCapacity decreases on add, increases on remove
*/
public void testRemainingCapacity() {
ArrayBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.remainingCapacity());
assertEquals(SIZE-i, q.size());
q.remove();
}
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i, q.remainingCapacity());
assertEquals(i, q.size());
q.add(new Integer(i));
}
}
/**
* offer(null) throws NPE
*/
public void testOfferNull() {
try {
ArrayBlockingQueue q = new ArrayBlockingQueue(1);
q.offer(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* add(null) throws NPE
*/
public void testAddNull() {
try {
ArrayBlockingQueue q = new ArrayBlockingQueue(1);
q.add(null);
shouldThrow();
} catch (NullPointerException success) { }
}
/**
* Offer succeeds if not full; fails if full
*/
public void testOffer() {
ArrayBlockingQueue q = new ArrayBlockingQueue(1);
assertTrue(q.offer(zero));
assertFalse(q.offer(one));
}
/**
* add succeeds if not full; throws ISE if full
*/
public void testAdd() {
try {
ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.add(new Integer(i)));
}
assertEquals(0, q.remainingCapacity());
q.add(new Integer(SIZE));
} catch (IllegalStateException success){
}
}
/**
* addAll(null) throws NPE
*/
public void testAddAll1() {
try {
ArrayBlockingQueue q = new ArrayBlockingQueue(1);
q.addAll(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll(this) throws IAE
*/
public void testAddAllSelf() {
try {
ArrayBlockingQueue q = populatedQueue(SIZE);
q.addAll(q);
shouldThrow();
}
catch (IllegalArgumentException success) {}
}
/**
* addAll of a collection with null elements throws NPE
*/
public void testAddAll2() {
try {
ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
Integer[] ints = new Integer[SIZE];
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll of a collection with any null elements throws NPE after
* possibly adding some elements
*/
public void testAddAll3() {
try {
ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* addAll throws ISE if not enough room
*/
public void testAddAll4() {
try {
ArrayBlockingQueue q = new ArrayBlockingQueue(1);
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch (IllegalStateException success) {}
}
/**
* Queue contains all elements, in traversal order, of successful addAll
*/
public void testAddAll5() {
try {
Integer[] empty = new Integer[0];
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
assertFalse(q.addAll(Arrays.asList(empty)));
assertTrue(q.addAll(Arrays.asList(ints)));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* put(null) throws NPE
*/
public void testPutNull() {
try {
ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
q.put(null);
shouldThrow();
}
catch (NullPointerException success){
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* all elements successfully put are contained
*/
public void testPut() {
try {
ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
Integer I = new Integer(i);
q.put(I);
assertTrue(q.contains(I));
}
assertEquals(0, q.remainingCapacity());
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* put blocks interruptibly if full
*/
public void testBlockingPut() {
final ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
Thread t = new Thread(new Runnable() {
public void run() {
int added = 0;
try {
for (int i = 0; i < SIZE; ++i) {
q.put(new Integer(i));
++added;
}
q.put(new Integer(SIZE));
threadShouldThrow();
} catch (InterruptedException ie){
threadAssertEquals(added, SIZE);
}
}});
try {
t.start();
Thread.sleep(MEDIUM_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* put blocks waiting for take when full
*/
public void testPutWithTake() {
final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
Thread t = new Thread(new Runnable() {
public void run() {
int added = 0;
try {
q.put(new Object());
++added;
q.put(new Object());
++added;
q.put(new Object());
++added;
q.put(new Object());
++added;
threadShouldThrow();
} catch (InterruptedException e){
threadAssertTrue(added >= 2);
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
q.take();
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* timed offer times out if full and elements not taken
*/
public void testTimedOffer() {
final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.put(new Object());
q.put(new Object());
threadAssertFalse(q.offer(new Object(), SHORT_DELAY_MS/2, TimeUnit.MILLISECONDS));
q.offer(new Object(), LONG_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch (InterruptedException success){}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* take retrieves elements in FIFO order
*/
public void testTake() {
try {
ArrayBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.take()).intValue());
}
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* take blocks interruptibly when empty
*/
public void testTakeFromEmpty() {
final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.take();
threadShouldThrow();
} catch (InterruptedException success){ }
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* Take removes existing elements until empty, then blocks interruptibly
*/
public void testBlockingTake() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
ArrayBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
threadAssertEquals(i, ((Integer)q.take()).intValue());
}
q.take();
threadShouldThrow();
} catch (InterruptedException success){
}
}});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* poll succeeds unless empty
*/
public void testPoll() {
ArrayBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.poll()).intValue());
}
assertNull(q.poll());
}
/**
* timed pool with zero timeout succeeds when non-empty, else times out
*/
public void testTimedPoll0() {
try {
ArrayBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.poll(0, TimeUnit.MILLISECONDS)).intValue());
}
assertNull(q.poll(0, TimeUnit.MILLISECONDS));
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* timed pool with nonzero timeout succeeds when non-empty, else times out
*/
public void testTimedPoll() {
try {
ArrayBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
}
assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* Interrupted timed poll throws InterruptedException instead of
* returning timeout status
*/
public void testInterruptedTimedPoll() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
ArrayBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
threadAssertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
}
threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
} catch (InterruptedException success){
}
}});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
}
catch (InterruptedException ie) {
unexpectedException();
}
}
/**
* timed poll before a delayed offer fails; after offer succeeds;
* on interruption throws
*/
public void testTimedPollWithOffer() {
final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
Thread t = new Thread(new Runnable() {
public void run() {
try {
threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch (InterruptedException success) { }
}
});
try {
t.start();
Thread.sleep(SMALL_DELAY_MS);
assertTrue(q.offer(zero, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
t.interrupt();
t.join();
} catch (Exception e){
unexpectedException();
}
}
/**
* peek returns next element, or null if empty
*/
public void testPeek() {
ArrayBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.peek()).intValue());
q.poll();
assertTrue(q.peek() == null ||
i != ((Integer)q.peek()).intValue());
}
assertNull(q.peek());
}
/**
* element returns next element, or throws NSEE if empty
*/
public void testElement() {
ArrayBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.element()).intValue());
q.poll();
}
try {
q.element();
shouldThrow();
}
catch (NoSuchElementException success) {}
}
/**
* remove removes next element, or throws NSEE if empty
*/
public void testRemove() {
ArrayBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.remove()).intValue());
}
try {
q.remove();
shouldThrow();
} catch (NoSuchElementException success){
}
}
/**
* remove(x) removes x and returns true if present
*/
public void testRemoveElement() {
ArrayBlockingQueue q = populatedQueue(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
assertFalse(q.remove(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* contains(x) reports true when elements added but not yet removed
*/
public void testContains() {
ArrayBlockingQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.contains(new Integer(i)));
q.poll();
assertFalse(q.contains(new Integer(i)));
}
}
/**
* clear removes all elements
*/
public void testClear() {
ArrayBlockingQueue q = populatedQueue(SIZE);
q.clear();
assertTrue(q.isEmpty());
assertEquals(0, q.size());
assertEquals(SIZE, q.remainingCapacity());
q.add(one);
assertFalse(q.isEmpty());
assertTrue(q.contains(one));
q.clear();
assertTrue(q.isEmpty());
}
/**
* containsAll(c) is true when c contains a subset of elements
*/
public void testContainsAll() {
ArrayBlockingQueue q = populatedQueue(SIZE);
ArrayBlockingQueue p = new ArrayBlockingQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.containsAll(p));
assertFalse(p.containsAll(q));
p.add(new Integer(i));
}
assertTrue(p.containsAll(q));
}
/**
* retainAll(c) retains only those elements of c and reports true if changed
*/
public void testRetainAll() {
ArrayBlockingQueue q = populatedQueue(SIZE);
ArrayBlockingQueue p = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
boolean changed = q.retainAll(p);
if (i == 0)
assertFalse(changed);
else
assertTrue(changed);
assertTrue(q.containsAll(p));
assertEquals(SIZE-i, q.size());
p.remove();
}
}
/**
* removeAll(c) removes only those elements of c and reports true if changed
*/
public void testRemoveAll() {
for (int i = 1; i < SIZE; ++i) {
ArrayBlockingQueue q = populatedQueue(SIZE);
ArrayBlockingQueue p = populatedQueue(i);
assertTrue(q.removeAll(p));
assertEquals(SIZE-i, q.size());
for (int j = 0; j < i; ++j) {
Integer I = (Integer)(p.remove());
assertFalse(q.contains(I));
}
}
}
/**
* toArray contains all elements
*/
public void testToArray() {
ArrayBlockingQueue q = populatedQueue(SIZE);
Object[] o = q.toArray();
try {
for(int i = 0; i < o.length; i++)
assertEquals(o[i], q.take());
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* toArray(a) contains all elements
*/
public void testToArray2() {
ArrayBlockingQueue q = populatedQueue(SIZE);
Integer[] ints = new Integer[SIZE];
ints = (Integer[])q.toArray(ints);
try {
for(int i = 0; i < ints.length; i++)
assertEquals(ints[i], q.take());
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* toArray(null) throws NPE
*/
public void testToArray_BadArg() {
try {
ArrayBlockingQueue q = populatedQueue(SIZE);
Object o[] = q.toArray(null);
shouldThrow();
} catch(NullPointerException success){}
}
/**
* toArray with incompatible array type throws CCE
*/
public void testToArray1_BadArg() {
try {
ArrayBlockingQueue q = populatedQueue(SIZE);
Object o[] = q.toArray(new String[10] );
shouldThrow();
} catch(ArrayStoreException success){}
}
/**
* iterator iterates through all elements
*/
public void testIterator() {
ArrayBlockingQueue q = populatedQueue(SIZE);
Iterator it = q.iterator();
try {
while(it.hasNext()){
assertEquals(it.next(), q.take());
}
} catch (InterruptedException e){
unexpectedException();
}
}
/**
* iterator.remove removes current element
*/
public void testIteratorRemove () {
final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
q.add(two);
q.add(one);
q.add(three);
Iterator it = q.iterator();
it.next();
it.remove();
it = q.iterator();
assertEquals(it.next(), one);
assertEquals(it.next(), three);
assertFalse(it.hasNext());
}
/**
* iterator ordering is FIFO
*/
public void testIteratorOrdering() {
final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
q.add(one);
q.add(two);
q.add(three);
assertEquals("queue should be full", 0, q.remainingCapacity());
int k = 0;
for (Iterator it = q.iterator(); it.hasNext();) {
int i = ((Integer)(it.next())).intValue();
assertEquals(++k, i);
}
assertEquals(3, k);
}
/**
* Modifications do not cause iterators to fail
*/
public void testWeaklyConsistentIteration () {
final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
q.add(one);
q.add(two);
q.add(three);
try {
for (Iterator it = q.iterator(); it.hasNext();) {
q.remove();
it.next();
}
}
catch (ConcurrentModificationException e) {
unexpectedException();
}
assertEquals(0, q.size());
}
/**
* toString contains toStrings of elements
*/
public void testToString() {
ArrayBlockingQueue q = populatedQueue(SIZE);
String s = q.toString();
for (int i = 0; i < SIZE; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
/**
* offer transfers elements across Executor tasks
*/
public void testOfferInExecutor() {
final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
q.add(one);
q.add(two);
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new Runnable() {
public void run() {
threadAssertFalse(q.offer(three));
try {
threadAssertTrue(q.offer(three, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
threadAssertEquals(0, q.remainingCapacity());
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
executor.execute(new Runnable() {
public void run() {
try {
Thread.sleep(SMALL_DELAY_MS);
threadAssertEquals(one, q.take());
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
joinPool(executor);
}
/**
* poll retrieves elements across Executor threads
*/
public void testPollInExecutor() {
final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new Runnable() {
public void run() {
threadAssertNull(q.poll());
try {
threadAssertTrue(null != q.poll(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
threadAssertTrue(q.isEmpty());
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
executor.execute(new Runnable() {
public void run() {
try {
Thread.sleep(SMALL_DELAY_MS);
q.put(one);
}
catch (InterruptedException e) {
threadUnexpectedException();
}
}
});
joinPool(executor);
}
/**
* A deserialized serialized queue has same elements in same order
*/
public void testSerialization() {
ArrayBlockingQueue q = populatedQueue(SIZE);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
ArrayBlockingQueue r = (ArrayBlockingQueue)in.readObject();
assertEquals(q.size(), r.size());
while (!q.isEmpty())
assertEquals(q.remove(), r.remove());
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* drainTo(null) throws NPE
*/
public void testDrainToNull() {
ArrayBlockingQueue q = populatedQueue(SIZE);
try {
q.drainTo(null);
shouldThrow();
} catch(NullPointerException success) {
}
}
/**
* drainTo(this) throws IAE
*/
public void testDrainToSelf() {
ArrayBlockingQueue q = populatedQueue(SIZE);
try {
q.drainTo(q);
shouldThrow();
} catch(IllegalArgumentException success) {
}
}
/**
* drainTo(c) empties queue into another collection c
*/
public void testDrainTo() {
ArrayBlockingQueue q = populatedQueue(SIZE);
ArrayList l = new ArrayList();
q.drainTo(l);
assertEquals(q.size(), 0);
assertEquals(l.size(), SIZE);
for (int i = 0; i < SIZE; ++i)
assertEquals(l.get(i), new Integer(i));
q.add(zero);
q.add(one);
assertFalse(q.isEmpty());
assertTrue(q.contains(zero));
assertTrue(q.contains(one));
l.clear();
q.drainTo(l);
assertEquals(q.size(), 0);
assertEquals(l.size(), 2);
for (int i = 0; i < 2; ++i)
assertEquals(l.get(i), new Integer(i));
}
/**
* drainTo empties full queue, unblocking a waiting put.
*/
public void testDrainToWithActivePut() {
final ArrayBlockingQueue q = populatedQueue(SIZE);
Thread t = new Thread(new Runnable() {
public void run() {
try {
q.put(new Integer(SIZE+1));
} catch (InterruptedException ie){
threadUnexpectedException();
}
}
});
try {
t.start();
ArrayList l = new ArrayList();
q.drainTo(l);
assertTrue(l.size() >= SIZE);
for (int i = 0; i < SIZE; ++i)
assertEquals(l.get(i), new Integer(i));
t.join();
assertTrue(q.size() + l.size() >= SIZE);
} catch(Exception e){
unexpectedException();
}
}
/**
* drainTo(null, n) throws NPE
*/
public void testDrainToNullN() {
ArrayBlockingQueue q = populatedQueue(SIZE);
try {
q.drainTo(null, 0);
shouldThrow();
} catch(NullPointerException success) {
}
}
/**
* drainTo(this, n) throws IAE
*/
public void testDrainToSelfN() {
ArrayBlockingQueue q = populatedQueue(SIZE);
try {
q.drainTo(q, 0);
shouldThrow();
} catch(IllegalArgumentException success) {
}
}
/**
* drainTo(c, n) empties first max {n, size} elements of queue into c
*/
public void testDrainToN() {
ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE*2);
for (int i = 0; i < SIZE + 2; ++i) {
for(int j = 0; j < SIZE; j++)
assertTrue(q.offer(new Integer(j)));
ArrayList l = new ArrayList();
q.drainTo(l, i);
int k = (i < SIZE)? i : SIZE;
assertEquals(l.size(), k);
assertEquals(q.size(), SIZE-k);
for (int j = 0; j < k; ++j)
assertEquals(l.get(j), new Integer(j));
while (q.poll() != null) ;
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/AtomicLongTest.java 0000644 0017507 0003772 00000015625 10253674160 024011 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import java.io.*;
public class AtomicLongTest extends JSR166TestCase {
public static void main (String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(AtomicLongTest.class);
}
/**
* constructor initializes to given value
*/
public void testConstructor(){
AtomicLong ai = new AtomicLong(1);
assertEquals(1,ai.get());
}
/**
* default constructed initializes to zero
*/
public void testConstructor2(){
AtomicLong ai = new AtomicLong();
assertEquals(0,ai.get());
}
/**
* get returns the last value set
*/
public void testGetSet(){
AtomicLong ai = new AtomicLong(1);
assertEquals(1,ai.get());
ai.set(2);
assertEquals(2,ai.get());
ai.set(-3);
assertEquals(-3,ai.get());
}
/**
* get returns the last value lazySet in same thread
*/
public void testGetLazySet(){
AtomicLong ai = new AtomicLong(1);
assertEquals(1,ai.get());
ai.lazySet(2);
assertEquals(2,ai.get());
ai.lazySet(-3);
assertEquals(-3,ai.get());
}
/**
* compareAndSet succeeds in changing value if equal to expected else fails
*/
public void testCompareAndSet(){
AtomicLong ai = new AtomicLong(1);
assertTrue(ai.compareAndSet(1,2));
assertTrue(ai.compareAndSet(2,-4));
assertEquals(-4,ai.get());
assertFalse(ai.compareAndSet(-5,7));
assertFalse((7 == ai.get()));
assertTrue(ai.compareAndSet(-4,7));
assertEquals(7,ai.get());
}
/**
* compareAndSet in one thread enables another waiting for value
* to succeed
*/
public void testCompareAndSetInMultipleThreads() {
final AtomicLong ai = new AtomicLong(1);
Thread t = new Thread(new Runnable() {
public void run() {
while(!ai.compareAndSet(2, 3)) Thread.yield();
}});
try {
t.start();
assertTrue(ai.compareAndSet(1, 2));
t.join(LONG_DELAY_MS);
assertFalse(t.isAlive());
assertEquals(ai.get(), 3);
}
catch(Exception e) {
unexpectedException();
}
}
/**
* repeated weakCompareAndSet succeeds in changing value when equal
* to expected
*/
public void testWeakCompareAndSet(){
AtomicLong ai = new AtomicLong(1);
while(!ai.weakCompareAndSet(1,2));
while(!ai.weakCompareAndSet(2,-4));
assertEquals(-4,ai.get());
while(!ai.weakCompareAndSet(-4,7));
assertEquals(7,ai.get());
}
/**
* getAndSet returns previous value and sets to given value
*/
public void testGetAndSet(){
AtomicLong ai = new AtomicLong(1);
assertEquals(1,ai.getAndSet(0));
assertEquals(0,ai.getAndSet(-10));
assertEquals(-10,ai.getAndSet(1));
}
/**
* getAndAdd returns previous value and adds given value
*/
public void testGetAndAdd(){
AtomicLong ai = new AtomicLong(1);
assertEquals(1,ai.getAndAdd(2));
assertEquals(3,ai.get());
assertEquals(3,ai.getAndAdd(-4));
assertEquals(-1,ai.get());
}
/**
* getAndDecrement returns previous value and decrements
*/
public void testGetAndDecrement(){
AtomicLong ai = new AtomicLong(1);
assertEquals(1,ai.getAndDecrement());
assertEquals(0,ai.getAndDecrement());
assertEquals(-1,ai.getAndDecrement());
}
/**
* getAndIncrement returns previous value and increments
*/
public void testGetAndIncrement(){
AtomicLong ai = new AtomicLong(1);
assertEquals(1,ai.getAndIncrement());
assertEquals(2,ai.get());
ai.set(-2);
assertEquals(-2,ai.getAndIncrement());
assertEquals(-1,ai.getAndIncrement());
assertEquals(0,ai.getAndIncrement());
assertEquals(1,ai.get());
}
/**
* addAndGet adds given value to current, and returns current value
*/
public void testAddAndGet(){
AtomicLong ai = new AtomicLong(1);
assertEquals(3,ai.addAndGet(2));
assertEquals(3,ai.get());
assertEquals(-1,ai.addAndGet(-4));
assertEquals(-1,ai.get());
}
/**
* decrementAndGet decrements and returns current value
*/
public void testDecrementAndGet(){
AtomicLong ai = new AtomicLong(1);
assertEquals(0,ai.decrementAndGet());
assertEquals(-1,ai.decrementAndGet());
assertEquals(-2,ai.decrementAndGet());
assertEquals(-2,ai.get());
}
/**
* incrementAndGet increments and returns current value
*/
public void testIncrementAndGet(){
AtomicLong ai = new AtomicLong(1);
assertEquals(2,ai.incrementAndGet());
assertEquals(2,ai.get());
ai.set(-2);
assertEquals(-1,ai.incrementAndGet());
assertEquals(0,ai.incrementAndGet());
assertEquals(1,ai.incrementAndGet());
assertEquals(1,ai.get());
}
/**
* a deserialized serialized atomic holds same value
*/
public void testSerialization() {
AtomicLong l = new AtomicLong();
try {
l.set(-22);
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(l);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
AtomicLong r = (AtomicLong) in.readObject();
assertEquals(l.get(), r.get());
} catch(Exception e){
unexpectedException();
}
}
/**
* toString returns current value.
*/
public void testToString() {
AtomicLong ai = new AtomicLong();
for (long i = -12; i < 6; ++i) {
ai.set(i);
assertEquals(ai.toString(), Long.toString(i));
}
}
/**
* longValue returns current value.
*/
public void testLongValue() {
AtomicLong ai = new AtomicLong();
for (int i = -12; i < 6; ++i) {
ai.set(i);
assertEquals((long)i, ai.longValue());
}
}
/**
* floatValue returns current value.
*/
public void testFloatValue() {
AtomicLong ai = new AtomicLong();
for (int i = -12; i < 6; ++i) {
ai.set(i);
assertEquals((float)i, ai.floatValue(), 0.0f);
}
}
/**
* doubleValue returns current value.
*/
public void testDoubleValue() {
AtomicLong ai = new AtomicLong();
for (int i = -12; i < 6; ++i) {
ai.set(i);
assertEquals((double)i, ai.doubleValue(), 0.0);
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/CopyOnWriteArraySetTest.java 0000644 0017507 0003772 00000017377 10365510635 025660 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.io.*;
import java.util.Vector;
import java.util.Iterator;
public class CopyOnWriteArraySetTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(CopyOnWriteArraySetTest.class);
}
static CopyOnWriteArraySet populatedSet(int n){
CopyOnWriteArraySet a = new CopyOnWriteArraySet();
assertTrue(a.isEmpty());
for (int i = 0; i < n; ++i)
a.add(new Integer(i));
assertFalse(a.isEmpty());
assertEquals(n, a.size());
return a;
}
/**
* Default-constructed set is empty
*/
public void testConstructor() {
CopyOnWriteArraySet a = new CopyOnWriteArraySet();
assertTrue(a.isEmpty());
}
/**
* Collection-constructed set holds all of its elements
*/
public void testConstructor3() {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE-1; ++i)
ints[i] = new Integer(i);
CopyOnWriteArraySet a = new CopyOnWriteArraySet(Arrays.asList(ints));
for (int i = 0; i < SIZE; ++i)
assertTrue(a.contains(ints[i]));
}
/**
* addAll adds each element from the given collection
*/
public void testAddAll() {
CopyOnWriteArraySet full = populatedSet(3);
Vector v = new Vector();
v.add(three);
v.add(four);
v.add(five);
full.addAll(v);
assertEquals(6, full.size());
}
/**
* addAll adds each element from the given collection that did not
* already exist in the set
*/
public void testAddAll2() {
CopyOnWriteArraySet full = populatedSet(3);
Vector v = new Vector();
v.add(three);
v.add(four);
v.add(one); // will not add this element
full.addAll(v);
assertEquals(5, full.size());
}
/**
* add will not add the element if it already exists in the set
*/
public void testAdd2() {
CopyOnWriteArraySet full = populatedSet(3);
full.add(one);
assertEquals(3, full.size());
}
/**
* add adds the element when it does not exist
* in the set
*/
public void testAdd3() {
CopyOnWriteArraySet full = populatedSet(3);
full.add(three);
assertTrue(full.contains(three));
}
/**
* clear removes all elements from the set
*/
public void testClear() {
CopyOnWriteArraySet full = populatedSet(3);
full.clear();
assertEquals(0, full.size());
}
/**
* contains returns true for added elements
*/
public void testContains() {
CopyOnWriteArraySet full = populatedSet(3);
assertTrue(full.contains(one));
assertFalse(full.contains(five));
}
/**
* Sets with equal elements are equal
*/
public void testEquals() {
CopyOnWriteArraySet a = populatedSet(3);
CopyOnWriteArraySet b = populatedSet(3);
assertTrue(a.equals(b));
assertTrue(b.equals(a));
assertEquals(a.hashCode(), b.hashCode());
a.add(m1);
assertFalse(a.equals(b));
assertFalse(b.equals(a));
b.add(m1);
assertTrue(a.equals(b));
assertTrue(b.equals(a));
assertEquals(a.hashCode(), b.hashCode());
}
/**
* containsAll returns true for collections with subset of elements
*/
public void testContainsAll() {
CopyOnWriteArraySet full = populatedSet(3);
Vector v = new Vector();
v.add(one);
v.add(two);
assertTrue(full.containsAll(v));
v.add(six);
assertFalse(full.containsAll(v));
}
/**
* isEmpty is true when empty, else false
*/
public void testIsEmpty() {
CopyOnWriteArraySet empty = new CopyOnWriteArraySet();
CopyOnWriteArraySet full = populatedSet(3);
assertTrue(empty.isEmpty());
assertFalse(full.isEmpty());
}
/**
* iterator() returns an iterator containing the elements of the set
*/
public void testIterator() {
CopyOnWriteArraySet full = populatedSet(3);
Iterator i = full.iterator();
int j;
for(j = 0; i.hasNext(); j++)
assertEquals(j, ((Integer)i.next()).intValue());
assertEquals(3, j);
}
/**
* iterator remove is unsupported
*/
public void testIteratorRemove () {
CopyOnWriteArraySet full = populatedSet(3);
Iterator it = full.iterator();
it.next();
try {
it.remove();
shouldThrow();
}
catch (UnsupportedOperationException success) {}
}
/**
* toString holds toString of elements
*/
public void testToString() {
CopyOnWriteArraySet full = populatedSet(3);
String s = full.toString();
for (int i = 0; i < 3; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
/**
* removeAll removes all elements from the given collection
*/
public void testRemoveAll() {
CopyOnWriteArraySet full = populatedSet(3);
Vector v = new Vector();
v.add(one);
v.add(two);
full.removeAll(v);
assertEquals(1, full.size());
}
/**
* remove removes an element
*/
public void testRemove() {
CopyOnWriteArraySet full = populatedSet(3);
full.remove(one);
assertFalse(full.contains(one));
assertEquals(2, full.size());
}
/**
* size returns the number of elements
*/
public void testSize() {
CopyOnWriteArraySet empty = new CopyOnWriteArraySet();
CopyOnWriteArraySet full = populatedSet(3);
assertEquals(3, full.size());
assertEquals(0, empty.size());
}
/**
* toArray returns an Object array containing all elements from the set
*/
public void testToArray() {
CopyOnWriteArraySet full = populatedSet(3);
Object[] o = full.toArray();
assertEquals(3, o.length);
assertEquals(0, ((Integer)o[0]).intValue());
assertEquals(1, ((Integer)o[1]).intValue());
assertEquals(2, ((Integer)o[2]).intValue());
}
/**
* toArray returns an Integer array containing all elements from
* the set
*/
public void testToArray2() {
CopyOnWriteArraySet full = populatedSet(3);
Integer[] i = new Integer[3];
i = (Integer[])full.toArray(i);
assertEquals(3, i.length);
assertEquals(0, i[0].intValue());
assertEquals(1, i[1].intValue());
assertEquals(2, i[2].intValue());
}
/**
* toArray throws an ArrayStoreException when the given array can
* not store the objects inside the set
*/
public void testToArray_ArrayStoreException() {
try {
CopyOnWriteArraySet c = new CopyOnWriteArraySet();
c.add("zfasdfsdf");
c.add("asdadasd");
c.toArray(new Long[5]);
shouldThrow();
} catch(ArrayStoreException e){}
}
/**
* A deserialized serialized set is equal
*/
public void testSerialization() {
CopyOnWriteArraySet q = populatedSet(SIZE);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
CopyOnWriteArraySet r = (CopyOnWriteArraySet)in.readObject();
assertEquals(q.size(), r.size());
assertTrue(q.equals(r));
assertTrue(r.equals(q));
} catch(Exception e){
unexpectedException();
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/FutureTaskTest.java 0000644 0017507 0003772 00000030616 10431260156 024041 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.*;
import java.util.NoSuchElementException;
public class FutureTaskTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(FutureTaskTest.class);
}
/**
* Subclass to expose protected methods
*/
static class PublicFutureTask extends FutureTask {
public PublicFutureTask(Callable r) { super(r); }
public boolean runAndReset() { return super.runAndReset(); }
public void set(Object x) { super.set(x); }
public void setException(Throwable t) { super.setException(t); }
}
/**
* Creating a future with a null callable throws NPE
*/
public void testConstructor() {
try {
FutureTask task = new FutureTask(null);
shouldThrow();
}
catch(NullPointerException success) {
}
}
/**
* creating a future with null runnable fails
*/
public void testConstructor2() {
try {
FutureTask task = new FutureTask(null, Boolean.TRUE);
shouldThrow();
}
catch(NullPointerException success) {
}
}
/**
* isDone is true when a task completes
*/
public void testIsDone() {
FutureTask task = new FutureTask( new NoOpCallable());
task.run();
assertTrue(task.isDone());
assertFalse(task.isCancelled());
}
/**
* runAndReset of a non-cancelled task succeeds
*/
public void testRunAndReset() {
PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
assertTrue(task.runAndReset());
assertFalse(task.isDone());
}
/**
* runAndReset after cancellation fails
*/
public void testResetAfterCancel() {
PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
assertTrue(task.cancel(false));
assertFalse(task.runAndReset());
assertTrue(task.isDone());
assertTrue(task.isCancelled());
}
/**
* setting value causes get to return it
*/
public void testSet() {
PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
task.set(one);
try {
assertEquals(task.get(), one);
}
catch(Exception e) {
unexpectedException();
}
}
/**
* setException causes get to throw ExecutionException
*/
public void testSetException() {
Exception nse = new NoSuchElementException();
PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
task.setException(nse);
try {
Object x = task.get();
shouldThrow();
}
catch(ExecutionException ee) {
Throwable cause = ee.getCause();
assertEquals(cause, nse);
}
catch(Exception e) {
unexpectedException();
}
}
/**
* Cancelling before running succeeds
*/
public void testCancelBeforeRun() {
FutureTask task = new FutureTask( new NoOpCallable());
assertTrue(task.cancel(false));
task.run();
assertTrue(task.isDone());
assertTrue(task.isCancelled());
}
/**
* Cancel(true) before run succeeds
*/
public void testCancelBeforeRun2() {
FutureTask task = new FutureTask( new NoOpCallable());
assertTrue(task.cancel(true));
task.run();
assertTrue(task.isDone());
assertTrue(task.isCancelled());
}
/**
* cancel of a completed task fails
*/
public void testCancelAfterRun() {
FutureTask task = new FutureTask( new NoOpCallable());
task.run();
assertFalse(task.cancel(false));
assertTrue(task.isDone());
assertFalse(task.isCancelled());
}
/**
* cancel(true) interrupts a running task
*/
public void testCancelInterrupt() {
FutureTask task = new FutureTask( new Callable() {
public Object call() {
try {
Thread.sleep(MEDIUM_DELAY_MS);
threadShouldThrow();
}
catch (InterruptedException success) {}
return Boolean.TRUE;
} });
Thread t = new Thread(task);
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
assertTrue(task.cancel(true));
t.join();
assertTrue(task.isDone());
assertTrue(task.isCancelled());
} catch(InterruptedException e){
unexpectedException();
}
}
/**
* cancel(false) does not interrupt a running task
*/
public void testCancelNoInterrupt() {
FutureTask task = new FutureTask( new Callable() {
public Object call() {
try {
Thread.sleep(MEDIUM_DELAY_MS);
}
catch (InterruptedException success) {
threadFail("should not interrupt");
}
return Boolean.TRUE;
} });
Thread t = new Thread(task);
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
assertTrue(task.cancel(false));
t.join();
assertTrue(task.isDone());
assertTrue(task.isCancelled());
} catch(InterruptedException e){
unexpectedException();
}
}
/**
* set in one thread causes get in another thread to retrieve value
*/
public void testGet1() {
final FutureTask ft = new FutureTask(new Callable() {
public Object call() {
try {
Thread.sleep(MEDIUM_DELAY_MS);
} catch(InterruptedException e){
threadUnexpectedException();
}
return Boolean.TRUE;
}
});
Thread t = new Thread(new Runnable() {
public void run() {
try {
ft.get();
} catch(Exception e){
threadUnexpectedException();
}
}
});
try {
assertFalse(ft.isDone());
assertFalse(ft.isCancelled());
t.start();
Thread.sleep(SHORT_DELAY_MS);
ft.run();
t.join();
assertTrue(ft.isDone());
assertFalse(ft.isCancelled());
} catch(InterruptedException e){
unexpectedException();
}
}
/**
* set in one thread causes timed get in another thread to retrieve value
*/
public void testTimedGet1() {
final FutureTask ft = new FutureTask(new Callable() {
public Object call() {
try {
Thread.sleep(MEDIUM_DELAY_MS);
} catch(InterruptedException e){
threadUnexpectedException();
}
return Boolean.TRUE;
}
});
Thread t = new Thread(new Runnable() {
public void run() {
try {
ft.get(SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
} catch(TimeoutException success) {
} catch(Exception e){
threadUnexpectedException();
}
}
});
try {
assertFalse(ft.isDone());
assertFalse(ft.isCancelled());
t.start();
ft.run();
t.join();
assertTrue(ft.isDone());
assertFalse(ft.isCancelled());
} catch(InterruptedException e){
unexpectedException();
}
}
/**
* Cancelling a task causes timed get in another thread to throw CancellationException
*/
public void testTimedGet_Cancellation() {
final FutureTask ft = new FutureTask(new Callable() {
public Object call() {
try {
Thread.sleep(SMALL_DELAY_MS);
threadShouldThrow();
} catch(InterruptedException e) {
}
return Boolean.TRUE;
}
});
try {
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
ft.get(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch(CancellationException success) {}
catch(Exception e){
e.printStackTrace();
threadUnexpectedException();
}
}
});
Thread t2 = new Thread(ft);
t1.start();
t2.start();
Thread.sleep(SHORT_DELAY_MS);
ft.cancel(true);
t1.join();
t2.join();
} catch(InterruptedException ie){
unexpectedException();
}
}
/**
* Cancelling a task causes get in another thread to throw CancellationException
*/
public void testGet_Cancellation() {
final FutureTask ft = new FutureTask(new Callable() {
public Object call() {
try {
Thread.sleep(MEDIUM_DELAY_MS);
threadShouldThrow();
} catch(InterruptedException e){
}
return Boolean.TRUE;
}
});
try {
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
ft.get();
threadShouldThrow();
} catch(CancellationException success){
}
catch(Exception e){
threadUnexpectedException();
}
}
});
Thread t2 = new Thread(ft);
t1.start();
t2.start();
Thread.sleep(SHORT_DELAY_MS);
ft.cancel(true);
t1.join();
t2.join();
} catch(InterruptedException success){
unexpectedException();
}
}
/**
* A runtime exception in task causes get to throw ExecutionException
*/
public void testGet_ExecutionException() {
final FutureTask ft = new FutureTask(new Callable() {
public Object call() {
int i = 5/0;
return Boolean.TRUE;
}
});
try {
ft.run();
ft.get();
shouldThrow();
} catch(ExecutionException success){
}
catch(Exception e){
unexpectedException();
}
}
/**
* A runtime exception in task causes timed get to throw ExecutionException
*/
public void testTimedGet_ExecutionException2() {
final FutureTask ft = new FutureTask(new Callable() {
public Object call() {
int i = 5/0;
return Boolean.TRUE;
}
});
try {
ft.run();
ft.get(SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
shouldThrow();
} catch(ExecutionException success) {
} catch(TimeoutException success) { } // unlikely but OK
catch(Exception e){
unexpectedException();
}
}
/**
* Interrupting a waiting get causes it to throw InterruptedException
*/
public void testGet_InterruptedException() {
final FutureTask ft = new FutureTask(new NoOpCallable());
Thread t = new Thread(new Runnable() {
public void run() {
try {
ft.get();
threadShouldThrow();
} catch(InterruptedException success){
} catch(Exception e){
threadUnexpectedException();
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch(Exception e){
unexpectedException();
}
}
/**
* Interrupting a waiting timed get causes it to throw InterruptedException
*/
public void testTimedGet_InterruptedException2() {
final FutureTask ft = new FutureTask(new NoOpCallable());
Thread t = new Thread(new Runnable() {
public void run() {
try {
ft.get(LONG_DELAY_MS,TimeUnit.MILLISECONDS);
threadShouldThrow();
} catch(InterruptedException success){}
catch(Exception e){
threadUnexpectedException();
}
}
});
try {
t.start();
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch(Exception e){
unexpectedException();
}
}
/**
* A timed out timed get throws TimeoutException
*/
public void testGet_TimeoutException() {
try {
FutureTask ft = new FutureTask(new NoOpCallable());
ft.get(1,TimeUnit.MILLISECONDS);
shouldThrow();
} catch(TimeoutException success){}
catch(Exception success){
unexpectedException();
}
}
}
backport-util-concurrent-3.1-src/test/tck/src/TreeMapTest.java 0000644 0017507 0003772 00000076415 10431777323 023321 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.io.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Random;
import java.util.BitSet;
import java.util.NoSuchElementException;
public class TreeMapTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(TreeMapTest.class);
}
/**
* Create a map from Integers 1-5 to Strings "A"-"E".
*/
private static TreeMap map5() {
TreeMap map = new TreeMap();
assertTrue(map.isEmpty());
map.put(one, "A");
map.put(five, "E");
map.put(three, "C");
map.put(two, "B");
map.put(four, "D");
assertFalse(map.isEmpty());
assertEquals(5, map.size());
return map;
}
/**
* clear removes all pairs
*/
public void testClear() {
TreeMap map = map5();
map.clear();
assertEquals(map.size(), 0);
}
/**
*
*/
public void testConstructFromSorted() {
TreeMap map = map5();
TreeMap map2 = new TreeMap(map);
assertEquals(map, map2);
}
/**
* Maps with same contents are equal
*/
public void testEquals() {
TreeMap map1 = map5();
TreeMap map2 = map5();
assertEquals(map1, map2);
assertEquals(map2, map1);
map1.clear();
assertFalse(map1.equals(map2));
assertFalse(map2.equals(map1));
}
/**
* containsKey returns true for contained key
*/
public void testContainsKey() {
TreeMap map = map5();
assertTrue(map.containsKey(one));
assertFalse(map.containsKey(zero));
}
/**
* containsValue returns true for held values
*/
public void testContainsValue() {
TreeMap map = map5();
assertTrue(map.containsValue("A"));
assertFalse(map.containsValue("Z"));
}
/**
* get returns the correct element at the given key,
* or null if not present
*/
public void testGet() {
TreeMap map = map5();
assertEquals("A", (String)map.get(one));
TreeMap empty = new TreeMap();
assertNull(empty.get(one));
}
/**
* isEmpty is true of empty map and false for non-empty
*/
public void testIsEmpty() {
TreeMap empty = new TreeMap();
TreeMap map = map5();
assertTrue(empty.isEmpty());
assertFalse(map.isEmpty());
}
/**
* firstKey returns first key
*/
public void testFirstKey() {
TreeMap map = map5();
assertEquals(one, map.firstKey());
}
/**
* lastKey returns last key
*/
public void testLastKey() {
TreeMap map = map5();
assertEquals(five, map.lastKey());
}
/**
* keySet.toArray returns contains all keys
*/
public void testKeySetToArray() {
TreeMap map = map5();
Set s = map.keySet();
Object[] ar = s.toArray();
assertTrue(s.containsAll(Arrays.asList(ar)));
assertEquals(5, ar.length);
ar[0] = m10;
assertFalse(s.containsAll(Arrays.asList(ar)));
}
/**
* descendingkeySet.toArray returns contains all keys
*/
public void testDescendingKeySetToArray() {
TreeMap map = map5();
Set s = map.descendingKeySet();
Object[] ar = s.toArray();
assertEquals(5, ar.length);
assertTrue(s.containsAll(Arrays.asList(ar)));
ar[0] = m10;
assertFalse(s.containsAll(Arrays.asList(ar)));
}
/**
* keySet returns a Set containing all the keys
*/
public void testKeySet() {
TreeMap map = map5();
Set s = map.keySet();
assertEquals(5, s.size());
assertTrue(s.contains(one));
assertTrue(s.contains(two));
assertTrue(s.contains(three));
assertTrue(s.contains(four));
assertTrue(s.contains(five));
}
/**
* keySet is ordered
*/
public void testKeySetOrder() {
TreeMap map = map5();
Set s = map.keySet();
Iterator i = s.iterator();
Integer last = (Integer)i.next();
assertEquals(last, one);
while (i.hasNext()) {
Integer k = (Integer)i.next();
assertTrue(last.compareTo(k) < 0);
last = k;
}
}
/**
* descendingKeySet is ordered
*/
public void testDescendingKeySetOrder() {
TreeMap map = map5();
Set s = map.descendingKeySet();
Iterator i = s.iterator();
Integer last = (Integer)i.next();
assertEquals(last, five);
while (i.hasNext()) {
Integer k = (Integer)i.next();
assertTrue(last.compareTo(k) > 0);
last = k;
}
}
/**
* values collection contains all values
*/
public void testValues() {
TreeMap map = map5();
Collection s = map.values();
assertEquals(5, s.size());
assertTrue(s.contains("A"));
assertTrue(s.contains("B"));
assertTrue(s.contains("C"));
assertTrue(s.contains("D"));
assertTrue(s.contains("E"));
}
/**
* entrySet contains all pairs
*/
public void testEntrySet() {
TreeMap map = map5();
Set s = map.entrySet();
assertEquals(5, s.size());
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
assertTrue(
(e.getKey().equals(one) && e.getValue().equals("A")) ||
(e.getKey().equals(two) && e.getValue().equals("B")) ||
(e.getKey().equals(three) && e.getValue().equals("C")) ||
(e.getKey().equals(four) && e.getValue().equals("D")) ||
(e.getKey().equals(five) && e.getValue().equals("E")));
}
}
/**
* descendingEntrySet contains all pairs
*/
public void testDescendingEntrySet() {
TreeMap map = map5();
Set s = map.descendingMap().entrySet();
assertEquals(5, s.size());
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
assertTrue(
(e.getKey().equals(one) && e.getValue().equals("A")) ||
(e.getKey().equals(two) && e.getValue().equals("B")) ||
(e.getKey().equals(three) && e.getValue().equals("C")) ||
(e.getKey().equals(four) && e.getValue().equals("D")) ||
(e.getKey().equals(five) && e.getValue().equals("E")));
}
}
/**
* entrySet.toArray contains all entries
*/
public void testEntrySetToArray() {
TreeMap map = map5();
Set s = map.entrySet();
Object[] ar = s.toArray();
assertEquals(5, ar.length);
for (int i = 0; i < 5; ++i) {
assertTrue(map.containsKey(((Map.Entry)(ar[i])).getKey()));
assertTrue(map.containsValue(((Map.Entry)(ar[i])).getValue()));
}
}
/**
* descendingEntrySet.toArray contains all entries
*/
public void testDescendingEntrySetToArray() {
TreeMap map = map5();
Set s = map.descendingMap().entrySet();
Object[] ar = s.toArray();
assertEquals(5, ar.length);
for (int i = 0; i < 5; ++i) {
assertTrue(map.containsKey(((Map.Entry)(ar[i])).getKey()));
assertTrue(map.containsValue(((Map.Entry)(ar[i])).getValue()));
}
}
/**
* putAll adds all key-value pairs from the given map
*/
public void testPutAll() {
TreeMap empty = new TreeMap();
TreeMap map = map5();
empty.putAll(map);
assertEquals(5, empty.size());
assertTrue(empty.containsKey(one));
assertTrue(empty.containsKey(two));
assertTrue(empty.containsKey(three));
assertTrue(empty.containsKey(four));
assertTrue(empty.containsKey(five));
}
/**
* remove removes the correct key-value pair from the map
*/
public void testRemove() {
TreeMap map = map5();
map.remove(five);
assertEquals(4, map.size());
assertFalse(map.containsKey(five));
}
/**
* lowerEntry returns preceding entry.
*/
public void testLowerEntry() {
TreeMap map = map5();
Map.Entry e1 = map.lowerEntry(three);
assertEquals(two, e1.getKey());
Map.Entry e2 = map.lowerEntry(six);
assertEquals(five, e2.getKey());
Map.Entry e3 = map.lowerEntry(one);
assertNull(e3);
Map.Entry e4 = map.lowerEntry(zero);
assertNull(e4);
}
/**
* higherEntry returns next entry.
*/
public void testHigherEntry() {
TreeMap map = map5();
Map.Entry e1 = map.higherEntry(three);
assertEquals(four, e1.getKey());
Map.Entry e2 = map.higherEntry(zero);
assertEquals(one, e2.getKey());
Map.Entry e3 = map.higherEntry(five);
assertNull(e3);
Map.Entry e4 = map.higherEntry(six);
assertNull(e4);
}
/**
* floorEntry returns preceding entry.
*/
public void testFloorEntry() {
TreeMap map = map5();
Map.Entry e1 = map.floorEntry(three);
assertEquals(three, e1.getKey());
Map.Entry e2 = map.floorEntry(six);
assertEquals(five, e2.getKey());
Map.Entry e3 = map.floorEntry(one);
assertEquals(one, e3.getKey());
Map.Entry e4 = map.floorEntry(zero);
assertNull(e4);
}
/**
* ceilingEntry returns next entry.
*/
public void testCeilingEntry() {
TreeMap map = map5();
Map.Entry e1 = map.ceilingEntry(three);
assertEquals(three, e1.getKey());
Map.Entry e2 = map.ceilingEntry(zero);
assertEquals(one, e2.getKey());
Map.Entry e3 = map.ceilingEntry(five);
assertEquals(five, e3.getKey());
Map.Entry e4 = map.ceilingEntry(six);
assertNull(e4);
}
/**
* lowerKey returns preceding element
*/
public void testLowerKey() {
TreeMap q = map5();
Object e1 = q.lowerKey(three);
assertEquals(two, e1);
Object e2 = q.lowerKey(six);
assertEquals(five, e2);
Object e3 = q.lowerKey(one);
assertNull(e3);
Object e4 = q.lowerKey(zero);
assertNull(e4);
}
/**
* higherKey returns next element
*/
public void testHigherKey() {
TreeMap q = map5();
Object e1 = q.higherKey(three);
assertEquals(four, e1);
Object e2 = q.higherKey(zero);
assertEquals(one, e2);
Object e3 = q.higherKey(five);
assertNull(e3);
Object e4 = q.higherKey(six);
assertNull(e4);
}
/**
* floorKey returns preceding element
*/
public void testFloorKey() {
TreeMap q = map5();
Object e1 = q.floorKey(three);
assertEquals(three, e1);
Object e2 = q.floorKey(six);
assertEquals(five, e2);
Object e3 = q.floorKey(one);
assertEquals(one, e3);
Object e4 = q.floorKey(zero);
assertNull(e4);
}
/**
* ceilingKey returns next element
*/
public void testCeilingKey() {
TreeMap q = map5();
Object e1 = q.ceilingKey(three);
assertEquals(three, e1);
Object e2 = q.ceilingKey(zero);
assertEquals(one, e2);
Object e3 = q.ceilingKey(five);
assertEquals(five, e3);
Object e4 = q.ceilingKey(six);
assertNull(e4);
}
/**
* pollFirstEntry returns entries in order
*/
public void testPollFirstEntry() {
TreeMap map = map5();
Map.Entry e = map.pollFirstEntry();
assertEquals(one, e.getKey());
assertEquals("A", e.getValue());
e = map.pollFirstEntry();
assertEquals(two, e.getKey());
map.put(one, "A");
e = map.pollFirstEntry();
assertEquals(one, e.getKey());
assertEquals("A", e.getValue());
e = map.pollFirstEntry();
assertEquals(three, e.getKey());
map.remove(four);
e = map.pollFirstEntry();
assertEquals(five, e.getKey());
try {
e.setValue("A");
shouldThrow();
} catch (Exception ok) {
}
e = map.pollFirstEntry();
assertNull(e);
}
/**
* pollLastEntry returns entries in order
*/
public void testPollLastEntry() {
TreeMap map = map5();
Map.Entry e = map.pollLastEntry();
assertEquals(five, e.getKey());
assertEquals("E", e.getValue());
e = map.pollLastEntry();
assertEquals(four, e.getKey());
map.put(five, "E");
e = map.pollLastEntry();
assertEquals(five, e.getKey());
assertEquals("E", e.getValue());
e = map.pollLastEntry();
assertEquals(three, e.getKey());
map.remove(two);
e = map.pollLastEntry();
assertEquals(one, e.getKey());
try {
e.setValue("E");
shouldThrow();
} catch (Exception ok) {
}
e = map.pollLastEntry();
assertNull(e);
}
/**
* size returns the correct values
*/
public void testSize() {
TreeMap map = map5();
TreeMap empty = new TreeMap();
assertEquals(0, empty.size());
assertEquals(5, map.size());
}
/**
* toString contains toString of elements
*/
public void testToString() {
TreeMap map = map5();
String s = map.toString();
for (int i = 1; i <= 5; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
// Exception tests
/**
* get(null) of nonempty map throws NPE
*/
public void testGet_NullPointerException() {
try {
TreeMap c = map5();
c.get(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* containsKey(null) of nonempty map throws NPE
*/
public void testContainsKey_NullPointerException() {
try {
TreeMap c = map5();
c.containsKey(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* remove(null) throws NPE for nonempty map
*/
public void testRemove1_NullPointerException() {
try {
TreeMap c = new TreeMap();
c.put("sadsdf", "asdads");
c.remove(null);
shouldThrow();
} catch(NullPointerException e){}
}
/**
* A deserialized map equals original
*/
public void testSerialization() {
TreeMap q = map5();
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
TreeMap r = (TreeMap)in.readObject();
assertEquals(q.size(), r.size());
assertTrue(q.equals(r));
assertTrue(r.equals(q));
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
/**
* subMap returns map with keys in requested range
*/
public void testSubMapContents() {
TreeMap map = map5();
NavigableMap sm = map.subMap(two, true, four, false);
assertEquals(two, sm.firstKey());
assertEquals(three, sm.lastKey());
assertEquals(2, sm.size());
assertFalse(sm.containsKey(one));
assertTrue(sm.containsKey(two));
assertTrue(sm.containsKey(three));
assertFalse(sm.containsKey(four));
assertFalse(sm.containsKey(five));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
assertFalse(i.hasNext());
Iterator r = sm.descendingKeySet().iterator();
k = (Integer)(r.next());
assertEquals(three, k);
k = (Integer)(r.next());
assertEquals(two, k);
assertFalse(r.hasNext());
Iterator j = sm.keySet().iterator();
j.next();
j.remove();
assertFalse(map.containsKey(two));
assertEquals(4, map.size());
assertEquals(1, sm.size());
assertEquals(three, sm.firstKey());
assertEquals(three, sm.lastKey());
assertTrue(sm.remove(three) != null);
assertTrue(sm.isEmpty());
assertEquals(3, map.size());
}
public void testSubMapContents2() {
TreeMap map = map5();
NavigableMap sm = map.subMap(two, true, three, false);
assertEquals(1, sm.size());
assertEquals(two, sm.firstKey());
assertEquals(two, sm.lastKey());
assertFalse(sm.containsKey(one));
assertTrue(sm.containsKey(two));
assertFalse(sm.containsKey(three));
assertFalse(sm.containsKey(four));
assertFalse(sm.containsKey(five));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
assertFalse(i.hasNext());
Iterator r = sm.descendingKeySet().iterator();
k = (Integer)(r.next());
assertEquals(two, k);
assertFalse(r.hasNext());
Iterator j = sm.keySet().iterator();
j.next();
j.remove();
assertFalse(map.containsKey(two));
assertEquals(4, map.size());
assertEquals(0, sm.size());
assertTrue(sm.isEmpty());
assertTrue(sm.remove(three) == null);
assertEquals(4, map.size());
}
/**
* headMap returns map with keys in requested range
*/
public void testHeadMapContents() {
TreeMap map = map5();
NavigableMap sm = map.headMap(four, false);
assertTrue(sm.containsKey(one));
assertTrue(sm.containsKey(two));
assertTrue(sm.containsKey(three));
assertFalse(sm.containsKey(four));
assertFalse(sm.containsKey(five));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(one, k);
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
assertFalse(i.hasNext());
sm.clear();
assertTrue(sm.isEmpty());
assertEquals(2, map.size());
assertEquals(four, map.firstKey());
}
/**
* headMap returns map with keys in requested range
*/
public void testTailMapContents() {
TreeMap map = map5();
NavigableMap sm = map.tailMap(two, true);
assertFalse(sm.containsKey(one));
assertTrue(sm.containsKey(two));
assertTrue(sm.containsKey(three));
assertTrue(sm.containsKey(four));
assertTrue(sm.containsKey(five));
Iterator i = sm.keySet().iterator();
Object k;
k = (Integer)(i.next());
assertEquals(two, k);
k = (Integer)(i.next());
assertEquals(three, k);
k = (Integer)(i.next());
assertEquals(four, k);
k = (Integer)(i.next());
assertEquals(five, k);
assertFalse(i.hasNext());
Iterator r = sm.descendingKeySet().iterator();
k = (Integer)(r.next());
assertEquals(five, k);
k = (Integer)(r.next());
assertEquals(four, k);
k = (Integer)(r.next());
assertEquals(three, k);
k = (Integer)(r.next());
assertEquals(two, k);
assertFalse(r.hasNext());
Iterator ei = sm.entrySet().iterator();
Map.Entry e;
e = (Map.Entry)(ei.next());
assertEquals(two, e.getKey());
assertEquals("B", e.getValue());
e = (Map.Entry)(ei.next());
assertEquals(three, e.getKey());
assertEquals("C", e.getValue());
e = (Map.Entry)(ei.next());
assertEquals(four, e.getKey());
assertEquals("D", e.getValue());
e = (Map.Entry)(ei.next());
assertEquals(five, e.getKey());
assertEquals("E", e.getValue());
assertFalse(i.hasNext());
NavigableMap ssm = sm.tailMap(four, true);
assertEquals(four, ssm.firstKey());
assertEquals(five, ssm.lastKey());
assertTrue(ssm.remove(four) != null);
assertEquals(1, ssm.size());
assertEquals(3, sm.size());
assertEquals(4, map.size());
}
Random rnd = new Random(666);
BitSet bs;
/**
* Submaps of submaps subdivide correctly
*/
public void testRecursiveSubMaps() {
int mapSize = 1000;
Class cl = TreeMap.class;
NavigableMap map = newMap(cl);
bs = new BitSet(mapSize);
populate(map, mapSize);
check(map, 0, mapSize - 1, true);
check(map.descendingMap(), 0, mapSize - 1, false);
mutateMap(map, 0, mapSize - 1);
check(map, 0, mapSize - 1, true);
check(map.descendingMap(), 0, mapSize - 1, false);
bashSubMap(map.subMap(new Integer(0), true, new Integer(mapSize), false),
0, mapSize - 1, true);
}
static NavigableMap newMap(Class cl) {
NavigableMap result = null;
try {
result = (NavigableMap) cl.newInstance();
} catch(Exception e) {
fail();
}
assertEquals(result.size(), 0);
assertFalse(result.keySet().iterator().hasNext());
return result;
}
void populate(NavigableMap map, int limit) {
for (int i = 0, n = 2 * limit / 3; i < n; i++) {
int key = rnd.nextInt(limit);
put(map, key);
}
}
void mutateMap(NavigableMap map, int min, int max) {
int size = map.size();
int rangeSize = max - min + 1;
// Remove a bunch of entries directly
for (int i = 0, n = rangeSize / 2; i < n; i++) {
remove(map, min - 5 + rnd.nextInt(rangeSize + 10));
}
// Remove a bunch of entries with iterator
for(Iterator it = map.keySet().iterator(); it.hasNext(); ) {
if (rnd.nextBoolean()) {
bs.clear(((Integer)it.next()).intValue());
it.remove();
}
}
// Add entries till we're back to original size
while (map.size() < size) {
int key = min + rnd.nextInt(rangeSize);
assertTrue(key >= min && key<= max);
put(map, key);
}
}
void mutateSubMap(NavigableMap map, int min, int max) {
int size = map.size();
int rangeSize = max - min + 1;
// Remove a bunch of entries directly
for (int i = 0, n = rangeSize / 2; i < n; i++) {
remove(map, min - 5 + rnd.nextInt(rangeSize + 10));
}
// Remove a bunch of entries with iterator
for(Iterator it = map.keySet().iterator(); it.hasNext(); ) {
if (rnd.nextBoolean()) {
bs.clear(((Integer)it.next()).intValue());
it.remove();
}
}
// Add entries till we're back to original size
while (map.size() < size) {
int key = min - 5 + rnd.nextInt(rangeSize + 10);
if (key >= min && key<= max) {
put(map, key);
} else {
try {
map.put(new Integer(key), new Integer(2 * key));
fail();
} catch(IllegalArgumentException e) {
// expected
}
}
}
}
void put(NavigableMap map, int key) {
if (map.put(new Integer(key), new Integer(2 * key)) == null)
bs.set(key);
}
void remove(NavigableMap map, int key) {
if (map.remove(new Integer(key)) != null)
bs.clear(key);
}
void bashSubMap(NavigableMap map,
int min, int max, boolean ascending) {
check(map, min, max, ascending);
check(map.descendingMap(), min, max, !ascending);
mutateSubMap(map, min, max);
check(map, min, max, ascending);
check(map.descendingMap(), min, max, !ascending);
// Recurse
if (max - min < 2)
return;
int midPoint = (min + max) / 2;
// headMap - pick direction and endpoint inclusion randomly
boolean incl = rnd.nextBoolean();
NavigableMap hm = map.headMap(new Integer(midPoint), incl);
if (ascending) {
if (rnd.nextBoolean())
bashSubMap(hm, min, midPoint - (incl ? 0 : 1), true);
else
bashSubMap(hm.descendingMap(), min, midPoint - (incl ? 0 : 1),
false);
} else {
if (rnd.nextBoolean())
bashSubMap(hm, midPoint + (incl ? 0 : 1), max, false);
else
bashSubMap(hm.descendingMap(), midPoint + (incl ? 0 : 1), max,
true);
}
// tailMap - pick direction and endpoint inclusion randomly
incl = rnd.nextBoolean();
NavigableMap tm = map.tailMap(new Integer(midPoint),incl);
if (ascending) {
if (rnd.nextBoolean())
bashSubMap(tm, midPoint + (incl ? 0 : 1), max, true);
else
bashSubMap(tm.descendingMap(), midPoint + (incl ? 0 : 1), max,
false);
} else {
if (rnd.nextBoolean()) {
bashSubMap(tm, min, midPoint - (incl ? 0 : 1), false);
} else {
bashSubMap(tm.descendingMap(), min, midPoint - (incl ? 0 : 1),
true);
}
}
// subMap - pick direction and endpoint inclusion randomly
int rangeSize = max - min + 1;
int[] endpoints = new int[2];
endpoints[0] = min + rnd.nextInt(rangeSize);
endpoints[1] = min + rnd.nextInt(rangeSize);
Arrays.sort(endpoints);
boolean lowIncl = rnd.nextBoolean();
boolean highIncl = rnd.nextBoolean();
if (ascending) {
NavigableMap sm = map.subMap(
new Integer(endpoints[0]), lowIncl, new Integer(endpoints[1]), highIncl);
if (rnd.nextBoolean())
bashSubMap(sm, endpoints[0] + (lowIncl ? 0 : 1),
endpoints[1] - (highIncl ? 0 : 1), true);
else
bashSubMap(sm.descendingMap(), endpoints[0] + (lowIncl ? 0 : 1),
endpoints[1] - (highIncl ? 0 : 1), false);
} else {
NavigableMap sm = map.subMap(
new Integer(endpoints[1]), highIncl, new Integer(endpoints[0]), lowIncl);
if (rnd.nextBoolean())
bashSubMap(sm, endpoints[0] + (lowIncl ? 0 : 1),
endpoints[1] - (highIncl ? 0 : 1), false);
else
bashSubMap(sm.descendingMap(), endpoints[0] + (lowIncl ? 0 : 1),
endpoints[1] - (highIncl ? 0 : 1), true);
}
}
/**
* min and max are both inclusive. If max < min, interval is empty.
*/
void check(NavigableMap map,
final int min, final int max, final boolean ascending) {
class ReferenceSet {
int lower(int key) {
return ascending ? lowerAscending(key) : higherAscending(key);
}
int floor(int key) {
return ascending ? floorAscending(key) : ceilingAscending(key);
}
int ceiling(int key) {
return ascending ? ceilingAscending(key) : floorAscending(key);
}
int higher(int key) {
return ascending ? higherAscending(key) : lowerAscending(key);
}
int first() {
return ascending ? firstAscending() : lastAscending();
}
int last() {
return ascending ? lastAscending() : firstAscending();
}
int lowerAscending(int key) {
return floorAscending(key - 1);
}
int floorAscending(int key) {
if (key < min)
return -1;
else if (key > max)
key = max;
// BitSet should support this! Test would run much faster
while (key >= min) {
if (bs.get(key))
return(key);
key--;
}
return -1;
}
int ceilingAscending(int key) {
if (key < min)
key = min;
else if (key > max)
return -1;
int result = bs.nextSetBit(key);
return result > max ? -1 : result;
}
int higherAscending(int key) {
return ceilingAscending(key + 1);
}
private int firstAscending() {
int result = ceilingAscending(min);
return result > max ? -1 : result;
}
private int lastAscending() {
int result = floorAscending(max);
return result < min ? -1 : result;
}
}
ReferenceSet rs = new ReferenceSet();
// Test contents using containsKey
int size = 0;
for (int i = min; i <= max; i++) {
boolean bsContainsI = bs.get(i);
assertEquals(bsContainsI, map.containsKey(new Integer(i)));
if (bsContainsI)
size++;
}
assertEquals(map.size(), size);
// Test contents using contains keySet iterator
int size2 = 0;
int previousKey = -1;
for (Iterator itr = map.keySet().iterator(); itr.hasNext();) {
int key = ((Integer)itr.next()).intValue();
assertTrue(bs.get(key));
size2++;
assertTrue(previousKey < 0 ||
(ascending ? key - previousKey > 0 : key - previousKey < 0));
previousKey = key;
}
assertEquals(size2, size);
// Test navigation ops
for (int key = min - 1; key <= max + 1; key++) {
assertEq((Integer)map.lowerKey(new Integer(key)), rs.lower(key));
assertEq((Integer)map.floorKey(new Integer(key)), rs.floor(key));
assertEq((Integer)map.higherKey(new Integer(key)), rs.higher(key));
assertEq((Integer)map.ceilingKey(new Integer(key)), rs.ceiling(key));
}
// Test extrema
if (map.size() != 0) {
assertEq((Integer)map.firstKey(), rs.first());
assertEq((Integer)map.lastKey(), rs.last());
} else {
assertEq(new Integer(rs.first()), -1);
assertEq(new Integer(rs.last()), -1);
try {
map.firstKey();
fail();
} catch(NoSuchElementException e) {
// expected
}
try {
map.lastKey();
fail();
} catch(NoSuchElementException e) {
// expected
}
}
}
static void assertEq(Integer i, int j) {
if (i == null)
assertEquals(j, -1);
else
assertEquals(i.intValue(), j);
}
static boolean eq(Integer i, int j) {
return i == null ? j == -1 : i.intValue() == j;
}
}
backport-util-concurrent-3.1-src/test/tck/src/TimeUnitTest.java 0000644 0017507 0003772 00000042421 10173315701 023477 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.io.*;
public class TimeUnitTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static Test suite() {
return new TestSuite(TimeUnitTest.class);
}
// (loops to 88888 check increments at all time divisions.)
/**
* convert correctly converts sample values across the units
*/
public void testConvert() {
for (long t = 0; t < 88888; ++t) {
assertEquals(t*60*60*24,
TimeUnit.SECONDS.convert(t,
TimeUnit.DAYS));
assertEquals(t*60*60,
TimeUnit.SECONDS.convert(t,
TimeUnit.HOURS));
assertEquals(t*60,
TimeUnit.SECONDS.convert(t,
TimeUnit.MINUTES));
assertEquals(t,
TimeUnit.SECONDS.convert(t,
TimeUnit.SECONDS));
assertEquals(t,
TimeUnit.SECONDS.convert(1000L*t,
TimeUnit.MILLISECONDS));
assertEquals(t,
TimeUnit.SECONDS.convert(1000000L*t,
TimeUnit.MICROSECONDS));
assertEquals(t,
TimeUnit.SECONDS.convert(1000000000L*t,
TimeUnit.NANOSECONDS));
assertEquals(1000L*t*60*60*24,
TimeUnit.MILLISECONDS.convert(t,
TimeUnit.DAYS));
assertEquals(1000L*t*60*60,
TimeUnit.MILLISECONDS.convert(t,
TimeUnit.HOURS));
assertEquals(1000L*t*60,
TimeUnit.MILLISECONDS.convert(t,
TimeUnit.MINUTES));
assertEquals(1000L*t,
TimeUnit.MILLISECONDS.convert(t,
TimeUnit.SECONDS));
assertEquals(t,
TimeUnit.MILLISECONDS.convert(t,
TimeUnit.MILLISECONDS));
assertEquals(t,
TimeUnit.MILLISECONDS.convert(1000L*t,
TimeUnit.MICROSECONDS));
assertEquals(t,
TimeUnit.MILLISECONDS.convert(1000000L*t,
TimeUnit.NANOSECONDS));
assertEquals(1000000L*t*60*60*24,
TimeUnit.MICROSECONDS.convert(t,
TimeUnit.DAYS));
assertEquals(1000000L*t*60*60,
TimeUnit.MICROSECONDS.convert(t,
TimeUnit.HOURS));
assertEquals(1000000L*t*60,
TimeUnit.MICROSECONDS.convert(t,
TimeUnit.MINUTES));
assertEquals(1000000L*t,
TimeUnit.MICROSECONDS.convert(t,
TimeUnit.SECONDS));
assertEquals(1000L*t,
TimeUnit.MICROSECONDS.convert(t,
TimeUnit.MILLISECONDS));
assertEquals(t,
TimeUnit.MICROSECONDS.convert(t,
TimeUnit.MICROSECONDS));
assertEquals(t,
TimeUnit.MICROSECONDS.convert(1000L*t,
TimeUnit.NANOSECONDS));
assertEquals(1000000000L*t*60*60*24,
TimeUnit.NANOSECONDS.convert(t,
TimeUnit.DAYS));
assertEquals(1000000000L*t*60*60,
TimeUnit.NANOSECONDS.convert(t,
TimeUnit.HOURS));
assertEquals(1000000000L*t*60,
TimeUnit.NANOSECONDS.convert(t,
TimeUnit.MINUTES));
assertEquals(1000000000L*t,
TimeUnit.NANOSECONDS.convert(t,
TimeUnit.SECONDS));
assertEquals(1000000L*t,
TimeUnit.NANOSECONDS.convert(t,
TimeUnit.MILLISECONDS));
assertEquals(1000L*t,
TimeUnit.NANOSECONDS.convert(t,
TimeUnit.MICROSECONDS));
assertEquals(t,
TimeUnit.NANOSECONDS.convert(t,
TimeUnit.NANOSECONDS));
}
}
/**
* toNanos correctly converts sample values in different units to
* nanoseconds
*/
public void testToNanos() {
for (long t = 0; t < 88888; ++t) {
assertEquals(t*1000000000L*60*60*24,
TimeUnit.DAYS.toNanos(t));
assertEquals(t*1000000000L*60*60,
TimeUnit.HOURS.toNanos(t));
assertEquals(t*1000000000L*60,
TimeUnit.MINUTES.toNanos(t));
assertEquals(1000000000L*t,
TimeUnit.SECONDS.toNanos(t));
assertEquals(1000000L*t,
TimeUnit.MILLISECONDS.toNanos(t));
assertEquals(1000L*t,
TimeUnit.MICROSECONDS.toNanos(t));
assertEquals(t,
TimeUnit.NANOSECONDS.toNanos(t));
}
}
/**
* toMicros correctly converts sample values in different units to
* microseconds
*/
public void testToMicros() {
for (long t = 0; t < 88888; ++t) {
assertEquals(t*1000000L*60*60*24,
TimeUnit.DAYS.toMicros(t));
assertEquals(t*1000000L*60*60,
TimeUnit.HOURS.toMicros(t));
assertEquals(t*1000000L*60,
TimeUnit.MINUTES.toMicros(t));
assertEquals(1000000L*t,
TimeUnit.SECONDS.toMicros(t));
assertEquals(1000L*t,
TimeUnit.MILLISECONDS.toMicros(t));
assertEquals(t,
TimeUnit.MICROSECONDS.toMicros(t));
assertEquals(t,
TimeUnit.NANOSECONDS.toMicros(t*1000L));
}
}
/**
* toMillis correctly converts sample values in different units to
* milliseconds
*/
public void testToMillis() {
for (long t = 0; t < 88888; ++t) {
assertEquals(t*1000L*60*60*24,
TimeUnit.DAYS.toMillis(t));
assertEquals(t*1000L*60*60,
TimeUnit.HOURS.toMillis(t));
assertEquals(t*1000L*60,
TimeUnit.MINUTES.toMillis(t));
assertEquals(1000L*t,
TimeUnit.SECONDS.toMillis(t));
assertEquals(t,
TimeUnit.MILLISECONDS.toMillis(t));
assertEquals(t,
TimeUnit.MICROSECONDS.toMillis(t*1000L));
assertEquals(t,
TimeUnit.NANOSECONDS.toMillis(t*1000000L));
}
}
/**
* toSeconds correctly converts sample values in different units to
* seconds
*/
public void testToSeconds() {
for (long t = 0; t < 88888; ++t) {
assertEquals(t*60*60*24,
TimeUnit.DAYS.toSeconds(t));
assertEquals(t*60*60,
TimeUnit.HOURS.toSeconds(t));
assertEquals(t*60,
TimeUnit.MINUTES.toSeconds(t));
assertEquals(t,
TimeUnit.SECONDS.toSeconds(t));
assertEquals(t,
TimeUnit.MILLISECONDS.toSeconds(t*1000L));
assertEquals(t,
TimeUnit.MICROSECONDS.toSeconds(t*1000000L));
assertEquals(t,
TimeUnit.NANOSECONDS.toSeconds(t*1000000000L));
}
}
/**
* toMinutes correctly converts sample values in different units to
* minutes
*/
public void testToMinutes() {
for (long t = 0; t < 88888; ++t) {
assertEquals(t*60*24,
TimeUnit.DAYS.toMinutes(t));
assertEquals(t*60,
TimeUnit.HOURS.toMinutes(t));
assertEquals(t,
TimeUnit.MINUTES.toMinutes(t));
assertEquals(t,
TimeUnit.SECONDS.toMinutes(t*60));
assertEquals(t,
TimeUnit.MILLISECONDS.toMinutes(t*1000L*60));
assertEquals(t,
TimeUnit.MICROSECONDS.toMinutes(t*1000000L*60));
assertEquals(t,
TimeUnit.NANOSECONDS.toMinutes(t*1000000000L*60));
}
}
/**
* toHours correctly converts sample values in different units to
* hours
*/
public void testToHours() {
for (long t = 0; t < 88888; ++t) {
assertEquals(t*24,
TimeUnit.DAYS.toHours(t));
assertEquals(t,
TimeUnit.HOURS.toHours(t));
assertEquals(t,
TimeUnit.MINUTES.toHours(t*60));
assertEquals(t,
TimeUnit.SECONDS.toHours(t*60*60));
assertEquals(t,
TimeUnit.MILLISECONDS.toHours(t*1000L*60*60));
assertEquals(t,
TimeUnit.MICROSECONDS.toHours(t*1000000L*60*60));
assertEquals(t,
TimeUnit.NANOSECONDS.toHours(t*1000000000L*60*60));
}
}
/**
* toDays correctly converts sample values in different units to
* days
*/
public void testToDays() {
for (long t = 0; t < 88888; ++t) {
assertEquals(t,
TimeUnit.DAYS.toDays(t));
assertEquals(t,
TimeUnit.HOURS.toDays(t*24));
assertEquals(t,
TimeUnit.MINUTES.toDays(t*60*24));
assertEquals(t,
TimeUnit.SECONDS.toDays(t*60*60*24));
assertEquals(t,
TimeUnit.MILLISECONDS.toDays(t*1000L*60*60*24));
assertEquals(t,
TimeUnit.MICROSECONDS.toDays(t*1000000L*60*60*24));
assertEquals(t,
TimeUnit.NANOSECONDS.toDays(t*1000000000L*60*60*24));
}
}
/**
* convert saturates positive too-large values to Long.MAX_VALUE
* and negative to LONG.MIN_VALUE
*/
public void testConvertSaturate() {
assertEquals(Long.MAX_VALUE,
TimeUnit.NANOSECONDS.convert(Long.MAX_VALUE / 2,
TimeUnit.SECONDS));
assertEquals(Long.MIN_VALUE,
TimeUnit.NANOSECONDS.convert(-Long.MAX_VALUE / 4,
TimeUnit.SECONDS));
assertEquals(Long.MAX_VALUE,
TimeUnit.NANOSECONDS.convert(Long.MAX_VALUE / 2,
TimeUnit.MINUTES));
assertEquals(Long.MIN_VALUE,
TimeUnit.NANOSECONDS.convert(-Long.MAX_VALUE / 4,
TimeUnit.MINUTES));
assertEquals(Long.MAX_VALUE,
TimeUnit.NANOSECONDS.convert(Long.MAX_VALUE / 2,
TimeUnit.HOURS));
assertEquals(Long.MIN_VALUE,
TimeUnit.NANOSECONDS.convert(-Long.MAX_VALUE / 4,
TimeUnit.HOURS));
assertEquals(Long.MAX_VALUE,
TimeUnit.NANOSECONDS.convert(Long.MAX_VALUE / 2,
TimeUnit.DAYS));
assertEquals(Long.MIN_VALUE,
TimeUnit.NANOSECONDS.convert(-Long.MAX_VALUE / 4,
TimeUnit.DAYS));
}
/**
* toNanos saturates positive too-large values to Long.MAX_VALUE
* and negative to LONG.MIN_VALUE
*/
public void testToNanosSaturate() {
assertEquals(Long.MAX_VALUE,
TimeUnit.MILLISECONDS.toNanos(Long.MAX_VALUE / 2));
assertEquals(Long.MIN_VALUE,
TimeUnit.MILLISECONDS.toNanos(-Long.MAX_VALUE / 3));
}
/**
* toString returns string containing common name of unit
*/
public void testToString() {
String s = TimeUnit.SECONDS.toString();
assertTrue(s.indexOf("ECOND") >= 0);
}
/**
* Timed wait without holding lock throws
* IllegalMonitorStateException
*/
public void testTimedWait_IllegalMonitorException() {
//created a new thread with anonymous runnable
Thread t = new Thread(new Runnable() {
public void run() {
Object o = new Object();
TimeUnit tu = TimeUnit.MILLISECONDS;
try {
tu.timedWait(o,LONG_DELAY_MS);
threadShouldThrow();
}
catch (InterruptedException ie) {
threadUnexpectedException();
}
catch(IllegalMonitorStateException success) {
}
}
});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch(Exception e) {
unexpectedException();
}
}
/**
* timedWait throws InterruptedException when interrupted
*/
public void testTimedWait() {
Thread t = new Thread(new Runnable() {
public void run() {
Object o = new Object();
TimeUnit tu = TimeUnit.MILLISECONDS;
try {
synchronized(o) {
tu.timedWait(o,MEDIUM_DELAY_MS);
}
threadShouldThrow();
}
catch(InterruptedException success) {}
catch(IllegalMonitorStateException failure) {
threadUnexpectedException();
}
}
});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch(Exception e) {
unexpectedException();
}
}
/**
* timedJoin throws InterruptedException when interrupted
*/
public void testTimedJoin() {
Thread t = new Thread(new Runnable() {
public void run() {
TimeUnit tu = TimeUnit.MILLISECONDS;
try {
Thread s = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(MEDIUM_DELAY_MS);
} catch(InterruptedException success){}
}
});
s.start();
tu.timedJoin(s,MEDIUM_DELAY_MS);
threadShouldThrow();
}
catch(Exception e) {}
}
});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch(Exception e) {
unexpectedException();
}
}
/**
* timedSleep throws InterruptedException when interrupted
*/
public void testTimedSleep() {
//created a new thread with anonymous runnable
Thread t = new Thread(new Runnable() {
public void run() {
TimeUnit tu = TimeUnit.MILLISECONDS;
try {
tu.sleep(MEDIUM_DELAY_MS);
threadShouldThrow();
}
catch(InterruptedException success) {}
}
});
t.start();
try {
Thread.sleep(SHORT_DELAY_MS);
t.interrupt();
t.join();
} catch(Exception e) {
unexpectedException();
}
}
/**
* a deserialized serialized unit is equal
*/
public void testSerialization() {
TimeUnit q = TimeUnit.MILLISECONDS;
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(q);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
TimeUnit r = (TimeUnit)in.readObject();
assertEquals(q.toString(), r.toString());
} catch(Exception e){
e.printStackTrace();
unexpectedException();
}
}
}
backport-util-concurrent-3.1-src/test/tck/LinkedListTest.java 0000644 0017507 0003772 00000037215 10262045450 023221 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import junit.framework.*;
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
public class LinkedListTest extends JSR166TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(LinkedListTest.class);
}
/**
* Create a queue of given size containing consecutive
* Integers 0 ... n.
*/
private LinkedList populatedQueue(int n) {
LinkedList q = new LinkedList();
assertTrue(q.isEmpty());
for(int i = 0; i < n; ++i)
assertTrue(q.offer(new Integer(i)));
assertFalse(q.isEmpty());
assertEquals(n, q.size());
return q;
}
/**
* new queue is empty
*/
public void testConstructor1() {
assertEquals(0, new LinkedList().size());
}
/**
* Initializing from null Collection throws NPE
*/
public void testConstructor3() {
try {
LinkedList q = new LinkedList((Collection)null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Queue contains all elements of collection used to initialize
*/
public void testConstructor6() {
try {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
LinkedList q = new LinkedList(Arrays.asList(ints));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* isEmpty is true before add, false after
*/
public void testEmpty() {
LinkedList q = new LinkedList();
assertTrue(q.isEmpty());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.add(new Integer(2));
q.remove();
q.remove();
assertTrue(q.isEmpty());
}
/**
* size changes when elements added and removed
*/
public void testSize() {
LinkedList q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE-i, q.size());
q.remove();
}
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
q.add(new Integer(i));
}
}
/**
* offer(null) succeeds
*/
public void testOfferNull() {
try {
LinkedList q = new LinkedList();
q.offer(null);
} catch (NullPointerException ie) {
unexpectedException();
}
}
/**
* Offer succeeds
*/
public void testOffer() {
LinkedList q = new LinkedList();
assertTrue(q.offer(new Integer(0)));
assertTrue(q.offer(new Integer(1)));
}
/**
* add succeeds
*/
public void testAdd() {
LinkedList q = new LinkedList();
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
assertTrue(q.add(new Integer(i)));
}
}
/**
* addAll(null) throws NPE
*/
public void testAddAll1() {
try {
LinkedList q = new LinkedList();
q.addAll(null);
shouldThrow();
}
catch (NullPointerException success) {}
}
/**
* Queue contains all elements, in traversal order, of successful addAll
*/
public void testAddAll5() {
try {
Integer[] empty = new Integer[0];
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
LinkedList q = new LinkedList();
assertFalse(q.addAll(Arrays.asList(empty)));
assertTrue(q.addAll(Arrays.asList(ints)));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.poll());
}
finally {}
}
/**
* addAll with too large an index throws IOOBE
*/
public void testAddAll2_IndexOutOfBoundsException() {
try {
LinkedList l = new LinkedList();
l.add(new Object());
LinkedList m = new LinkedList();
m.add(new Object());
l.addAll(4,m);
shouldThrow();
} catch(IndexOutOfBoundsException success) {}
}
/**
* addAll with negative index throws IOOBE
*/
public void testAddAll4_BadIndex() {
try {
LinkedList l = new LinkedList();
l.add(new Object());
LinkedList m = new LinkedList();
m.add(new Object());
l.addAll(-1,m);
shouldThrow();
} catch(IndexOutOfBoundsException success){}
}
/**
* poll succeeds unless empty
*/
public void testPoll() {
LinkedList q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.poll()).intValue());
}
assertNull(q.poll());
}
/**
* peek returns next element, or null if empty
*/
public void testPeek() {
LinkedList q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.peek()).intValue());
q.poll();
assertTrue(q.peek() == null ||
i != ((Integer)q.peek()).intValue());
}
assertNull(q.peek());
}
/**
* element returns next element, or throws NSEE if empty
*/
public void testElement() {
LinkedList q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.element()).intValue());
q.poll();
}
try {
q.element();
shouldThrow();
}
catch (NoSuchElementException success) {}
}
/**
* remove removes next element, or throws NSEE if empty
*/
public void testRemove() {
LinkedList q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.remove()).intValue());
}
try {
q.remove();
shouldThrow();
} catch (NoSuchElementException success){
}
}
/**
* remove(x) removes x and returns true if present
*/
public void testRemoveElement() {
LinkedList q = populatedQueue(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.remove(new Integer(i)));
assertFalse(q.remove(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* contains(x) reports true when elements added but not yet removed
*/
public void testContains() {
LinkedList q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.contains(new Integer(i)));
q.poll();
assertFalse(q.contains(new Integer(i)));
}
}
/**
* clear removes all elements
*/
public void testClear() {
LinkedList q = populatedQueue(SIZE);
q.clear();
assertTrue(q.isEmpty());
assertEquals(0, q.size());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.clear();
assertTrue(q.isEmpty());
}
/**
* containsAll(c) is true when c contains a subset of elements
*/
public void testContainsAll() {
LinkedList q = populatedQueue(SIZE);
LinkedList p = new LinkedList();
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.containsAll(p));
assertFalse(p.containsAll(q));
p.add(new Integer(i));
}
assertTrue(p.containsAll(q));
}
/**
* retainAll(c) retains only those elements of c and reports true if changed
*/
public void testRetainAll() {
LinkedList q = populatedQueue(SIZE);
LinkedList p = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
boolean changed = q.retainAll(p);
if (i == 0)
assertFalse(changed);
else
assertTrue(changed);
assertTrue(q.containsAll(p));
assertEquals(SIZE-i, q.size());
p.remove();
}
}
/**
* removeAll(c) removes only those elements of c and reports true if changed
*/
public void testRemoveAll() {
for (int i = 1; i < SIZE; ++i) {
LinkedList q = populatedQueue(SIZE);
LinkedList p = populatedQueue(i);
assertTrue(q.removeAll(p));
assertEquals(SIZE-i, q.size());
for (int j = 0; j < i; ++j) {
Integer Object = (Integer)(p.remove());
assertFalse(q.contains);
}
}
}
/**
* toArray contains all elements
*/
public void testToArray() {
LinkedList q = populatedQueue(SIZE);
Object[] o = q.toArray();
Arrays.sort(o);
for(int i = 0; i < o.length; i++)
assertEquals(o[i], q.poll());
}
/**
* toArray(a) contains all elements
*/
public void testToArray2() {
LinkedList q = populatedQueue(SIZE);
Integer[] ints = new Integer[SIZE];
ints = (Integer[])q.toArray(ints);
Arrays.sort(ints);
for(int i = 0; i < ints.length; i++)
assertEquals(ints[i], q.poll());
}
/**
* toArray(null) throws NPE
*/
public void testToArray_BadArg() {
try {
LinkedList l = new LinkedList();
l.add(new Object());
Object o[] = l.toArray(null);
shouldThrow();
} catch(NullPointerException success){}
}
/**
* toArray with incompatable aray type throws CCE
*/
public void testToArray1_BadArg() {
try {
LinkedList l = new LinkedList();
l.add(new Integer(5));
Object o[] = l.toArray(new String[10] );
shouldThrow();
} catch(ArrayStoreException success){}
}
/**
* iterator iterates through all elements
*/
public void testIterator() {
LinkedList q = populatedQueue(SIZE);
int i = 0;
Iterator it = q.iterator();
while(it.hasNext()) {
assertTrue(q.contains(it.next()));
++i;
}
assertEquals(i, SIZE);
}
/**
* iterator ordering is FIFO
*/
public void testIteratorOrdering() {
final LinkedList q = new LinkedList();
q.add(new Integer(1));
q.add(new Integer(2));
q.add(new Integer(3));
int k = 0;
for (Iterator it = q.iterator(); it.hasNext();) {
int i = ((Integer)(it.next())).intValue();
assertEquals(++k, i);
}
assertEquals(3, k);
}
/**
* iterator.remove removes current element
*/
public void testIteratorRemove () {
final LinkedList q = new LinkedList();
q.add(new Integer(1));
q.add(new Integer(2));
q.add(new Integer(3));
Iterator it = q.iterator();
it.next();
it.remove();
it = q.iterator();
assertEquals(it.next(), new Integer(2));
assertEquals(it.next(), new Integer(3));
assertFalse(it.hasNext());
}
/**
* toString contains toStrings of elements
*/
public void testToString() {
LinkedList q = populatedQueue(SIZE);
String s = q.toString();
for (int i = 0; i < SIZE; ++i) {
assertTrue(s.indexOf(String.valueOf(i)) >= 0);
}
}
/**
* peek returns element inserted with addFirst
*/
public void testAddFirst() {
LinkedList q = populatedQueue(3);
q.addFirst(four);
assertEquals(four,q.peek());
}
/**
* peekFirst returns element inserted with push
*/
public void testPush() {
LinkedList q = populatedQueue(3);
q.pollLast();
q.push(four);
assertEquals(four,q.peekFirst());
}
/**
* pop removes next element, or throws NSEE if empty
*/
public void testPop() {
LinkedList q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.pop()).intValue());
}
try {
q.pop();
shouldThrow();
} catch (NoSuchElementException success){
}
}
/**
* OfferFirst succeeds
*/
public void testOfferFirst() {
LinkedList q = new LinkedList();
assertTrue(q.offerFirst(new Integer(0)));
assertTrue(q.offerFirst(new Integer(1)));
}
/**
* OfferLast succeeds
*/
public void testOfferLast() {
LinkedList q = new LinkedList();
assertTrue(q.offerLast(new Integer(0)));
assertTrue(q.offerLast(new Integer(1)));
}
/**
* pollLast succeeds unless empty
*/
public void testPollLast() {
LinkedList q = populatedQueue(SIZE);
for (int i = SIZE-1; i >= 0; --i) {
assertEquals(i, ((Integer)q.pollLast()).intValue());
}
assertNull(q.pollLast());
}
/**
* peekFirst returns next element, or null if empty
*/
public void testPeekFirst() {
LinkedList q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.peekFirst()).intValue());
q.pollFirst();
assertTrue(q.peekFirst() == null ||
i != ((Integer)q.peekFirst()).intValue());
}
assertNull(q.peekFirst());
}
/**
* peekLast returns next element, or null if empty
*/
public void testPeekLast() {
LinkedList q = populatedQueue(SIZE);
for (int i = SIZE-1; i >= 0; --i) {
assertEquals(i, ((Integer)q.peekLast()).intValue());
q.pollLast();
assertTrue(q.peekLast() == null ||
i != ((Integer)q.peekLast()).intValue());
}
assertNull(q.peekLast());
}
public void testFirstElement() {
LinkedList q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, ((Integer)q.getFirst()).intValue());
q.pollFirst();
}
try {
q.getFirst();
shouldThrow();
}
catch (NoSuchElementException success) {}
}
/**
* getLast returns next element, or throws NSEE if empty
*/
public void testLastElement() {
LinkedList q = populatedQueue(SIZE);
for (int i = SIZE-1; i >= 0; --i) {
assertEquals(i, ((Integer)q.getLast()).intValue());
q.pollLast();
}
try {
q.getLast();
shouldThrow();
}
catch (NoSuchElementException success) {}
assertNull(q.peekLast());
}
/**
* removeFirstOccurrence(x) removes x and returns true if present
*/
public void testRemoveFirstOccurrence() {
LinkedList q = populatedQueue(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.removeFirstOccurrence(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.removeFirstOccurrence(new Integer(i)));
assertFalse(q.removeFirstOccurrence(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
/**
* removeLastOccurrence(x) removes x and returns true if present
*/
public void testRemoveLastOccurrence() {
LinkedList q = populatedQueue(SIZE);
for (int i = 1; i < SIZE; i+=2) {
assertTrue(q.removeLastOccurrence(new Integer(i)));
}
for (int i = 0; i < SIZE; i+=2) {
assertTrue(q.removeLastOccurrence(new Integer(i)));
assertFalse(q.removeLastOccurrence(new Integer(i+1)));
}
assertTrue(q.isEmpty());
}
}
backport-util-concurrent-3.1-src/test/tck/RECONCILED_ON 0000644 0017507 0003772 00000000013 10153210664 021364 0 ustar dawidk dcl 2004-11-30
backport-util-concurrent-3.1-src/test/loops/ 0000755 0017507 0003772 00000000000 10643402426 020022 5 ustar dawidk dcl backport-util-concurrent-3.1-src/test/loops/src/ 0000755 0017507 0003772 00000000000 10643402426 020611 5 ustar dawidk dcl backport-util-concurrent-3.1-src/test/loops/src/CancelledLockLoops.java 0000644 0017507 0003772 00000010554 10431260156 025156 0 ustar dawidk dcl /*
* @test
* @summary tests lockInterruptibly
* Checks for responsiveness of locks to interrupts. Runs under that
* assumption that ITERS_VALUE computations require more than TIMEOUT
* msecs to complete.
*/
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain. Use, modify, and
* redistribute this code in any way without acknowledgement.
*/
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
public final class CancelledLockLoops {
static final Random rng = new Random();
static boolean print = false;
static final int ITERS = 10000000;
static final long TIMEOUT = 100;
public static void main(String[] args) throws Exception {
int maxThreads = 100;
if (args.length > 0)
maxThreads = Integer.parseInt(args[0]);
print = true;
for (int i = 2; i <= maxThreads; i += (i+1) >>> 1) {
System.out.print("Threads: " + i);
try {
new ReentrantLockLoop(i).test();
}
catch(BrokenBarrierException bb) {
// OK, ignore
}
}
}
static final class ReentrantLockLoop implements Runnable {
private int v = rng.nextInt();
private int completed;
private volatile int result = 17;
private final ReentrantLock lock = new ReentrantLock();
private final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
private final CyclicBarrier barrier;
private final int nthreads;
ReentrantLockLoop(int nthreads) {
this.nthreads = nthreads;
barrier = new CyclicBarrier(nthreads+1, timer);
}
final void test() throws Exception {
Thread[] threads = new Thread[nthreads];
for (int i = 0; i < threads.length; ++i)
threads[i] = new Thread(this);
for (int i = 0; i < threads.length; ++i)
threads[i].start();
Thread[] cancels = (Thread[]) (threads.clone());
Collections.shuffle(Arrays.asList(cancels), rng);
barrier.await();
Thread.sleep(TIMEOUT);
for (int i = 0; i < cancels.length-2; ++i) {
cancels[i].interrupt();
// make sure all OK even when cancellations spaced out
if ( (i & 3) == 0)
Thread.sleep(1 + rng.nextInt(10));
}
barrier.await();
if (print) {
long time = timer.getTime();
double secs = (double)(time) / 1000000000.0;
System.out.println("\t " + secs + "s run time");
}
int c;
lock.lock();
try {
c = completed;
}
finally {
lock.unlock();
}
if (completed != 2)
throw new Error("Completed != 2");
int r = result;
if (r == 0) // avoid overoptimization
System.out.println("useless result: " + r);
}
public final void run() {
try {
barrier.await();
int sum = v;
int x = 0;
int n = ITERS;
boolean done = false;
do {
try {
lock.lockInterruptibly();
}
catch (InterruptedException ie) {
break;
}
try {
v = x = LoopHelpers.compute1(v);
}
finally {
lock.unlock();
}
sum += LoopHelpers.compute2(x);
} while (n-- > 0);
if (n <= 0) {
lock.lock();
try {
++completed;
}
finally {
lock.unlock();
}
}
barrier.await();
result += sum;
}
catch (Exception ex) {
// ex.printStackTrace();
return;
}
}
}
}
backport-util-concurrent-3.1-src/test/loops/src/StringMapLoops.java 0000644 0017507 0003772 00000015113 10346121124 024367 0 ustar dawidk dcl /*
* @test
* @synopsis Exercise multithreaded maps, by default
* ConcurrentHashMap. Each thread does a random walk though elements
* of "key" array. On each iteration, it checks if table includes key.
* If absent, with probablility pinsert it inserts it, and if present,
* with probablility premove it removes it. (pinsert and premove are
* expressed as percentages to simplify parsing from command line.)
*/
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain. Use, modify, and
* redistribute this code in any way without acknowledgement.
*/
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.util.Map;
import java.util.Random;
public class StringMapLoops {
static int nkeys = 1000;
static int pinsert = 60;
static int premove = 2;
static int maxThreads = 100;
static int nops = 1000000;
static int removesPerMaxRandom;
static int insertsPerMaxRandom;
static final ExecutorService pool = Executors.newCachedThreadPool();
public static void main(String[] args) throws Exception {
Class mapClass = null;
if (args.length > 0) {
try {
mapClass = Class.forName(args[0]);
} catch(ClassNotFoundException e) {
throw new RuntimeException("Class " + args[0] + " not found.");
}
}
else
mapClass = edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap.class;
if (args.length > 1)
maxThreads = Integer.parseInt(args[1]);
if (args.length > 2)
nkeys = Integer.parseInt(args[2]);
if (args.length > 3)
pinsert = Integer.parseInt(args[3]);
if (args.length > 4)
premove = Integer.parseInt(args[4]);
if (args.length > 5)
nops = Integer.parseInt(args[5]);
// normalize probabilities wrt random number generator
removesPerMaxRandom = (int)(((double)premove/100.0 * 0x7FFFFFFFL));
insertsPerMaxRandom = (int)(((double)pinsert/100.0 * 0x7FFFFFFFL));
System.out.print("Class: " + mapClass.getName());
System.out.print(" threads: " + maxThreads);
System.out.print(" size: " + nkeys);
System.out.print(" ins: " + pinsert);
System.out.print(" rem: " + premove);
System.out.print(" ops: " + nops);
System.out.println();
String[] key = makeKeys(nkeys);
int k = 1;
int warmups = 2;
for (int i = 1; i <= maxThreads;) {
Thread.sleep(100);
test(i, nkeys, key, mapClass);
shuffleKeys(key);
if (warmups > 0)
--warmups;
else if (i == k) {
k = i << 1;
i = i + (i >>> 1);
}
else if (i == 1 && k == 2) {
i = k;
warmups = 1;
}
else
i = k;
}
pool.shutdown();
}
static String[] makeKeys(int n) {
LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
String[] key = new String[n];
for (int i = 0; i < key.length; ++i) {
int k = 0;
int len = 1 + (rng.next() & 0xf);
char[] c = new char[len * 4];
for (int j = 0; j < len; ++j) {
int r = rng.next();
c[k++] = (char)(' ' + (r & 0x7f));
r >>>= 8;
c[k++] = (char)(' ' + (r & 0x7f));
r >>>= 8;
c[k++] = (char)(' ' + (r & 0x7f));
r >>>= 8;
c[k++] = (char)(' ' + (r & 0x7f));
}
key[i] = new String(c);
}
return key;
}
static void shuffleKeys(String[] key) {
Random rng = new Random();
for (int i = key.length; i > 1; --i) {
int j = rng.nextInt(i);
String tmp = key[j];
key[j] = key[i-1];
key[i-1] = tmp;
}
}
static void test(int i, int nkeys, String[] key, Class mapClass) throws Exception {
System.out.print("Threads: " + i + "\t:");
Map map = (Map)mapClass.newInstance();
// Uncomment to start with a non-empty table
// for (int j = 0; j < nkeys; j += 4) // start 1/4 occupied
// map.put(key[j], key[j]);
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier barrier = new CyclicBarrier(i+1, timer);
for (int t = 0; t < i; ++t)
pool.execute(new Runner(t, map, key, barrier));
barrier.await();
barrier.await();
long time = timer.getTime();
long tpo = time / (i * (long)nops);
System.out.print(LoopHelpers.rightJustify(tpo) + " ns per op");
double secs = (double)(time) / 1000000000.0;
System.out.println("\t " + secs + "s run time");
map.clear();
}
static class Runner implements Runnable {
final Map map;
final String[] key;
final LoopHelpers.SimpleRandom rng;
final CyclicBarrier barrier;
int position;
int total;
Runner(int id, Map map, String[] key, CyclicBarrier barrier) {
this.map = map;
this.key = key;
this.barrier = barrier;
position = key.length / 2;
rng = new LoopHelpers.SimpleRandom((id + 1) * 8862213513L);
rng.next();
}
int step() {
// random-walk around key positions, bunching accesses
int r = rng.next();
position += (r & 7) - 3;
while (position >= key.length) position -= key.length;
while (position < 0) position += key.length;
String k = key[position];
String x = (String)map.get(k);
if (x != null) {
if (r < removesPerMaxRandom) {
if (map.remove(k) != null) {
position = total % key.length; // move from position
return 2;
}
}
}
else if (r < insertsPerMaxRandom) {
++position;
map.put(k, k);
return 2;
}
total += r;
return 1;
}
public void run() {
try {
barrier.await();
int ops = nops;
while (ops > 0)
ops -= step();
barrier.await();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
backport-util-concurrent-3.1-src/test/loops/src/ExchangeLoops.java 0000644 0017507 0003772 00000011336 10431777323 024225 0 ustar dawidk dcl /*
* Written by Bill Scherer and Doug Lea with assistance from members
* of JCP JSR-166 Expert Group and released to the public domain. Use,
* modify, and redistribute this code in any way without
* acknowledgement.
*/
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import edu.emory.mathcs.backport.java.util.concurrent.helpers.Utils;
public class ExchangeLoops {
static final int NCPUS = Runtime.getRuntime().availableProcessors();
static final int DEFAULT_THREADS = NCPUS + 2;
static final long DEFAULT_TRIAL_MILLIS = 10000;
public static void main(String[] args) throws Exception {
int maxThreads = DEFAULT_THREADS;
long trialMillis = DEFAULT_TRIAL_MILLIS;
int nReps = 3;
// Parse and check args
int argc = 0;
while (argc < args.length) {
String option = args[argc++];
if (option.equals("-t"))
trialMillis = Integer.parseInt(args[argc]);
else if (option.equals("-r"))
nReps = Integer.parseInt(args[argc]);
else
maxThreads = Integer.parseInt(option);
argc++;
}
// Display runtime parameters
System.out.print("ExchangeTest");
System.out.print(" -t " + trialMillis);
System.out.print(" -r " + nReps);
System.out.print(" max threads " + maxThreads);
System.out.println();
long warmupTime = 2000;
long sleepTime = 100;
int nw = maxThreads >= 3? 3 : 2;
System.out.println("Warmups..");
oneRun(3, warmupTime);
Thread.sleep(sleepTime);
for (int i = maxThreads; i >= 2; i -= 1) {
oneRun(i, warmupTime++);
// System.gc();
Thread.sleep(sleepTime);
}
/*
for (int i = maxThreads; i >= 2; i -= 1) {
oneRun(i, warmupTime++);
}
*/
for (int j = 0; j < nReps; ++j) {
System.out.println("Trial: " + j);
for (int i = 2; i <= maxThreads; i += 2) {
oneRun(i, trialMillis);
// System.gc();
Thread.sleep(sleepTime);
}
for (int i = maxThreads; i >= 2; i -= 2) {
oneRun(i, trialMillis);
// System.gc();
Thread.sleep(sleepTime);
}
Thread.sleep(sleepTime);
}
}
static void oneRun(int nThreads, long trialMillis) throws Exception {
System.out.println(nThreads + " threads");
Exchanger x = new Exchanger();
Runner[] runners = new Runner[nThreads];
Thread[] threads = new Thread[nThreads];
for (int i = 0; i < nThreads; ++i) {
runners[i] = new Runner(x);
threads[i] = new Thread(runners[i]);
// int h = System.identityHashCode(threads[i]);
// h ^= h << 1;
// h ^= h >>> 3;
// h ^= h << 10;
// System.out.printf("%10x\n", h);
}
long startTime = Utils.nanoTime();
for (int i = 0; i < nThreads; ++i) {
threads[i].start();
}
Thread.sleep(trialMillis);
for (int i = 0; i < nThreads; ++i)
threads[i].interrupt();
long elapsed = Utils.nanoTime() - startTime;
for (int i = 0; i < nThreads; ++i)
threads[i].join();
int iters = 1;
// System.out.println();
for (int i = 0; i < nThreads; ++i) {
int ipr = runners[i].iters;
// System.out.println(ipr);
iters += ipr;
}
long rate = iters * 1000L * 1000L * 1000L / elapsed;
long npt = elapsed / iters;
System.out.println(elapsed / (1000L * 1000L) + "ms");
System.out.println(rate + " it/s ");
System.out.println(npt + " ns/it");
System.out.println();
// x.printStats();
}
static final class Runner implements Runnable {
final Exchanger exchanger;
final Object mine = new Integer(2688);
volatile int iters;
Runner(Exchanger x) { this.exchanger = x; }
public void run() {
Exchanger x = exchanger;
Object m = mine;
int i = 0;
try {
for (;;) {
Object e = x.exchange(m);
if (e == null || e == m)
throw new Error();
m = e;
++i;
}
} catch (InterruptedException ie) {
iters = i;
}
}
}
}
backport-util-concurrent-3.1-src/test/loops/src/NoopLockLoops.java 0000644 0017507 0003772 00000006174 10253737131 024226 0 ustar dawidk dcl /*
* @test
* @synopsis multiple threads using a single builtin lock
*/
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain. Use, modify, and
* redistribute this code in any way without acknowledgement.
*/
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import edu.emory.mathcs.backport.java.util.*;
public final class NoopLockLoops {
static final ExecutorService pool = Executors.newCachedThreadPool();
static final LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
static boolean print = false;
static int iters = 20000000;
public static void main(String[] args) throws Exception {
int maxThreads = 100;
if (args.length > 0)
maxThreads = Integer.parseInt(args[0]);
new ReentrantLockLoop(1).test();
new ReentrantLockLoop(1).test();
print = true;
int k = 1;
for (int i = 1; i <= maxThreads;) {
System.out.print("Threads: " + i);
new ReentrantLockLoop(i).test();
Thread.sleep(100);
if (i == k) {
k = i << 1;
i = i + (i >>> 1);
}
else
i = k;
}
pool.shutdown();
}
static final class ReentrantLockLoop implements Runnable {
private int v = rng.next();
private volatile int result = 17;
private final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
private final CyclicBarrier barrier;
private final int nthreads;
private volatile int readBarrier;
ReentrantLockLoop(int nthreads) {
this.nthreads = nthreads;
barrier = new CyclicBarrier(nthreads+1, timer);
}
final void test() throws Exception {
for (int i = 0; i < nthreads; ++i)
pool.execute(this);
barrier.await();
barrier.await();
if (print) {
long time = timer.getTime();
long tpi = time / ((long)iters * nthreads);
System.out.print("\t" + LoopHelpers.rightJustify(tpi) + " ns per lock");
double secs = (double)(time) / 1000000000.0;
System.out.println("\t " + secs + "s run time");
}
int r = result;
if (r == 0) // avoid overoptimization
System.out.println("useless result: " + r);
}
public final void run() {
try {
barrier.await();
int sum = v + 1;
int x = sum + 1;
int n = iters;
while (n-- > 0) {
synchronized(this) {
x = LoopHelpers.compute4(x);
}
sum += x;
if ((x += readBarrier) == 0)
++readBarrier;
}
barrier.await();
result += sum;
}
catch (Exception ie) {
return;
}
}
}
}
backport-util-concurrent-3.1-src/test/loops/src/FinalLongTest142.java 0000644 0017507 0003772 00000004126 10201025631 024404 0 ustar dawidk dcl /*
* @test %I% %E%
* @bug 5041458
* @compile FinalLongTest.java
* @run main FinalLongTest
* @summary Detects reads of uninitialized final value field of Long class
*/
public class FinalLongTest142 {
static int npairs = 2;
static int iters = 500000000;
static final int LEN = 4;
static final Long[] nums = new Long[LEN];
static volatile boolean done;
static volatile long total;
public static void main(String[] args) {
for (int i = 0; i < LEN; ++i)
nums[i] = new Long(i+1);
Thread[] ps = new Thread[npairs];
Thread[] as = new Reader[npairs];
for (int i = 0; i < npairs; ++i) {
ps[i] = new Writer();
as[i] = new Reader();
}
for (int i = 0; i < as.length; ++i) {
ps[i].start();
as[i].start();
}
}
static long nextRandom(long seed) {
return (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
}
static long initialSeed(Object x) {
return (System.currentTimeMillis() + x.hashCode()) | 1;
}
static class Writer extends Thread {
public void run() {
long s = initialSeed(this);
int n = iters / 2;
while (!done && n-- > 0) {
int k = (int)(s & (LEN-1));
int l = (k+1) & (LEN-1);
nums[k] = new Long(s);
nums[l] = new Long(s);
s = nextRandom(s);
if (s == 0) s = initialSeed(this);
}
done = true;
total += s;
}
}
static class Reader extends Thread {
public void run() {
int n = iters;
long s = initialSeed(this);
while (s != 0 && n > 0) {
long nexts = nums[(int)(s & (LEN-1))].longValue();
if (nexts != s)
--n;
else if (done)
break;
s = nexts;
}
done = true;
total += s;
if (s == 0)
throw new Error("Saw uninitialized value");
}
}
}
backport-util-concurrent-3.1-src/test/loops/src/Mutex.java 0000644 0017507 0003772 00000003015 10431260156 022552 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import java.io.*;
/**
* A sample user extension of AbstractQueuedSynchronizer.
*/
public final class Mutex {//extends AbstractQueuedSynchronizer implements Lock, java.io.Serializable {
// public boolean isHeldExclusively() { return getState() == 1; }
//
// public boolean tryAcquire(int acquires) {
// return compareAndSetState(0, 1);
// }
//
// public boolean tryRelease(int releases) {
// setState(0);
// return true;
// }
// public Condition newCondition() { return new ConditionObject(); }
//
// private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
// s.defaultReadObject();
// setState(0); // reset to unlocked state
// }
//
// public void lock() {
// acquire(1);
// }
// public boolean tryLock() {
// return tryAcquire(1);
// }
// public void lockInterruptibly() throws InterruptedException {
// acquireInterruptibly(1);
// }
// public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
// return tryAcquireNanos(1, unit.toNanos(timeout));
// }
// public void unlock() { release(1); }
}
backport-util-concurrent-3.1-src/test/loops/src/LockLoops.java 0000644 0017507 0003772 00000026547 10253737131 023400 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
/*
* A simple test program. Feel free to play.
*/
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import edu.emory.mathcs.backport.java.util.*;
public final class LockLoops {
static final ExecutorService pool = Executors.newCachedThreadPool();
static final LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
static boolean print = false;
static boolean doBuiltin = true;
static boolean doReadWrite = true;
static boolean doSemaphore = true;
static boolean doFair = true;
public static void main(String[] args) throws Exception {
int maxThreads = 100;
int iters = 1000000;
int replications = 1;
if (args.length > 0)
maxThreads = Integer.parseInt(args[0]);
if (args.length > 1)
iters = Integer.parseInt(args[1]);
if (args.length > 2)
replications = Integer.parseInt(args[2]);
rng.setSeed(3122688L);
print = false;
System.out.println("Warmup...");
oneTest(3, 10000);
Thread.sleep(1000);
oneTest(2, 10000);
Thread.sleep(100);
oneTest(1, 100000);
Thread.sleep(100);
oneTest(1, 100000);
Thread.sleep(1000);
print = true;
for (int i = 1; i <= maxThreads; ++i) {
for (int j = 0; j < replications; ++j) {
System.out.println("Threads:" + i);
oneTest(i, iters / i);
Thread.sleep(100);
}
}
pool.shutdown();
}
static void oneTest(int nthreads, int iters) throws Exception {
int v = rng.next();
if (print)
System.out.print("No shared vars ");
new NoLockLoop().test(v, nthreads, iters * 10);
Thread.sleep(10);
if (print)
System.out.print("No Lock + volatile ");
new NoLockVolatileLoop().test(v, nthreads, iters);
Thread.sleep(10);
if (doBuiltin) {
if (print)
System.out.print("builtin lock ");
new BuiltinLockLoop().test(v, nthreads, iters);
Thread.sleep(10);
}
if (print)
System.out.print("ReentrantLock ");
new ReentrantLockLoop().test(v, nthreads, iters);
Thread.sleep(10);
if (doReadWrite) {
if (print)
System.out.print("ReentrantWriteLock ");
new ReentrantWriteLockLoop().test(v, nthreads, iters);
Thread.sleep(10);
if (print)
System.out.print("ReentrantReadWriteLock");
new ReentrantReadWriteLockLoop().test(v, nthreads, iters);
Thread.sleep(10);
}
if (doSemaphore) {
if (print)
System.out.print("Semaphore ");
new SemaphoreLoop().test(v, nthreads, iters);
Thread.sleep(10);
if (print)
System.out.print("FairSemaphore ");
new FairSemaphoreLoop().test(v, nthreads, iters);
Thread.sleep(10);
}
if (doFair) {
if (print)
System.out.print("FairReentrantLock ");
new FairReentrantLockLoop().test(v, nthreads, iters);
Thread.sleep(10);
if (doReadWrite) {
// if (print)
// System.out.print("FairRWriteLock ");
// new FairReentrantWriteLockLoop().test(v, nthreads, iters);
// Thread.sleep(10);
// if (print)
// System.out.print("FairRReadWriteLock ");
// new FairReentrantReadWriteLockLoop().test(v, nthreads, iters);
// Thread.sleep(10);
}
}
}
static abstract class LockLoop implements Runnable {
int v;
int iters;
volatile int result;
final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier barrier;
final void test(int initialValue, int nthreads, int iters) throws Exception {
v = initialValue;
this.iters = iters;
barrier = new CyclicBarrier(nthreads+1, timer);
for (int i = 0; i < nthreads; ++i)
pool.execute(this);
barrier.await();
barrier.await();
long time = timer.getTime();
if (print) {
long tpi = time / (iters * nthreads);
System.out.print("\t" + LoopHelpers.rightJustify(tpi) + " ns per update");
// double secs = (double)(time) / 1000000000.0;
// System.out.print("\t " + secs + "s run time");
System.out.println();
}
if (result == 0) // avoid overoptimization
System.out.println("useless result: " + result);
}
abstract int loop(int n);
public final void run() {
try {
barrier.await();
result += loop(iters);
barrier.await();
}
catch (Exception ie) {
return;
}
}
}
private static class BuiltinLockLoop extends LockLoop {
final int loop(int n) {
int sum = 0;
while (n-- > 0) {
synchronized(this) {
v = LoopHelpers.compute1(v);
}
sum += LoopHelpers.compute2(v);
}
return sum;
}
}
private static class NoLockLoop extends LockLoop {
final int loop(int n) {
int sum = 0;
int y = v;
while (n-- > 0) {
y = LoopHelpers.compute1(y);
sum += LoopHelpers.compute2(y);
}
return sum;
}
}
private static class NoLockVolatileLoop extends LockLoop {
volatile private int vv;
final int loop(int n) {
int sum = 0;
while (n-- > 0) {
int y = LoopHelpers.compute1(vv);
vv = y;
sum += LoopHelpers.compute2(y);
}
return sum;
}
}
private static class ReentrantLockLoop extends LockLoop {
final private ReentrantLock lock = new ReentrantLock();
final int loop(int n) {
int sum = 0;
while (n-- > 0) {
lock.lock();
try {
v = LoopHelpers.compute1(v);
}
finally {
lock.unlock();
}
sum += LoopHelpers.compute2(v);
}
return sum;
}
}
private static class FairReentrantLockLoop extends LockLoop {
final private ReentrantLock lock = new ReentrantLock(true);
final int loop(int n) {
int sum = 0;
while (n-- > 0) {
lock.lock();
try {
v = LoopHelpers.compute1(v);
}
finally {
lock.unlock();
}
sum += LoopHelpers.compute2(v);
}
return sum;
}
}
private static class ReentrantWriteLockLoop extends LockLoop {
final private Lock lock = new ReentrantReadWriteLock().writeLock();
final int loop(int n) {
int sum = 0;
while (n-- > 0) {
lock.lock();
try {
v = LoopHelpers.compute1(v);
}
finally {
lock.unlock();
}
sum += LoopHelpers.compute2(v);
}
return sum;
}
}
private static class ReentrantReadWriteLockLoop extends LockLoop {
final private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
final int loop(int n) {
int sum = 0;
while (n-- > 0) {
int x;
lock.readLock().lock();
try {
x = LoopHelpers.compute1(v);
}
finally {
lock.readLock().unlock();
}
lock.writeLock().lock();
try {
v = x;
}
finally {
lock.writeLock().unlock();
}
sum += LoopHelpers.compute2(v);
}
return sum;
}
}
// private static class FairReentrantWriteLockLoop extends LockLoop {
// final Lock lock = new ReentrantReadWriteLock(true).writeLock();
// final int loop(int n) {
// int sum = 0;
// while (n-- > 0) {
// lock.lock();
// try {
// v = LoopHelpers.compute1(v);
// }
// finally {
// lock.unlock();
// }
// sum += LoopHelpers.compute2(v);
// }
// return sum;
// }
// }
//
private static class SemaphoreLoop extends LockLoop {
final private Semaphore sem = new Semaphore(1, false);
final int loop(int n) {
int sum = 0;
try {
while (n-- > 0) {
sem.acquire();
try {
v = LoopHelpers.compute1(v);
}
finally {
sem.release();
}
sum += LoopHelpers.compute2(v);
}
}
catch (InterruptedException ie) {
return sum;
}
return sum;
}
}
private static class FairSemaphoreLoop extends LockLoop {
final private Semaphore sem = new Semaphore(1, true);
final int loop(int n) {
int sum = 0;
try {
while (n-- > 0) {
sem.acquire();
try {
v = LoopHelpers.compute1(v);
}
finally {
sem.release();
}
sum += LoopHelpers.compute2(v);
}
}
catch (InterruptedException ie) {
return sum;
}
return sum;
}
}
// private static class FairReentrantReadWriteLockLoop extends LockLoop {
// final private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
// final int loop(int n) {
// int sum = 0;
// while (n-- > 0) {
// int x;
// lock.readLock().lock();
// try {
// x = LoopHelpers.compute1(v);
// }
// finally {
// lock.readLock().unlock();
// }
// lock.writeLock().lock();
// try {
// v = x;
// }
// finally {
// lock.writeLock().unlock();
// }
// sum += LoopHelpers.compute2(v);
// }
// return sum;
// }
// }
//
}
backport-util-concurrent-3.1-src/test/loops/src/SimpleReentrantLockLoops.java 0000644 0017507 0003772 00000007055 10256105111 026414 0 ustar dawidk dcl /*
* @test
* @synopsis multiple threads using a single ReentrantLock
*/
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain. Use, modify, and
* redistribute this code in any way without acknowledgement.
*/
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import edu.emory.mathcs.backport.java.util.*;
public final class SimpleReentrantLockLoops {
static final ExecutorService pool = Executors.newCachedThreadPool();
static final LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
static boolean print = false;
static int iters = 2000000;
public static void main(String[] args) throws Exception {
int maxThreads = 100;
if (args.length > 0)
maxThreads = Integer.parseInt(args[0]);
new ReentrantLockLoop(1).test();
new ReentrantLockLoop(1).test();
print = true;
int k = 1;
for (int i = 1; i <= maxThreads;) {
System.out.print("Threads: " + i);
new ReentrantLockLoop(i).test();
Thread.sleep(100);
if (i == k) {
k = i << 1;
i = i + (i >>> 1);
}
else
i = k;
}
pool.shutdown();
}
static final class ReentrantLockLoop implements Runnable {
private int v = rng.next();
private volatile int result = 17;
private final ReentrantLock lock = new ReentrantLock();
private final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
private final CyclicBarrier barrier;
private final int nthreads;
private volatile int readBarrier;
ReentrantLockLoop(int nthreads) {
this.nthreads = nthreads;
barrier = new CyclicBarrier(nthreads+1, timer);
}
final void test() throws Exception {
for (int i = 0; i < nthreads; ++i)
pool.execute(this);
barrier.await();
barrier.await();
if (print) {
long time = timer.getTime();
long tpi = time / ((long)iters * nthreads);
System.out.print("\t" + LoopHelpers.rightJustify(tpi) + " ns per lock");
double secs = (double)(time) / 1000000000.0;
System.out.println("\t " + secs + "s run time");
}
int r = result;
if (r == 0) // avoid overoptimization
System.out.println("useless result: " + r);
}
public final void run() {
final ReentrantLock lock = this.lock;
try {
barrier.await();
int sum = v + 1;
int x = 0;
int n = iters;
while (n-- > 0) {
lock.lock();
int k = (sum & 3);
if (k > 0) {
x = v;
while (k-- > 0)
x = LoopHelpers.compute6(x);
v = x;
}
else x = sum + 1;
lock.unlock();
if ((x += readBarrier) == 0)
++readBarrier;
for (int l = x & 7; l > 0; --l)
sum += LoopHelpers.compute6(sum);
}
barrier.await();
result += sum;
}
catch (Exception ie) {
return;
}
}
}
}
backport-util-concurrent-3.1-src/test/loops/src/RWCollection.java 0000644 0017507 0003772 00000010653 10346121124 024016 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.ArrayList;
/**
* This is an incomplete implementation of a wrapper class
* that places read-write locks around unsynchronized Collections.
* Exists as a sample input for CollectionLoops test.
*/
public final class RWCollection implements Collection {
private final Collection c;
private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
public RWCollection(Collection c) {
if (c == null)
throw new NullPointerException();
this.c = c;
}
public RWCollection() {
this(new ArrayList());
}
public final int size() {
final ReentrantReadWriteLock.ReadLock l = (ReentrantReadWriteLock.ReadLock)rwl.readLock();
l.lock(); try {return c.size();} finally { l.unlock(); }
}
public final boolean isEmpty(){
final ReentrantReadWriteLock.ReadLock l = (ReentrantReadWriteLock.ReadLock)rwl.readLock();
l.lock(); try {return c.isEmpty();} finally { l.unlock(); }
}
public final boolean contains(Object o) {
final ReentrantReadWriteLock.ReadLock l = (ReentrantReadWriteLock.ReadLock)rwl.readLock();
l.lock(); try {return c.contains(o);} finally { l.unlock(); }
}
public final boolean equals(Object o) {
final ReentrantReadWriteLock.ReadLock l = (ReentrantReadWriteLock.ReadLock)rwl.readLock();
l.lock(); try {return c.equals(o);} finally { l.unlock(); }
}
public final int hashCode() {
final ReentrantReadWriteLock.ReadLock l = (ReentrantReadWriteLock.ReadLock)rwl.readLock();
l.lock(); try {return c.hashCode();} finally { l.unlock(); }
}
public final String toString() {
final ReentrantReadWriteLock.ReadLock l = (ReentrantReadWriteLock.ReadLock)rwl.readLock();
l.lock(); try {return c.toString();} finally { l.unlock(); }
}
public final Iterator iterator() {
final ReentrantReadWriteLock.ReadLock l = (ReentrantReadWriteLock.ReadLock)rwl.readLock();
l.lock(); try {return c.iterator();} finally { l.unlock(); }
}
public final Object[] toArray() {
final ReentrantReadWriteLock.ReadLock l = (ReentrantReadWriteLock.ReadLock)rwl.readLock();
l.lock(); try {return c.toArray();} finally { l.unlock(); }
}
public final Object[] toArray(Object[] a) {
final ReentrantReadWriteLock.ReadLock l = (ReentrantReadWriteLock.ReadLock)rwl.readLock();
l.lock(); try {return c.toArray(a);} finally { l.unlock(); }
}
public final boolean add(Object e) {
final ReentrantReadWriteLock.WriteLock l = (ReentrantReadWriteLock.WriteLock)rwl.writeLock();
l.lock(); try {return c.add(e);} finally { l.unlock(); }
}
public final boolean remove(Object o) {
final ReentrantReadWriteLock.WriteLock l = (ReentrantReadWriteLock.WriteLock)rwl.writeLock();
l.lock(); try {return c.remove(o);} finally { l.unlock(); }
}
public final boolean containsAll(Collection coll) {
final ReentrantReadWriteLock.WriteLock l = (ReentrantReadWriteLock.WriteLock)rwl.writeLock();
l.lock(); try {return c.containsAll(coll);} finally { l.unlock(); }
}
public final boolean addAll(Collection coll) {
final ReentrantReadWriteLock.WriteLock l = (ReentrantReadWriteLock.WriteLock)rwl.writeLock();
l.lock(); try {return c.addAll(coll);} finally { l.unlock(); }
}
public final boolean removeAll(Collection coll) {
final ReentrantReadWriteLock.WriteLock l = (ReentrantReadWriteLock.WriteLock)rwl.writeLock();
l.lock(); try {return c.removeAll(coll);} finally { l.unlock(); }
}
public final boolean retainAll(Collection coll) {
final ReentrantReadWriteLock.WriteLock l = (ReentrantReadWriteLock.WriteLock)rwl.writeLock();
l.lock(); try {return c.retainAll(coll);} finally { l.unlock(); }
}
public final void clear() {
final ReentrantReadWriteLock.WriteLock l = (ReentrantReadWriteLock.WriteLock)rwl.writeLock();
l.lock(); try {c.clear();} finally { l.unlock(); }
}
}
backport-util-concurrent-3.1-src/test/loops/src/FinalLongTest.java 0000644 0017507 0003772 00000006265 10253737131 024177 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
public class FinalLongTest {
static int npairs = 2;
static int iters = 10000000;
static int LEN = 2;
static final Long[] nums = new Long[LEN];
static volatile boolean done;
static volatile long total;
static Long n0 = new Long(21);
static Long n1 = new Long(22);
static Long n2 = new Long(23);
static Long n3 = new Long(23);
public static void main(String[] args) {
for (int i = 0; i < LEN; ++i)
nums[i] = new Long(i+1);
Thread[] ps = new Thread[npairs];
Thread[] as = new Reader[npairs];
for (int i = 0; i < npairs; ++i) {
ps[i] = new Writer();
as[i] = new Reader();
}
for (int i = 0; i < as.length; ++i) {
ps[i].start();
as[i].start();
}
}
static long nextRandom(long seed) {
return (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
}
static long initialSeed(Object x) {
return (System.currentTimeMillis() + x.hashCode()) | 1;
}
static class Writer extends Thread {
public void run() {
long s = initialSeed(this);
int n = iters / 2;
Long[] ns = nums;
while (n-- > 0) {
// int k = (int)(s & (LEN-1));
// if (k < 0 || k >= LEN) k = 1;
// int l = (k+1) & (LEN-1);
// if (l < 0 || l >= LEN) l = 0;
// int k = (s & 1) == 0? 0 : 1;
// int l = (k == 0)? 1 : 0;
if ((s & (LEN-1)) == 0) {
n3 = n1;
n0 = new Long(s);
n2 = n1;
n1 = new Long(s);
}
else {
n3 = n0;
n1 = new Long(s);
n2 = n0;
n0 = new Long(s);
}
s = nextRandom(s);
if (s == 0) s = initialSeed(this);
}
done = true;
total += s;
}
}
static class Reader extends Thread {
public void run() {
int n = iters;
long s = initialSeed(this);
while (s != 0 && n > 0) {
long nexts; // = nums[(int)(s & (LEN-1))].longValue();
if ((s & (LEN-1)) == 0)
nexts = n0.longValue();
else
nexts = n1.longValue();
if (nexts != 0) {
if ((s & 4) == 0)
nexts = n2.longValue();
else
nexts = n3.longValue();
}
if (nexts != s)
--n;
else if (done)
break;
s = nexts;
}
done = true;
total += s;
if (s == 0)
throw new Error("Saw uninitialized value");
}
}
}
backport-util-concurrent-3.1-src/test/loops/src/CollectionWordLoops.java 0000644 0017507 0003772 00000013101 10431260156 025411 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import java.io.*;
import java.util.Collection;
public class CollectionWordLoops {
static final String[] WORDS_FILES = {
"kw.txt",
"class.txt",
};
static final int MAX_WORDS = 500000;
static final int pinsert = 80;
static final int premove = 2;
static final int NOPS = 100000;
static final int numTests = 2;
public static void main(String[] args) {
Class collectionClass = null;
try {
collectionClass = Class.forName(args[0]);
} catch(ClassNotFoundException e) {
throw new RuntimeException("Class " + args[0] + " not found.");
}
System.out.println("Testing " + collectionClass.getName());
for (int s = 0; s < WORDS_FILES.length; ++s)
tests(collectionClass, numTests, s);
for (int s = WORDS_FILES.length-1; s >= 0; --s)
tests(collectionClass, numTests, s);
}
static void tests(Class collectionClass, int numTests, int sizeIndex) {
try {
String[] key = readWords(sizeIndex);
int size = key.length;
System.out.print("n = " +LoopHelpers.rightJustify(size) +" : ");
long least = Long.MAX_VALUE;
for (int i = 0; i < numTests; ++i) {
Collection m = newCollection(collectionClass);
long t = doTest(collectionClass.getName(), m, key);
if (t < least) least = t;
m.clear();
m = null;
}
long nano = Math.round(1000000.0 * (least) / NOPS);
System.out.println(LoopHelpers.rightJustify(nano) + " ns per op");
} catch (IOException ignore) {
return; // skip test if can't read file
}
}
static Collection newCollection(Class cl) {
try {
Collection m = (Collection)cl.newInstance();
return m;
} catch(Exception e) {
throw new RuntimeException("Can't instantiate " + cl + ": " + e);
}
}
static void pause() {
try { Thread.sleep(100); } catch(InterruptedException ie) { return; }
}
static String[] readWords(int sizeIndex) throws IOException {
String[] l = new String[MAX_WORDS];
String[] array = null;
try {
FileReader fr = new FileReader(WORDS_FILES[sizeIndex]);
BufferedReader reader = new BufferedReader(fr);
int k = 0;
for (;;) {
String s = reader.readLine();
if (s == null) break;
l[k++] = s;
}
array = new String[k];
for (int i = 0; i < k; ++i) {
array[i] = l[i];
l[i] = null;
}
l = null;
reader.close();
}
catch (IOException ex) {
System.out.println("Can't read words file:" + ex);
throw ex;
}
return array;
}
static long doTest(String name,
final Collection m,
final String[] key) {
// System.out.print(name + "\t");
Runner runner = new Runner(m, key);
long startTime = System.currentTimeMillis();
runner.run();
long afterRun = System.currentTimeMillis();
long runTime = (afterRun - startTime);
int np = runner.total;
if (runner.total == runner.hashCode())
System.out.println("Useless Number" + runner.total);
int sz = runner.maxsz;
if (sz == runner.hashCode())
System.out.println("Useless Number" + sz);
// System.out.print(" m = " + sz);
return runTime;
}
static class Runner implements Runnable {
final Collection collection;
final String[] key;
LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
final int pctrem;
final int pctins;
int nputs = 0;
int npgets = 0;
int nagets = 0;
int nremoves = 0;
volatile int total;
int maxsz;
Runner(Collection m, String[] k) {
collection = m; key = k;
pctrem = (int)(((long)premove * (long)(Integer.MAX_VALUE/2)) / 50);
pctins = (int)(((long)pinsert * (long)(Integer.MAX_VALUE/2)) / 50);
}
int oneStep(int j) {
int n = key.length;
int r = rng.next() & 0x7FFFFFFF;
int jinc = (r & 7);
j += jinc - 3;
if (j >= n) j -= n;
if (j < 0) j += n;
int l = n / 4 + j;
if (l >= n) l -= n;
String k = key[j];
if (!collection.contains(k)) {
++nagets;
if (r < pctins) {
collection.add(k);
++nputs;
int csz = nputs - nremoves;
if (csz > maxsz) maxsz = csz;
}
}
else {
++npgets;
if (r < pctrem) {
collection.remove(k);
++nremoves;
j += ((r >>> 8) & 7) + n / 2;
if (j >= n) j -= n;
}
}
return j;
}
public void run() {
int j = key.length / 2;
for (int i = 0; i < NOPS; ++i) {
j = oneStep(j);
}
total = nputs + npgets + nagets + nremoves;
}
}
}
backport-util-concurrent-3.1-src/test/loops/src/SimpleSpinLockLoops.java 0000644 0017507 0003772 00000007115 10256105111 025360 0 ustar dawidk dcl /*
* @test
* @synopsis multiple threads using a spinlock
*/
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain. Use, modify, and
* redistribute this code in any way without acknowledgement.
*/
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import edu.emory.mathcs.backport.java.util.*;
public final class SimpleSpinLockLoops {
static final ExecutorService pool = Executors.newCachedThreadPool();
static final LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
static boolean print = false;
static int iters = 2000000;
public static void main(String[] args) throws Exception {
int maxThreads = 100;
if (args.length > 0)
maxThreads = Integer.parseInt(args[0]);
new LockLoop(1).test();
new LockLoop(1).test();
print = true;
int k = 1;
for (int i = 1; i <= maxThreads;) {
System.out.print("Threads: " + i);
new LockLoop(i).test();
Thread.sleep(100);
if (i == k) {
k = i << 1;
i = i + (i >>> 1);
}
else
i = k;
}
pool.shutdown();
}
static final class LockLoop implements Runnable {
private int v = rng.next();
private volatile int result = 17;
private final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
private final CyclicBarrier barrier;
private final int nthreads;
private volatile int readBarrier;
private final AtomicInteger spinlock = new AtomicInteger();
LockLoop(int nthreads) {
this.nthreads = nthreads;
barrier = new CyclicBarrier(nthreads+1, timer);
}
final void test() throws Exception {
for (int i = 0; i < nthreads; ++i)
pool.execute(this);
barrier.await();
barrier.await();
if (print) {
long time = timer.getTime();
long tpi = time / ((long)iters * nthreads);
System.out.print("\t" + LoopHelpers.rightJustify(tpi) + " ns per lock");
double secs = (double)(time) / 1000000000.0;
System.out.println("\t " + secs + "s run time");
}
int r = result;
if (r == 0) // avoid overoptimization
System.out.println("useless result: " + r);
}
public final void run() {
final AtomicInteger lock = this.spinlock;
try {
barrier.await();
int sum = v + 1;
int x = 0;
int n = iters;
while (n-- > 0) {
while (!lock.compareAndSet(0, 1)) ;
int k = (sum & 3);
if (k > 0) {
x = v;
while (k-- > 0)
x = LoopHelpers.compute6(x);
v = x;
}
else x = sum + 1;
lock.set(0);
if ((x += readBarrier) == 0)
++readBarrier;
for (int l = x & 1; l > 0; --l)
sum += LoopHelpers.compute6(sum);
}
barrier.await();
result += sum;
}
catch (Exception ie) {
return;
}
}
}
}
backport-util-concurrent-3.1-src/test/loops/src/UncheckedLockLoops.java 0000644 0017507 0003772 00000032711 10253737131 025200 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
/*
* @test
* @summary basic safety and liveness of ReentrantLocks, and other locks based on them
*/
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import edu.emory.mathcs.backport.java.util.*;
public final class UncheckedLockLoops {
static final LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
static boolean print = false;
static boolean doBuiltin = true;
public static void main(String[] args) throws Exception {
int maxThreads = 100;
int iters = 10000000;
if (args.length > 0)
maxThreads = Integer.parseInt(args[0]);
rng.setSeed(3122688L);
print = false;
System.out.println("Warmup...");
oneTest(1, 100000);
Thread.sleep(1000);
oneTest(3, 10000);
Thread.sleep(1000);
oneTest(2, 10000);
Thread.sleep(100);
oneTest(1, 100000);
Thread.sleep(100);
oneTest(1, 100000);
Thread.sleep(1000);
print = true;
System.out.println("Threads:" + 1);
oneTest(1, iters / 1);
Thread.sleep(100);
for (int i = 1; i <= maxThreads; i += (i+1) >>> 1) {
System.out.println("Threads:" + i);
oneTest(i, iters / i);
Thread.sleep(100);
}
}
static void oneTest(int nthreads, int iters) throws Exception {
int fairIters = (nthreads <= 1)? iters : iters/20;
int v = rng.next();
if (print)
System.out.print("NoLock (1 thread) ");
new NoLockLoop().test(v, 1, iters * nthreads);
Thread.sleep(10);
if (print)
System.out.print("ReentrantLock ");
new ReentrantLockLoop().test(v, nthreads, iters);
Thread.sleep(10);
if (false) {
if (print)
System.out.print("FairReentrantLock ");
new FairReentrantLockLoop().test(v, nthreads, fairIters);
Thread.sleep(10);
}
if (doBuiltin) {
if (print)
System.out.print("builtin lock ");
new BuiltinLockLoop().test(v, nthreads, fairIters);
Thread.sleep(10);
}
// if (print)
// System.out.print("Mutex ");
// new MutexLoop().test(v, nthreads, iters);
// Thread.sleep(10);
//
// if (print)
// System.out.print("LongMutex ");
// new LongMutexLoop().test(v, nthreads, iters);
// Thread.sleep(10);
//
if (print)
System.out.print("Semaphore ");
new SemaphoreLoop().test(v, nthreads, iters);
Thread.sleep(10);
if (print)
System.out.print("FairSemaphore ");
new FairSemaphoreLoop().test(v, nthreads, fairIters);
Thread.sleep(10);
if (print)
System.out.print("ReentrantWriteLock ");
new ReentrantWriteLockLoop().test(v, nthreads, iters);
Thread.sleep(10);
// if (print)
// System.out.print("FairRWriteLock ");
// new FairReentrantWriteLockLoop().test(v, nthreads, fairIters);
// Thread.sleep(10);
//
if (print)
System.out.print("ReentrantReadWriteLock");
new ReentrantReadWriteLockLoop().test(v, nthreads, iters);
Thread.sleep(10);
// if (print)
// System.out.print("FairRReadWriteLock ");
// new FairReentrantReadWriteLockLoop().test(v, nthreads, fairIters);
// Thread.sleep(10);
//
}
static abstract class LockLoop implements Runnable {
int value;
int checkValue;
int iters;
volatile int result;
volatile int failures;
final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier barrier;
final int setValue(int v) {
checkValue = v ^ 0x55555555;
value = v;
return v;
}
final int getValue() {
int v = value;
if (checkValue != ~(v ^ 0xAAAAAAAA))
++failures;
return v;
}
final void test(int initialValue, int nthreads, int iters) throws Exception {
setValue(initialValue);
this.iters = iters;
barrier = new CyclicBarrier(nthreads+1, timer);
for (int i = 0; i < nthreads; ++i)
new Thread(this).start();
barrier.await();
barrier.await();
long time = timer.getTime();
if (print) {
long tpi = time / (iters * nthreads);
System.out.print("\t" + LoopHelpers.rightJustify(tpi) + " ns per update");
// double secs = (double)(time) / 1000000000.0;
// System.out.print("\t " + secs + "s run time");
System.out.println();
}
if (result == 0) // avoid overoptimization
System.out.println("useless result: " + result);
if (failures != 0)
throw new Error("protection failure?");
}
abstract int loop(int n);
public final void run() {
try {
barrier.await();
result += loop(iters);
barrier.await();
}
catch (Exception ie) {
return;
}
}
}
private static class NoLockLoop extends LockLoop {
private volatile int readBarrier;
final int loop(int n) {
int sum = 0;
int x = 0;;
while (n-- > 0) {
int r1 = readBarrier;
x = setValue(LoopHelpers.compute1(getValue()));
int r2 = readBarrier;
if (r1 == r2 && (x & 255) == 0)
++readBarrier;
sum += LoopHelpers.compute2(x);
}
return sum;
}
}
private static class BuiltinLockLoop extends LockLoop {
final int loop(int n) {
int sum = 0;
int x = 0;;
while (n-- > 0) {
synchronized(this) {
x = setValue(LoopHelpers.compute1(getValue()));
}
sum += LoopHelpers.compute2(x);
}
return sum;
}
}
private static class ReentrantLockLoop extends LockLoop {
final private ReentrantLock lock = new ReentrantLock();
final int loop(int n) {
final ReentrantLock lock = this.lock;
int sum = 0;
int x = 0;
while (n-- > 0) {
lock.lock();
try {
x = setValue(LoopHelpers.compute1(getValue()));
}
finally {
lock.unlock();
}
sum += LoopHelpers.compute2(x);
}
return sum;
}
}
// private static class MutexLoop extends LockLoop {
// final private Mutex lock = new Mutex();
// final int loop(int n) {
// final Mutex lock = this.lock;
// int sum = 0;
// int x = 0;
// while (n-- > 0) {
// lock.lock();
// try {
// x = setValue(LoopHelpers.compute1(getValue()));
// }
// finally {
// lock.unlock();
// }
// sum += LoopHelpers.compute2(x);
// }
// return sum;
// }
// }
//
// private static class LongMutexLoop extends LockLoop {
// final private LongMutex lock = new LongMutex();
// final int loop(int n) {
// final LongMutex lock = this.lock;
// int sum = 0;
// int x = 0;
// while (n-- > 0) {
// lock.lock();
// try {
// x = setValue(LoopHelpers.compute1(getValue()));
// }
// finally {
// lock.unlock();
// }
// sum += LoopHelpers.compute2(x);
// }
// return sum;
// }
// }
private static class FairReentrantLockLoop extends LockLoop {
final private ReentrantLock lock = new ReentrantLock(true);
final int loop(int n) {
final ReentrantLock lock = this.lock;
int sum = 0;
int x = 0;
while (n-- > 0) {
lock.lock();
try {
x = setValue(LoopHelpers.compute1(getValue()));
}
finally {
lock.unlock();
}
sum += LoopHelpers.compute2(x);
}
return sum;
}
}
private static class ReentrantWriteLockLoop extends LockLoop {
final private Lock lock = new ReentrantReadWriteLock().writeLock();
final int loop(int n) {
final Lock lock = this.lock;
int sum = 0;
int x = 0;
while (n-- > 0) {
lock.lock();
try {
x = setValue(LoopHelpers.compute1(getValue()));
}
finally {
lock.unlock();
}
sum += LoopHelpers.compute2(x);
}
return sum;
}
}
// private static class FairReentrantWriteLockLoop extends LockLoop {
// final Lock lock = new ReentrantReadWriteLock(true).writeLock();
// final int loop(int n) {
// final Lock lock = this.lock;
// int sum = 0;
// int x = 0;
// while (n-- > 0) {
// lock.lock();
// try {
// x = setValue(LoopHelpers.compute1(getValue()));
// }
// finally {
// lock.unlock();
// }
// sum += LoopHelpers.compute2(x);
// }
// return sum;
// }
// }
//
private static class SemaphoreLoop extends LockLoop {
final private Semaphore sem = new Semaphore(1, false);
final int loop(int n) {
final Semaphore sem = this.sem;
int sum = 0;
int x = 0;
while (n-- > 0) {
sem.acquireUninterruptibly();
try {
x = setValue(LoopHelpers.compute1(getValue()));
}
finally {
sem.release();
}
sum += LoopHelpers.compute2(x);
}
return sum;
}
}
private static class FairSemaphoreLoop extends LockLoop {
final private Semaphore sem = new Semaphore(1, true);
final int loop(int n) {
final Semaphore sem = this.sem;
int sum = 0;
int x = 0;
while (n-- > 0) {
sem.acquireUninterruptibly();
try {
x = setValue(LoopHelpers.compute1(getValue()));
}
finally {
sem.release();
}
sum += LoopHelpers.compute2(x);
}
return sum;
}
}
private static class ReentrantReadWriteLockLoop extends LockLoop {
final private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
final int loop(int n) {
final Lock rlock = lock.readLock();
final Lock wlock = lock.writeLock();
int sum = 0;
int x = 0;
while (n-- > 0) {
if ((n & 16) != 0) {
rlock.lock();
try {
x = LoopHelpers.compute1(getValue());
x = LoopHelpers.compute2(x);
}
finally {
rlock.unlock();
}
}
else {
wlock.lock();
try {
setValue(x);
}
finally {
wlock.unlock();
}
sum += LoopHelpers.compute2(x);
}
}
return sum;
}
}
// private static class FairReentrantReadWriteLockLoop extends LockLoop {
// final private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
// final int loop(int n) {
// final Lock rlock = lock.readLock();
// final Lock wlock = lock.writeLock();
// int sum = 0;
// int x = 0;
// while (n-- > 0) {
// if ((n & 16) != 0) {
// rlock.lock();
// try {
// x = LoopHelpers.compute1(getValue());
// x = LoopHelpers.compute2(x);
// }
// finally {
// rlock.unlock();
// }
// }
// else {
// wlock.lock();
// try {
// setValue(x);
// }
// finally {
// wlock.unlock();
// }
// sum += LoopHelpers.compute2(x);
// }
// }
// return sum;
// }
//
// }
}
backport-util-concurrent-3.1-src/test/loops/src/TimeoutLockLoops.java 0000644 0017507 0003772 00000007467 10253737131 024747 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
/*
* @test %I% %E%
* @bug 4486658
* @compile -source 1.5 TimeoutLockLoops.java
* @run main TimeoutLockLoops
* @summary Checks for responsiveness of locks to timeouts.
* Runs under the assumption that ITERS computations require more than
* TIMEOUT msecs to complete, which seems to be a safe assumption for
* another decade.
*/
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import edu.emory.mathcs.backport.java.util.*;
public final class TimeoutLockLoops {
static final ExecutorService pool = Executors.newCachedThreadPool();
static final LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
static boolean print = false;
static final int ITERS = Integer.MAX_VALUE;
static final long TIMEOUT = 100;
public static void main(String[] args) throws Exception {
int maxThreads = 100;
if (args.length > 0)
maxThreads = Integer.parseInt(args[0]);
print = true;
for (int i = 1; i <= maxThreads; i += (i+1) >>> 1) {
System.out.print("Threads: " + i);
new ReentrantLockLoop(i).test();
// Thread.sleep(10);
}
pool.shutdown();
}
static final class ReentrantLockLoop implements Runnable {
private int v = rng.next();
private volatile boolean completed;
private volatile int result = 17;
private final ReentrantLock lock = new ReentrantLock();
private final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
private final CyclicBarrier barrier;
private final int nthreads;
ReentrantLockLoop(int nthreads) {
this.nthreads = nthreads;
barrier = new CyclicBarrier(nthreads+1, timer);
}
final void test() throws Exception {
for (int i = 0; i < nthreads; ++i) {
lock.lock();
pool.execute(this);
lock.unlock();
}
barrier.await();
Thread.sleep(TIMEOUT);
while (!lock.tryLock()); // Jam lock
// lock.lock();
barrier.await();
if (print) {
long time = timer.getTime();
double secs = (double)(time) / 1000000000.0;
System.out.println("\t " + secs + "s run time");
}
if (completed)
throw new Error("Some thread completed instead of timing out");
int r = result;
if (r == 0) // avoid overoptimization
System.out.println("useless result: " + r);
}
public final void run() {
try {
barrier.await();
int sum = v;
int x = 17;
int n = ITERS;
final ReentrantLock lock = this.lock;
for (;;) {
if (x != 0) {
if (n-- <= 0)
break;
}
if (!lock.tryLock(TIMEOUT, TimeUnit.MILLISECONDS))
break;
try {
v = x = LoopHelpers.compute1(v);
}
finally {
lock.unlock();
}
sum += LoopHelpers.compute2(x);
}
if (n <= 0)
completed = true;
barrier.await();
result += sum;
}
catch (Exception ex) {
ex.printStackTrace();
return;
}
}
}
}
backport-util-concurrent-3.1-src/test/loops/src/LoopHelpers.java 0000644 0017507 0003772 00000012302 10346121124 023677 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
/**
* Misc utilities in JSR166 performance tests
*/
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import edu.emory.mathcs.backport.java.util.concurrent.helpers.Utils;
class LoopHelpers {
static final SimpleRandom staticRNG = new SimpleRandom();
// Some mindless computation to do between synchronizations...
/**
* generates 32 bit pseudo-random numbers.
* Adapted from http://www.snippets.org
*/
public static int compute1(int x) {
int lo = 16807 * (x & 0xFFFF);
int hi = 16807 * (x >>> 16);
lo += (hi & 0x7FFF) << 16;
if ((lo & 0x80000000) != 0) {
lo &= 0x7fffffff;
++lo;
}
lo += hi >>> 15;
if (lo == 0 || (lo & 0x80000000) != 0) {
lo &= 0x7fffffff;
++lo;
}
return lo;
}
/**
* Computes a linear congruential random number a random number
* of times.
*/
public static int compute2(int x) {
int loops = (x >>> 4) & 7;
while (loops-- > 0) {
x = (x * 2147483647) % 16807;
}
return x;
}
/**
* Yet another random number generator
*/
public static int compute3(int x) {
int t = (x % 127773) * 16807 - (x / 127773) * 2836;
return (t > 0)? t : t + 0x7fffffff;
}
/**
* Yet another random number generator
*/
public static int compute4(int x) {
return x * 134775813 + 1;
}
/**
* Yet another random number generator
*/
public static int compute5(int x) {
return 36969 * (x & 65535) + (x >> 16);
}
/**
* Marsaglia xorshift (1, 3, 10)
*/
public static int compute6(int seed) {
seed ^= seed << 1;
seed ^= seed >>> 3;
seed ^= (seed << 10);
return seed;
}
/**
* Marsaglia xorshift (6, 21, 7)
*/
public static int compute7(int y) {
y ^= y << 6;
y ^= y >>> 21;
y ^= (y << 7);
return y;
}
/**
* Marsaglia xorshift for longs
*/
public static long compute8(long x) {
x ^= x << 13;
x ^= x >>> 7;
x ^= (x << 17);
return x;
}
public static final class XorShift32Random {
static final AtomicInteger seq = new AtomicInteger(8862213);
int x = -1831433054;
public XorShift32Random(int seed) { x = seed; }
public XorShift32Random() {
this((int)Utils.nanoTime() + seq.getAndAdd(129));
}
public int next() {
x ^= x << 6;
x ^= x >>> 21;
x ^= (x << 7);
return x;
}
}
/** Multiplication-free RNG from Marsaglia "Xorshift RNGs" paper */
public static final class MarsagliaRandom {
static final AtomicInteger seq = new AtomicInteger(3122688);
int x;
int y = 842502087;
int z = -715159705;
int w = 273326509;
public MarsagliaRandom(int seed) { x = seed; }
public MarsagliaRandom() {
this((int)Utils.nanoTime() + seq.getAndAdd(129));
}
public int next() {
int t = x ^ (x << 11);
x = y;
y = z;
z = w;
return w = (w ^ (w >>> 19) ^ (t ^ (t >>> 8)));
}
}
/**
* Unsynchronized version of java.util.Random algorithm.
*/
public static final class SimpleRandom {
private final static long multiplier = 0x5DEECE66DL;
private final static long addend = 0xBL;
private final static long mask = (1L << 48) - 1;
static final AtomicLong seq = new AtomicLong( -715159705);
private long seed;
SimpleRandom(long s) {
seed = s;
}
SimpleRandom() {
seed = Utils.nanoTime() + seq.getAndAdd(129);
}
public void setSeed(long s) {
seed = s;
}
public int next() {
long nextseed = (seed * multiplier + addend) & mask;
seed = nextseed;
return ((int)(nextseed >>> 17)) & 0x7FFFFFFF;
}
}
public static class BarrierTimer implements Runnable {
volatile boolean started;
volatile long startTime;
volatile long endTime;
public void run() {
long t = Utils.nanoTime();
if (!started) {
started = true;
startTime = t;
} else
endTime = t;
}
public void clear() {
started = false;
}
public long getTime() {
return endTime - startTime;
}
}
public static String rightJustify(long n) {
// There's probably a better way to do this...
String field = " ";
String num = Long.toString(n);
if (num.length() >= field.length())
return num;
StringBuffer b = new StringBuffer(field);
b.replace(b.length()-num.length(), b.length(), num);
return b.toString();
}
}
backport-util-concurrent-3.1-src/test/loops/src/CASLoops.java 0000644 0017507 0003772 00000046262 10643126465 023117 0 ustar dawidk dcl /*
* Written by Doug Lea and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
/*
* Estimates the difference in time for compareAndSet and CAS-like
* operations versus unsynchronized, non-volatile pseudo-CAS when
* updating random numbers. These estimates thus give the cost
* of atomicity/barriers/exclusion over and above the time to
* just compare and conditionally store (int) values, so are
* not intended to measure the "raw" cost of a CAS.
*
* Outputs, in nanoseconds:
* "Atomic CAS" AtomicInteger.compareAndSet
* "Updater CAS" CAS first comparing args
* "Volatile" pseudo-CAS using volatile store if comparison succeeds
* "Mutex" emulated compare and set done under AQS-based mutex lock
* "Synchronized" emulated compare and set done under a synchronized block.
*
* By default, these are printed for 1..#cpus threads, but you can
* change the upper bound number of threads by providing the
* first argument to this program.
*
* The last two kinds of runs (mutex and synchronized) are done only
* if this program is called with (any) second argument
*/
import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicInteger;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicLong;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
public class CASLoops {
static final int TRIALS = 2;
static final long BASE_SECS_PER_RUN = 4;
static final int NCPUS = Runtime.getRuntime().availableProcessors();
static int maxThreads = NCPUS;
static boolean includeLocks = false;
public static void main(String[] args) throws Exception {
if (args.length > 0)
maxThreads = Integer.parseInt(args[0]);
loopIters = new long[maxThreads+1];
if (args.length > 1)
includeLocks = true;
System.out.println("Warmup...");
for (int i = maxThreads; i > 0; --i) {
runCalibration(i, 10);
oneRun(i, loopIters[i] / 4, false);
System.out.print(".");
}
for (int i = 1; i <= maxThreads; ++i)
loopIters[i] = 0;
for (int j = 0; j < 2; ++j) {
for (int i = 1; i <= maxThreads; ++i) {
runCalibration(i, 1000);
oneRun(i, loopIters[i] / 8, false);
System.out.print(".");
}
}
for (int i = 1; i <= maxThreads; ++i)
loopIters[i] = 0;
for (int j = 0; j < TRIALS; ++j) {
System.out.println("Trial " + j);
for (int i = 1; i <= maxThreads; ++i) {
runCalibration(i, BASE_SECS_PER_RUN * 1000L);
oneRun(i, loopIters[i], true);
}
}
}
static final AtomicLong totalIters = new AtomicLong(0);
static final AtomicLong successes = new AtomicLong(0);
static final AtomicInteger sum = new AtomicInteger(0);
static final LoopHelpers.MarsagliaRandom rng = new LoopHelpers.MarsagliaRandom();
static long[] loopIters;
static final class NonAtomicInteger {
volatile int readBarrier;
int value;
NonAtomicInteger() {}
int get() {
int junk = readBarrier;
return value;
}
boolean compareAndSet(int cmp, int val) {
if (value == cmp) {
value = val;
return true;
}
return false;
}
void set(int val) { value = val; }
}
// static final class UpdaterAtomicInteger {
// volatile int value;
//
// static final AtomicIntegerFieldUpdater
// valueUpdater = AtomicIntegerFieldUpdater.newUpdater
// (UpdaterAtomicInteger.class, "value");
//
//
// UpdaterAtomicInteger() {}
// int get() {
// return value;
// }
// boolean compareAndSet(int cmp, int val) {
// return valueUpdater.compareAndSet(this, cmp, val);
// }
//
// void set(int val) { value = val; }
// }
//
static final class VolatileInteger {
volatile int value;
VolatileInteger() {}
int get() {
return value;
}
boolean compareAndSet(int cmp, int val) {
if (value == cmp) {
value = val;
return true;
}
return false;
}
void set(int val) { value = val; }
}
static final class SynchedInteger {
int value;
SynchedInteger() {}
int get() {
return value;
}
synchronized boolean compareAndSet(int cmp, int val) {
if (value == cmp) {
value = val;
return true;
}
return false;
}
synchronized void set(int val) { value = val; }
}
static final class LockedInteger extends ReentrantLock {
int value;
LockedInteger() {}
int get() {
return value;
}
boolean compareAndSet(int cmp, int val) {
lock();
try {
if (value == cmp) {
value = val;
return true;
}
return false;
} finally {
unlock();
}
}
void set(int val) {
lock();
try {
value = val;
} finally {
unlock();
}
}
}
// All these versions are copy-paste-hacked to avoid
// contamination with virtual call resolution etc.
// Use fixed-length unrollable inner loops to reduce safepoint checks
static final int innerPerOuter = 16;
static final class NonAtomicLoop implements Runnable {
final long iters;
final NonAtomicInteger obj;
final CyclicBarrier barrier;
NonAtomicLoop(long iters, NonAtomicInteger obj, CyclicBarrier b) {
this.iters = iters;
this.obj = obj;
this.barrier = b;
obj.set(rng.next());
}
public void run() {
try {
barrier.await();
long i = iters;
int y = 0;
int succ = 0;
while (i > 0) {
for (int k = 0; k < innerPerOuter; ++k) {
int x = obj.get();
int z = y + LoopHelpers.compute6(x);
if (obj.compareAndSet(x, z))
++succ;
y = LoopHelpers.compute7(z);
}
i -= innerPerOuter;
}
sum.getAndAdd(obj.get());
successes.getAndAdd(succ);
barrier.await();
}
catch (Exception ie) {
return;
}
}
}
static final class AtomicLoop implements Runnable {
final long iters;
final AtomicInteger obj;
final CyclicBarrier barrier;
AtomicLoop(long iters, AtomicInteger obj, CyclicBarrier b) {
this.iters = iters;
this.obj = obj;
this.barrier = b;
obj.set(rng.next());
}
public void run() {
try {
barrier.await();
long i = iters;
int y = 0;
int succ = 0;
while (i > 0) {
for (int k = 0; k < innerPerOuter; ++k) {
int x = obj.get();
int z = y + LoopHelpers.compute6(x);
if (obj.compareAndSet(x, z))
++succ;
y = LoopHelpers.compute7(z);
}
i -= innerPerOuter;
}
sum.getAndAdd(obj.get());
successes.getAndAdd(succ);
barrier.await();
}
catch (Exception ie) {
return;
}
}
}
// static final class UpdaterAtomicLoop implements Runnable {
// final long iters;
// final UpdaterAtomicInteger obj;
// final CyclicBarrier barrier;
// UpdaterAtomicLoop(long iters, UpdaterAtomicInteger obj, CyclicBarrier b) {
// this.iters = iters;
// this.obj = obj;
// this.barrier = b;
// obj.set(rng.next());
// }
//
// public void run() {
// try {
// barrier.await();
// long i = iters;
// int y = 0;
// int succ = 0;
// while (i > 0) {
// for (int k = 0; k < innerPerOuter; ++k) {
// int x = obj.get();
// int z = y + LoopHelpers.compute6(x);
// if (obj.compareAndSet(x, z))
// ++succ;
// y = LoopHelpers.compute7(z);
// }
// i -= innerPerOuter;
// }
// sum.getAndAdd(obj.get());
// successes.getAndAdd(succ);
// barrier.await();
// }
// catch (Exception ie) {
// return;
// }
// }
// }
static final class VolatileLoop implements Runnable {
final long iters;
final VolatileInteger obj;
final CyclicBarrier barrier;
VolatileLoop(long iters, VolatileInteger obj, CyclicBarrier b) {
this.iters = iters;
this.obj = obj;
this.barrier = b;
obj.set(rng.next());
}
public void run() {
try {
barrier.await();
long i = iters;
int y = 0;
int succ = 0;
while (i > 0) {
for (int k = 0; k < innerPerOuter; ++k) {
int x = obj.get();
int z = y + LoopHelpers.compute6(x);
if (obj.compareAndSet(x, z))
++succ;
y = LoopHelpers.compute7(z);
}
i -= innerPerOuter;
}
sum.getAndAdd(obj.get());
successes.getAndAdd(succ);
barrier.await();
}
catch (Exception ie) {
return;
}
}
}
static final class SynchedLoop implements Runnable {
final long iters;
final SynchedInteger obj;
final CyclicBarrier barrier;
SynchedLoop(long iters, SynchedInteger obj, CyclicBarrier b) {
this.iters = iters;
this.obj = obj;
this.barrier = b;
obj.set(rng.next());
}
public void run() {
try {
barrier.await();
long i = iters;
int y = 0;
int succ = 0;
while (i > 0) {
for (int k = 0; k < innerPerOuter; ++k) {
int x = obj.get();
int z = y + LoopHelpers.compute6(x);
if (obj.compareAndSet(x, z))
++succ;
y = LoopHelpers.compute7(z);
}
i -= innerPerOuter;
}
sum.getAndAdd(obj.get());
successes.getAndAdd(succ);
barrier.await();
}
catch (Exception ie) {
return;
}
}
}
static final class LockedLoop implements Runnable {
final long iters;
final LockedInteger obj;
final CyclicBarrier barrier;
LockedLoop(long iters, LockedInteger obj, CyclicBarrier b) {
this.iters = iters;
this.obj = obj;
this.barrier = b;
obj.set(rng.next());
}
public void run() {
try {
barrier.await();
long i = iters;
int y = 0;
int succ = 0;
while (i > 0) {
for (int k = 0; k < innerPerOuter; ++k) {
int x = obj.get();
int z = y + LoopHelpers.compute6(x);
if (obj.compareAndSet(x, z))
++succ;
y = LoopHelpers.compute7(z);
}
i -= innerPerOuter;
}
sum.getAndAdd(obj.get());
successes.getAndAdd(succ);
barrier.await();
}
catch (Exception ie) {
return;
}
}
}
static final int loopsPerTimeCheck = 2048;
static final class NACalibrationLoop implements Runnable {
final long endTime;
final NonAtomicInteger obj;
final CyclicBarrier barrier;
NACalibrationLoop(long endTime, NonAtomicInteger obj, CyclicBarrier b) {
this.endTime = endTime;
this.obj = obj;
this.barrier = b;
obj.set(rng.next());
}
public void run() {
try {
barrier.await();
long iters = 0;
int y = 0;
int succ = 0;
do {
int i = loopsPerTimeCheck;
while (i > 0) {
for (int k = 0; k < innerPerOuter; ++k) {
int x = obj.get();
int z = y + LoopHelpers.compute6(x);
if (obj.compareAndSet(x, z))
++succ;
y = LoopHelpers.compute7(z);
}
i -= innerPerOuter;
}
iters += loopsPerTimeCheck;
} while (System.currentTimeMillis() < endTime);
totalIters.getAndAdd(iters);
sum.getAndAdd(obj.get());
successes.getAndAdd(succ);
barrier.await();
}
catch (Exception ie) {
return;
}
}
}
static void runCalibration(int n, long nms) throws Exception {
long now = System.currentTimeMillis();
long endTime = now + nms;
CyclicBarrier b = new CyclicBarrier(n+1);
totalIters.set(0);
NonAtomicInteger a = new NonAtomicInteger();
for (int j = 0; j < n; ++j)
new Thread(new NACalibrationLoop(endTime, a, b)).start();
b.await();
b.await();
long ipt = totalIters.get() / n;
if (ipt > loopIters[n])
loopIters[n] = ipt;
if (sum.get() == 0) System.out.print(" ");
}
static long runNonAtomic(int n, long iters) throws Exception {
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier b = new CyclicBarrier(n+1, timer);
NonAtomicInteger a = new NonAtomicInteger();
for (int j = 0; j < n; ++j)
new Thread(new NonAtomicLoop(iters, a, b)).start();
b.await();
b.await();
if (sum.get() == 0) System.out.print(" ");
return timer.getTime();
}
// static long runUpdaterAtomic(int n, long iters) throws Exception {
// LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
// CyclicBarrier b = new CyclicBarrier(n+1, timer);
// UpdaterAtomicInteger a = new UpdaterAtomicInteger();
// for (int j = 0; j < n; ++j)
// new Thread(new UpdaterAtomicLoop(iters, a, b)).start();
// b.await();
// b.await();
// if (sum.get() == 0) System.out.print(" ");
// return timer.getTime();
// }
//
static long runAtomic(int n, long iters) throws Exception {
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier b = new CyclicBarrier(n+1, timer);
AtomicInteger a = new AtomicInteger();
for (int j = 0; j < n; ++j)
new Thread(new AtomicLoop(iters, a, b)).start();
b.await();
b.await();
if (sum.get() == 0) System.out.print(" ");
return timer.getTime();
}
static long runVolatile(int n, long iters) throws Exception {
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier b = new CyclicBarrier(n+1, timer);
VolatileInteger a = new VolatileInteger();
for (int j = 0; j < n; ++j)
new Thread(new VolatileLoop(iters, a, b)).start();
b.await();
b.await();
if (sum.get() == 0) System.out.print(" ");
return timer.getTime();
}
static long runSynched(int n, long iters) throws Exception {
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier b = new CyclicBarrier(n+1, timer);
SynchedInteger a = new SynchedInteger();
for (int j = 0; j < n; ++j)
new Thread(new SynchedLoop(iters, a, b)).start();
b.await();
b.await();
if (sum.get() == 0) System.out.print(" ");
return timer.getTime();
}
static long runLocked(int n, long iters) throws Exception {
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier b = new CyclicBarrier(n+1, timer);
LockedInteger a = new LockedInteger();
for (int j = 0; j < n; ++j)
new Thread(new LockedLoop(iters, a, b)).start();
b.await();
b.await();
if (sum.get() == 0) System.out.print(" ");
return timer.getTime();
}
static void report(String tag, long runtime, long basetime,
int nthreads, long iters) {
System.out.print(tag);
long t = (runtime - basetime) / iters;
if (nthreads > NCPUS)
t = t * NCPUS / nthreads;
System.out.print(LoopHelpers.rightJustify(t));
double secs = (double)(runtime) / 1000000000.0;
System.out.println("\t " + secs + "s run time");
}
static void oneRun(int i, long iters, boolean print) throws Exception {
if (print)
System.out.println("threads : " + i +
" base iters per thread per run : " +
LoopHelpers.rightJustify(loopIters[i]));
long ntime = runNonAtomic(i, iters);
if (print)
report("Base : ", ntime, ntime, i, iters);
Thread.sleep(100L);
long atime = runAtomic(i, iters);
if (print)
report("Atomic CAS : ", atime, ntime, i, iters);
Thread.sleep(100L);
// long gtime = runUpdaterAtomic(i, iters);
// if (print)
// report("Updater CAS : ", gtime, ntime, i, iters);
// Thread.sleep(100L);
long vtime = runVolatile(i, iters);
if (print)
report("Volatile : ", vtime, ntime, i, iters);
Thread.sleep(100L);
if (!includeLocks) return;
long mtime = runLocked(i, iters);
if (print)
report("Mutex : ", mtime, ntime, i, iters);
Thread.sleep(100L);
long stime = runSynched(i, iters);
if (print)
report("Synchronized: ", stime, ntime, i, iters);
Thread.sleep(100L);
}
}
backport-util-concurrent-3.1-src/test/loops/src/MapLoops.java 0000644 0017507 0003772 00000014526 10346121124 023207 0 ustar dawidk dcl /*
* @test
* @synopsis Exercise multithreaded maps, by default
* ConcurrentHashMap. Each thread does a random walk though elements
* of "key" array. On each iteration, it checks if table includes key.
* If absent, with probablility pinsert it inserts it, and if present,
* with probablility premove it removes it. (pinsert and premove are
* expressed as percentages to simplify parsing from command line.)
*/
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain. Use, modify, and
* redistribute this code in any way without acknowledgement.
*/
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.util.Map;
import java.util.Random;
public class MapLoops {
static int nkeys = 1000;
static int pinsert = 60;
static int premove = 2;
static int maxThreads = 100;
static int nops = 1000000;
static int removesPerMaxRandom;
static int insertsPerMaxRandom;
static final ExecutorService pool = Executors.newCachedThreadPool();
public static void main(String[] args) throws Exception {
Class mapClass = null;
if (args.length > 0) {
try {
mapClass = Class.forName(args[0]);
} catch(ClassNotFoundException e) {
throw new RuntimeException("Class " + args[0] + " not found.");
}
}
else
mapClass = edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap.class;
if (args.length > 1)
maxThreads = Integer.parseInt(args[1]);
if (args.length > 2)
nkeys = Integer.parseInt(args[2]);
if (args.length > 3)
pinsert = Integer.parseInt(args[3]);
if (args.length > 4)
premove = Integer.parseInt(args[4]);
if (args.length > 5)
nops = Integer.parseInt(args[5]);
// normalize probabilities wrt random number generator
removesPerMaxRandom = (int)(((double)premove/100.0 * 0x7FFFFFFFL));
insertsPerMaxRandom = (int)(((double)pinsert/100.0 * 0x7FFFFFFFL));
System.out.print("Class: " + mapClass.getName());
System.out.print(" threads: " + maxThreads);
System.out.print(" size: " + nkeys);
System.out.print(" ins: " + pinsert);
System.out.print(" rem: " + premove);
System.out.print(" ops: " + nops);
System.out.println();
int k = 1;
int warmups = 2;
for (int i = 1; i <= maxThreads;) {
Thread.sleep(100);
test(i, nkeys, mapClass);
if (warmups > 0)
--warmups;
else if (i == k) {
k = i << 1;
i = i + (i >>> 1);
}
else if (i == 1 && k == 2) {
i = k;
warmups = 1;
}
else
i = k;
}
pool.shutdown();
}
static Integer[] makeKeys(int n) {
LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
Integer[] key = new Integer[n];
for (int i = 0; i < key.length; ++i)
key[i] = new Integer(rng.next());
return key;
}
static void shuffleKeys(Integer[] key) {
Random rng = new Random();
for (int i = key.length; i > 1; --i) {
int j = rng.nextInt(i);
Integer tmp = key[j];
key[j] = key[i-1];
key[i-1] = tmp;
}
}
static void test(int i, int nkeys, Class mapClass) throws Exception {
System.out.print("Threads: " + i + "\t:");
Map map = (Map)mapClass.newInstance();
Integer[] key = makeKeys(nkeys);
// Uncomment to start with a non-empty table
// for (int j = 0; j < nkeys; j += 4) // start 1/4 occupied
// map.put(key[j], key[j]);
shuffleKeys(key);
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier barrier = new CyclicBarrier(i+1, timer);
for (int t = 0; t < i; ++t)
pool.execute(new Runner(t, map, key, barrier));
barrier.await();
barrier.await();
long time = timer.getTime();
long tpo = time / (i * (long)nops);
System.out.print(LoopHelpers.rightJustify(tpo) + " ns per op");
double secs = (double)(time) / 1000000000.0;
System.out.println("\t " + secs + "s run time");
map.clear();
}
static class Runner implements Runnable {
final Map map;
final Integer[] key;
final LoopHelpers.SimpleRandom rng;
final CyclicBarrier barrier;
int position;
int total;
Runner(int id, Map map, Integer[] key, CyclicBarrier barrier) {
this.map = map;
this.key = key;
this.barrier = barrier;
position = key.length / 2;
rng = new LoopHelpers.SimpleRandom((id + 1) * 8862213513L);
rng.next();
}
int step() {
// random-walk around key positions, bunching accesses
int r = rng.next();
position += (r & 7) - 3;
while (position >= key.length) position -= key.length;
while (position < 0) position += key.length;
Integer k = key[position];
Integer x = (Integer)map.get(k);
if (x != null) {
if (x.intValue() != k.intValue())
throw new Error("bad mapping: " + x + " to " + k);
if (r < removesPerMaxRandom) {
if (map.remove(k) != null) {
position = total % key.length; // move from position
return 2;
}
}
}
else if (r < insertsPerMaxRandom) {
++position;
map.put(k, k);
return 2;
}
// Uncomment to add a little computation between accesses
// total += LoopHelpers.compute1(k.intValue());
total += r;
return 1;
}
public void run() {
try {
barrier.await();
int ops = nops;
while (ops > 0)
ops -= step();
barrier.await();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
backport-util-concurrent-3.1-src/test/loops/src/SCollection.java 0000644 0017507 0003772 00000005477 10346121124 023700 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.ArrayList;
/**
* This is an incomplete implementation of a wrapper class
* that places read-write locks around unsynchronized Collections.
* Exists as a sample input for CollectionLoops test.
*/
public final class SCollection implements Collection {
private final Collection c;
private final ReentrantLock l = new ReentrantLock();
public SCollection(Collection c) {
if (c == null)
throw new NullPointerException();
this.c = c;
}
public SCollection() {
this(new ArrayList());
}
public final int size() {
l.lock(); try {return c.size();} finally { l.unlock(); }
}
public final boolean isEmpty(){
l.lock(); try {return c.isEmpty();} finally { l.unlock(); }
}
public final boolean contains(Object o) {
l.lock(); try {return c.contains(o);} finally { l.unlock(); }
}
public final boolean equals(Object o) {
l.lock(); try {return c.equals(o);} finally { l.unlock(); }
}
public final int hashCode() {
l.lock(); try {return c.hashCode();} finally { l.unlock(); }
}
public final String toString() {
l.lock(); try {return c.toString();} finally { l.unlock(); }
}
public final Iterator iterator() {
l.lock(); try {return c.iterator();} finally { l.unlock(); }
}
public final Object[] toArray() {
l.lock(); try {return c.toArray();} finally { l.unlock(); }
}
public final Object[] toArray(Object[] a) {
l.lock(); try {return c.toArray(a);} finally { l.unlock(); }
}
public final boolean add(Object e) {
l.lock(); try {return c.add(e);} finally { l.unlock(); }
}
public final boolean remove(Object o) {
l.lock(); try {return c.remove(o);} finally { l.unlock(); }
}
public final boolean containsAll(Collection coll) {
l.lock(); try {return c.containsAll(coll);} finally { l.unlock(); }
}
public final boolean addAll(Collection coll) {
l.lock(); try {return c.addAll(coll);} finally { l.unlock(); }
}
public final boolean removeAll(Collection coll) {
l.lock(); try {return c.removeAll(coll);} finally { l.unlock(); }
}
public final boolean retainAll(Collection coll) {
l.lock(); try {return c.retainAll(coll);} finally { l.unlock(); }
}
public final void clear() {
l.lock(); try {c.clear();} finally { l.unlock(); }
}
}
backport-util-concurrent-3.1-src/test/loops/src/SMap.java 0000644 0017507 0003772 00000004174 10256105111 022311 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import java.util.Map;
import java.util.Set;
import java.util.Collection;
/**
* This is an incomplete implementation of a wrapper class
* that places read-write locks around unsynchronized Maps.
* Exists as a sample input for MapLoops test.
*/
public class SMap implements Map {
private final Map m;
public SMap(Map m) {
if (m == null)
throw new NullPointerException();
this.m = m;
}
public SMap() {
this(new TreeMap()); // use TreeMap by default
}
public synchronized int size() {
return m.size();
}
public synchronized boolean isEmpty(){
return m.isEmpty();
}
public synchronized Object get(Object key) {
return m.get(key);
}
public synchronized boolean containsKey(Object key) {
return m.containsKey(key);
}
public synchronized boolean containsValue(Object value){
return m.containsValue(value);
}
public synchronized Set keySet() { // Not implemented
return m.keySet();
}
public synchronized Set entrySet() { // Not implemented
return m.entrySet();
}
public synchronized Collection values() { // Not implemented
return m.values();
}
public synchronized boolean equals(Object o) {
return m.equals(o);
}
public synchronized int hashCode() {
return m.hashCode();
}
public synchronized String toString() {
return m.toString();
}
public synchronized Object put(Object key, Object value) {
return m.put(key, value);
}
public synchronized Object remove(Object key) {
return m.remove(key);
}
public synchronized void putAll(Map map) {
m.putAll(map);
}
public synchronized void clear() {
m.clear();
}
}
backport-util-concurrent-3.1-src/test/loops/src/SimpleLoops.java 0000644 0017507 0003772 00000006361 10253737131 023731 0 ustar dawidk dcl /*
* @test
* @synopsis multiple threads using a single lock
*/
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain. Use, modify, and
* redistribute this code in any way without acknowledgement.
*/
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import edu.emory.mathcs.backport.java.util.*;
public final class SimpleLoops {
static final ExecutorService pool = Executors.newCachedThreadPool();
static final LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
static boolean print = false;
static int iters = 10000000;
public static void main(String[] args) throws Exception {
int maxThreads = 100;
if (args.length > 0)
maxThreads = Integer.parseInt(args[0]);
print = true;
int k = 1;
for (int i = 1; i <= maxThreads;) {
System.out.print("Threads: " + 1);
new Loop(1).test();
Thread.sleep(100);
if (i == k) {
k = i << 1;
i = i + (i >>> 1);
}
else
i = k;
}
pool.shutdown();
}
static final class Loop implements Runnable {
private int v = rng.next();
private volatile int result = 17;
private final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
private final CyclicBarrier barrier;
private final int nthreads;
private volatile int readBarrier;
Loop(int nthreads) {
this.nthreads = nthreads;
barrier = new CyclicBarrier(nthreads+1, timer);
}
final void test() throws Exception {
for (int i = 0; i < nthreads; ++i)
pool.execute(this);
barrier.await();
barrier.await();
if (print) {
long time = timer.getTime();
long tpi = time / ((long)iters * nthreads);
System.out.print("\t" + LoopHelpers.rightJustify(tpi) + " ns per lock");
double secs = (double)(time) / 1000000000.0;
System.out.println("\t " + secs + "s run time");
}
int r = result;
if (r == 0) // avoid overoptimization
System.out.println("useless result: " + r);
}
public final void run() {
try {
barrier.await();
int sum = v + 1;
int x = 0;
int n = iters;
while (n-- > 0) {
int k = (sum & 3);
if (k > 0) {
x = v;
while (k-- > 0)
x = LoopHelpers.compute1(x);
v = x;
}
else x = sum + 1;
if ((x += readBarrier) == 0)
++readBarrier;
for (int l = x & 7; l > 0; --l)
sum += LoopHelpers.compute1(sum);
}
barrier.await();
result += sum;
}
catch (Exception ie) {
return;
}
}
}
}
backport-util-concurrent-3.1-src/test/loops/src/RLMap.java 0000644 0017507 0003772 00000004456 10256105111 022427 0 ustar dawidk dcl import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import java.util.Map;
import java.util.Set;
import java.util.Collection;
/**
* This is an incomplete implementation of a wrapper class
* that places read-write locks around unsynchronized Maps.
* Exists as a sample input for MapLoops test.
*/
public class RLMap implements Map {
private final Map m;
private final ReentrantLock rl = new ReentrantLock();
public RLMap(Map m) {
if (m == null)
throw new NullPointerException();
this.m = m;
}
public RLMap() {
this(new TreeMap()); // use TreeMap by default
}
public int size() {
rl.lock(); try {return m.size();} finally { rl.unlock(); }
}
public boolean isEmpty(){
rl.lock(); try {return m.isEmpty();} finally { rl.unlock(); }
}
public Object get(Object key) {
rl.lock(); try {return m.get(key);} finally { rl.unlock(); }
}
public boolean containsKey(Object key) {
rl.lock(); try {return m.containsKey(key);} finally { rl.unlock(); }
}
public boolean containsValue(Object value){
rl.lock(); try {return m.containsValue(value);} finally { rl.unlock(); }
}
public Set keySet() { // Not implemented
return m.keySet();
}
public Set entrySet() { // Not implemented
return m.entrySet();
}
public Collection values() { // Not implemented
return m.values();
}
public boolean equals(Object o) {
rl.lock(); try {return m.equals(o);} finally { rl.unlock(); }
}
public int hashCode() {
rl.lock(); try {return m.hashCode();} finally { rl.unlock(); }
}
public String toString() {
rl.lock(); try {return m.toString();} finally { rl.unlock(); }
}
public Object put(Object key, Object value) {
rl.lock(); try {return m.put(key, value);} finally { rl.unlock(); }
}
public Object remove(Object key) {
rl.lock(); try {return m.remove(key);} finally { rl.unlock(); }
}
public void putAll(Map map) {
rl.lock(); try {m.putAll(map);} finally { rl.unlock(); }
}
public void clear() {
rl.lock(); try {m.clear();} finally { rl.unlock(); }
}
}
backport-util-concurrent-3.1-src/test/loops/src/CountedMapLoops.java 0000644 0017507 0003772 00000015010 10431260156 024522 0 ustar dawidk dcl /*
* @test
* @synopsis Exercise multithreaded maps, byt default ConcurrentHashMap
* Multithreaded hash table test. Each thread does a random walk
* though elements of "key" array. On each iteration, it checks if
* table includes key. If absent, with probablility pinsert it
* inserts it, and if present, with probablility premove it removes
* it. (pinsert and premove are expressed as percentages to simplify
* parsing from command line.)
*/
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain. Use, modify, and
* redistribute this code in any way without acknowledgement.
*/
import java.util.Map;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
public class CountedMapLoops {
static int nkeys = 100000;
static int pinsert = 60;
static int premove = 2;
static int maxThreads = 100;
static int nops = 2000000;
static int removesPerMaxRandom;
static int insertsPerMaxRandom;
static final ExecutorService pool = Executors.newCachedThreadPool();
public static void main(String[] args) throws Exception {
Class mapClass = null;
if (args.length > 0) {
try {
mapClass = Class.forName(args[0]);
} catch(ClassNotFoundException e) {
throw new RuntimeException("Class " + args[0] + " not found.");
}
}
else
mapClass = edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap.class;
if (args.length > 1)
maxThreads = Integer.parseInt(args[1]);
if (args.length > 2)
nkeys = Integer.parseInt(args[2]);
if (args.length > 3)
pinsert = Integer.parseInt(args[3]);
if (args.length > 4)
premove = Integer.parseInt(args[4]);
if (args.length > 5)
nops = Integer.parseInt(args[5]);
// normalize probabilities wrt random number generator
removesPerMaxRandom = (int)(((double)premove/100.0 * 0x7FFFFFFFL));
insertsPerMaxRandom = (int)(((double)pinsert/100.0 * 0x7FFFFFFFL));
System.out.print("Class: " + mapClass.getName());
System.out.print(" threads: " + maxThreads);
System.out.print(" size: " + nkeys);
System.out.print(" ins: " + pinsert);
System.out.print(" rem: " + premove);
System.out.print(" ops: " + nops);
System.out.println();
final LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
Integer[] key = new Integer[nkeys];
for (int i = 0; i < key.length; ++i)
key[i] = new Integer(rng.next());
AtomicInteger counter;
// warmup
System.out.println("Warmup...");
for (int k = 0; k < 2; ++k) {
Map map = (Map)mapClass.newInstance();
counter = new AtomicInteger(0);
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier barrier = new CyclicBarrier(1, timer);
new Runner(map, key, barrier, counter).run();
int size = map.size();
if (size != counter.get()) throw new Error();
map.clear();
map = null;
Thread.sleep(100);
}
System.gc();
int k = 1;
for (int i = 1; i <= maxThreads;) {
System.out.print("Threads: " + i + "\t:");
Map map = (Map)mapClass.newInstance();
counter = new AtomicInteger(0);
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier barrier = new CyclicBarrier(i+1, timer);
for (int t = 0; t < i; ++t)
pool.execute(new Runner(map, key, barrier, counter));
barrier.await();
barrier.await();
long time = timer.getTime();
long tpo = time / (i * (long)nops);
System.out.print(LoopHelpers.rightJustify(tpo) + " ns per op");
double secs = (double)(time) / 1000000000.0;
System.out.println("\t " + secs + "s run time");
int size = map.size();
if (size != counter.get()) throw new Error();
map.clear();
map = null;
// System.gc();
Thread.sleep(100);
if (i == k) {
k = i << 1;
i = i + (i >>> 1);
}
else
i = k;
}
pool.shutdown();
}
static class Runner implements Runnable {
final Map map;
final Integer[] key;
final LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
final CyclicBarrier barrier;
final AtomicInteger counter;
int position;
int total;
Runner(Map map, Integer[] key,
CyclicBarrier barrier, AtomicInteger counter) {
this.map = map;
this.key = key;
this.barrier = barrier;
this.counter = counter;
position = key.length / 2;
}
int step() {
// random-walk around key positions, bunching accesses
int r = rng.next();
position += (r & 7) - 3;
while (position >= key.length) position -= key.length;
while (position < 0) position += key.length;
Integer k = key[position];
Integer x = (Integer)map.get(k);
if (x != null) {
// if (x.intValue() != k.intValue())
// throw new Error("bad mapping: " + x + " to " + k);
if (r < removesPerMaxRandom) {
if (map.remove(k) != null) {
counter.getAndDecrement();
position = total % key.length; // move from position
return 2;
}
}
}
else if (r < insertsPerMaxRandom) {
if (map.put(k, k) == null)
counter.getAndIncrement();
return 2;
}
// total += LoopHelpers.compute1(k.intValue());
total += r;
return 1;
}
public void run() {
try {
barrier.await();
int ops = nops;
while (ops > 0)
ops -= step();
barrier.await();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
backport-util-concurrent-3.1-src/test/loops/src/ConcurrentHashSet.java 0000644 0017507 0003772 00000004422 10431260156 025055 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
// A set wrapper over CHM for testing
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import java.io.*;
public class ConcurrentHashSet extends AbstractSet
implements Set, Serializable {
private final ConcurrentHashMap m; // The backing map
private transient Set keySet; // Its keySet
public ConcurrentHashSet() {
m = new ConcurrentHashMap();
keySet = m.keySet();
}
public ConcurrentHashSet(int initialCapacity) {
m = new ConcurrentHashMap(initialCapacity);
keySet = m.keySet();
}
public ConcurrentHashSet(int initialCapacity, float loadFactor,
int concurrencyLevel) {
m = new ConcurrentHashMap(initialCapacity, loadFactor,
concurrencyLevel);
keySet = m.keySet();
}
public int size() { return m.size(); }
public boolean isEmpty() { return m.isEmpty(); }
public boolean contains(Object o) { return m.containsKey(o); }
public Iterator iterator() { return keySet.iterator(); }
public Object[] toArray() { return keySet.toArray(); }
public Object[] toArray(Object[] a) { return keySet.toArray(a); }
public boolean add(Object e) {
return m.put(e, Boolean.TRUE) == null;
}
public boolean remove(Object o) { return m.remove(o) != null; }
public boolean removeAll(Collection c) {
return keySet.removeAll(c);
}
public boolean retainAll(Collection c) {
return keySet.retainAll(c);
}
public void clear() { m.clear(); }
public boolean equals(Object o) { return keySet.equals(o); }
public int hashCode() { return keySet.hashCode(); }
private static final long serialVersionUID = 2454657854757543876L;
private void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
s.defaultReadObject();
keySet = m.keySet();
}
}
backport-util-concurrent-3.1-src/test/loops/src/IteratorLoops.java 0000644 0017507 0003772 00000007256 10431777323 024302 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.helpers.Utils;
import java.util.Collection;
import java.util.Iterator;
import java.util.ArrayList;
/**
* Estimates time per iteration of collection iterators. Preloads
* most elements, but adds about 1/8 of them dynamically to preclude
* overly clever optimizations. The array of collections has
* approximately exponentially different lengths, so check both short
* and long iterators. Reports include times for adds and other
* checks, so overestimate times per iteration.
*/
public final class IteratorLoops {
static final int DEFAULT_SIZE = 16384;
static final int DEFAULT_TRIALS = 4;
static final int NC = 16; // number of collections must be power of 2
static volatile long mismatches = 0;
static int randomSeed = 3122688;
public static void main(String[] args) throws Exception {
Class klass = Class.forName(args[0]);
int n = (args.length <= 1)? DEFAULT_SIZE : Integer.parseInt(args[1]);
int t = (args.length <= 2)? DEFAULT_TRIALS : Integer.parseInt(args[2]);
System.out.print("Class: " + klass.getName());
System.out.print(" ~iters: " + (long)n * (long)n);
System.out.print(" trials: " + t);
System.out.println();
Collection[] colls =
(Collection[])new Collection[NC];
for (int k = 0; k < colls.length; ++k)
colls[k] = (Collection)klass.newInstance();
for (int i = 0; i < t; ++i)
new IteratorLoops(colls).oneRun(n);
if (mismatches != 0)
throw new Error("Bad checksum :" + mismatches);
}
private int elementCount;
private final Collection[] cs;
IteratorLoops(Collection[] colls) {
cs = colls;
elementCount = 0;
}
void oneRun(int n) {
preload(n);
long startTime = Utils.nanoTime();
long count = traversals(n);
double elapsed = (double)(Utils.nanoTime() - startTime);
double npi = elapsed / count;
double secs = elapsed / 1000000000;
System.out.print("" + npi + " ns/iter " + secs + "s run time\n");
}
long traversals(int n) {
long count = 0;
long check = 0;
for (int i = 0; i < n; i++) {
check += elementCount;
count += counts();
maybeAdd();
}
if (count != check)
mismatches = count;
return count;
}
int counts() {
int count = 0;
for (int k = 0; k < cs.length; ++k) {
for (Iterator it = cs[k].iterator(); it.hasNext();) {
if (it.next() != null)
++count;
}
}
return count;
}
void maybeAdd() {
int r = randomSeed;
r ^= r << 6;
r ^= r >>> 21;
r ^= r << 7;
randomSeed = r;
if ((r >>> 29) == 0)
cs[r & (cs.length-1)].add(new Integer(elementCount++));
}
void preload(int n) {
for (int i = 0; i < cs.length; ++i)
cs[i].clear();
int k = (n - n / 8) / 2;
ArrayList al = new ArrayList(k+1);
for (int i = 0; i < cs.length; ++i) {
if (k > 0) {
for (int j = 0; j < k; ++j)
al.add(new Integer(elementCount++));
cs[i].addAll(al);
al.clear();
}
k >>>= 1;
}
// let GC settle down
try { Thread.sleep(500); } catch(Exception ex) { return; }
}
}
backport-util-concurrent-3.1-src/test/loops/src/ConcurrentQueueLoops.java 0000644 0017507 0003772 00000012137 10346121124 025615 0 ustar dawidk dcl /*
* @test %I% %E%
* @bug 4486658
* @compile -source 1.5 ConcurrentQueueLoops.java
* @run main/timeout=230 ConcurrentQueueLoops
* @summary Checks that a set of threads can repeatedly get and modify items
*/
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain. Use, modify, and
* redistribute this code in any way without acknowledgement.
*/
import edu.emory.mathcs.backport.java.util.*;
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import edu.emory.mathcs.backport.java.util.concurrent.helpers.Utils;
import edu.emory.mathcs.backport.java.util.Queue;
import java.util.ArrayList;
public class ConcurrentQueueLoops {
static final ExecutorService pool = Executors.newCachedThreadPool();
static boolean print = false;
static final Integer zero = new Integer(0);
static final Integer one = new Integer(1);
static int workMask;
static final long RUN_TIME_NANOS = 5 * 1000L * 1000L * 1000L;
static final int BATCH_SIZE = 8;
public static void main(String[] args) throws Exception {
int maxStages = 100;
int work = 1024;
Class klass = null;
if (args.length > 0) {
try {
klass = Class.forName(args[0]);
} catch(ClassNotFoundException e) {
throw new RuntimeException("Class " + args[0] + " not found.");
}
}
if (args.length > 1)
maxStages = Integer.parseInt(args[1]);
if (args.length > 2)
work = Integer.parseInt(args[2]);
workMask = work - 1;
System.out.print("Class: " + klass.getName());
System.out.print(" stages: " + maxStages);
System.out.println(" work: " + work);
print = false;
System.out.println("Warmup...");
// oneRun(klass, 4);
//
Thread.sleep(100);
oneRun(klass, 1);
Thread.sleep(100);
print = true;
int k = 1;
for (int i = 1; i <= maxStages;) {
oneRun(klass, i);
if (i == k) {
k = i << 1;
i = i + (i >>> 1);
}
else
i = k;
}
pool.shutdown();
}
static final class Stage implements Callable {
final Queue queue;
final CyclicBarrier barrier;
final int nthreads;
Stage (Queue q, CyclicBarrier b, int nthreads) {
queue = q;
barrier = b;
this.nthreads = nthreads;
}
static int compute(int l) {
if (l == 0)
return (int)Utils.nanoTime();
int nn = (l >>> 7) & workMask;
while (nn-- > 0)
l = LoopHelpers.compute6(l);
return l;
}
public Object call() {
try {
barrier.await();
long now = Utils.nanoTime();
long stopTime = now + RUN_TIME_NANOS;
int l = (int)now;
int takes = 0;
int misses = 0;
int lmask = 1;
for (;;) {
l = compute(l);
Integer item = (Integer)queue.poll();
if (item != null) {
++takes;
if (item == one)
l = LoopHelpers.compute6(l);
} else if ((misses++ & 255) == 0 &&
Utils.nanoTime() >= stopTime) {
return new Integer(takes);
} else {
for (int i = 0; i < BATCH_SIZE; ++i) {
queue.offer(((l & lmask)== 0)? zero : one);
if ((lmask <<= 1) == 0) lmask = 1;
if (i != 0) l = compute(l);
}
}
}
}
catch (Exception ie) {
ie.printStackTrace();
throw new Error("Call loop failed");
}
}
}
static void oneRun(Class klass, int n) throws Exception {
Queue q = (Queue)klass.newInstance();
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier barrier = new CyclicBarrier(n + 1, timer);
ArrayList results = new ArrayList(n);
for (int i = 0; i < n; ++i)
results.add(pool.submit(new Stage(q, barrier, n)));
if (print)
System.out.print("Threads: " + n + "\t:");
barrier.await();
int total = 0;
for (int i = 0; i < n; ++i) {
Future f = (Future)results.get(i);
Integer r = (Integer)f.get();
total += r.intValue();
}
long endTime = Utils.nanoTime();
long time = endTime - timer.startTime;
long ips = 1000000000L * total / time;
if (print)
System.out.print(LoopHelpers.rightJustify(ips) + " items per sec");
if (print)
System.out.println();
}
}
backport-util-concurrent-3.1-src/test/loops/src/CachedThreadPoolLoops.java 0000644 0017507 0003772 00000007042 10346121124 025616 0 ustar dawidk dcl /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain. Use, modify, and
* redistribute this code in any way without acknowledgement.
*/
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import edu.emory.mathcs.backport.java.util.concurrent.helpers.Utils;
public class CachedThreadPoolLoops {
static final AtomicInteger remaining = new AtomicInteger();
static final int maxIters = 1000000;
public static void main(String[] args) throws Exception {
int maxThreads = 100;
if (args.length > 0)
maxThreads = Integer.parseInt(args[0]);
System.out.print("Warmup:");
for (int j = 0; j < 2; ++j) {
int k = 1;
for (int i = 1; i <= maxThreads;) {
System.out.print(" " + i);
oneTest(i, 10000, false);
Thread.sleep(100);
if (i == k) {
k = i << 1;
i = i + (i >>> 1);
}
else
i = k;
}
}
System.out.println();
int k = 1;
for (int i = 1; i <= maxThreads;) {
System.out.println("Threads:" + i);
oneTest(i, maxIters, true);
Thread.sleep(100);
if (i == k) {
k = i << 1;
i = i + (i >>> 1);
}
else
i = k;
}
}
static void oneTest(int nThreads, int iters, boolean print) throws Exception {
if (print) System.out.print("SynchronousQueue ");
oneRun(new SynchronousQueue(false), nThreads, iters, print);
if (print) System.out.print("SynchronousQueue(fair) ");
oneRun(new SynchronousQueue(true), nThreads, iters, print);
}
static final class Task implements Runnable {
final ThreadPoolExecutor pool;
final CountDownLatch done;
Task(ThreadPoolExecutor p, CountDownLatch d) {
pool = p;
done = d;
}
public void run() {
done.countDown();
remaining.incrementAndGet();
int n;
while (!Thread.interrupted() &&
(n = remaining.get()) > 0 &&
done.getCount() > 0) {
if (remaining.compareAndSet(n, n-1)) {
try {
pool.execute(this);
}
catch (RuntimeException ex) {
System.out.print("*");
while (done.getCount() > 0) done.countDown();
return;
}
}
}
}
}
static void oneRun(BlockingQueue q, int nThreads, int iters, boolean print) throws Exception {
ThreadPoolExecutor pool =
new ThreadPoolExecutor(nThreads+1, Integer.MAX_VALUE,
1L, TimeUnit.SECONDS, q);
CountDownLatch done = new CountDownLatch(iters);
remaining.set(nThreads-1);
pool.prestartAllCoreThreads();
Task t = new Task(pool, done);
long start = Utils.nanoTime();
pool.execute(t);
done.await();
long time = Utils.nanoTime() - start;
if (print)
System.out.println("\t: " + LoopHelpers.rightJustify(time / iters) + " ns per task");
q.clear();
Thread.sleep(100);
pool.shutdown();
Thread.sleep(100);
pool.shutdownNow();
}
}
backport-util-concurrent-3.1-src/test/loops/src/LastKeyOfSubMap.java 0000644 0017507 0003772 00000002564 10256105111 024423 0 ustar dawidk dcl // from bug report 5018354
import edu.emory.mathcs.backport.java.util.*;
import java.util.Comparator;
import java.util.SortedMap;
public class LastKeyOfSubMap {
private static final Comparator NULL_AT_END = new Comparator() {
/**
* Allows for nulls. Null is greater than anything non-null.
*/
public int compare(Object pObj1, Object pObj2) {
if (pObj1 == null && pObj2 == null) return 0;
if (pObj1 == null && pObj2 != null) return 1;
if (pObj1 != null && pObj2 == null) return -1;
return ((Comparable) pObj1).compareTo(pObj2);
}
};
public static void main(String[] pArgs) {
SortedMap m1 = new TreeMap(NULL_AT_END);
m1.put("a", "a");
m1.put("b", "b");
m1.put("c", "c");
m1.put(null, "d");
SortedMap m2 = new TreeMap(m1);
System.out.println(m1.lastKey());
System.out.println(m1.get(m1.lastKey()));
Object m1lk = m1.remove(m1.lastKey());
if (m1lk == null)
throw new Error("bad remove of last key");
m2 = m2.tailMap("b");
System.out.println(m2.lastKey());
System.out.println(m2.get(m2.lastKey()));
Object m2lk = m2.remove(m2.lastKey());
if (m2lk == null)
throw new Error("bad remove of last key");
}
}
backport-util-concurrent-3.1-src/test/loops/src/SetBash.java 0000644 0017507 0003772 00000011133 10431260156 023001 0 ustar dawidk dcl /*
* Written by Doug Lea and Josh Bloch with assistance from members of
* JCP JSR-166 Expert Group and released to the public domain, as
* explained at http://creativecommons.org/licenses/publicdomain
*/
import java.util.Set;
import java.util.Iterator;
import java.util.Random;
import java.util.Arrays;
import java.util.Collections;
public class SetBash {
static Random rnd = new Random();
public static void main(String[] args) {
int numItr = Integer.parseInt(args[1]);
int setSize = Integer.parseInt(args[2]);
Class cl = null;
try {
cl = Class.forName(args[0]);
} catch(ClassNotFoundException e) {
fail("Class " + args[0] + " not found.");
}
boolean synch = (args.length>3);
for (int i=0; i