harmony-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From hinde...@apache.org
Subject svn commit: r794678 [18/19] - in /harmony/enhanced/classlib/trunk/modules/concurrent/src: main/java/java/util/concurrent/ main/java/java/util/concurrent/atomic/ main/java/java/util/concurrent/locks/ test/java/
Date Thu, 16 Jul 2009 14:01:17 GMT
Added: harmony/enhanced/classlib/trunk/modules/concurrent/src/main/java/java/util/concurrent/package-info.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/main/java/java/util/concurrent/package-info.java?rev=794678&view=auto
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/main/java/java/util/concurrent/package-info.java (added)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/main/java/java/util/concurrent/package-info.java Thu Jul 16 14:01:15 2009
@@ -0,0 +1,233 @@
+/*
+ * 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
+ */
+
+/**
+ * Utility classes commonly useful in concurrent programming.  This
+ * package includes a few small standardized extensible frameworks, as
+ * well as some classes that provide useful functionality and are
+ * otherwise tedious or difficult to implement.  Here are brief
+ * descriptions of the main components.  See also the
+ * {@link java.util.concurrent.locks} and
+ * {@link java.util.concurrent.atomic} packages.
+ *
+ * <h2>Executors</h2>
+ *
+ * <b>Interfaces.</b>
+ *
+ * {@link java.util.concurrent.Executor} is a simple standardized
+ * interface for defining custom thread-like subsystems, including
+ * thread pools, asynchronous IO, and lightweight task frameworks.
+ * Depending on which concrete Executor class is being used, tasks may
+ * execute in a newly created thread, an existing task-execution thread,
+ * or the thread calling {@link java.util.concurrent.Executor#execute
+ * execute}, and may execute sequentially or concurrently.
+ *
+ * {@link java.util.concurrent.ExecutorService} provides a more
+ * complete asynchronous task execution framework.  An
+ * ExecutorService manages queuing and scheduling of tasks,
+ * and allows controlled shutdown.
+ *
+ * The {@link java.util.concurrent.ScheduledExecutorService}
+ * subinterface and associated interfaces add support for
+ * delayed and periodic task execution.  ExecutorServices
+ * provide methods arranging asynchronous execution of any
+ * function expressed as {@link java.util.concurrent.Callable},
+ * the result-bearing analog of {@link java.lang.Runnable}.
+ *
+ * A {@link java.util.concurrent.Future} returns the results of
+ * a function, allows determination of whether execution has
+ * completed, and provides a means to cancel execution.
+ *
+ * A {@link java.util.concurrent.RunnableFuture} is a {@code Future}
+ * that possesses a {@code run} method that upon execution,
+ * sets its results.
+ *
+ * <p>
+ *
+ * <b>Implementations.</b>
+ *
+ * Classes {@link java.util.concurrent.ThreadPoolExecutor} and
+ * {@link java.util.concurrent.ScheduledThreadPoolExecutor}
+ * provide tunable, flexible thread pools.
+ *
+ * The {@link java.util.concurrent.Executors} class provides
+ * factory methods for the most common kinds and configurations
+ * of Executors, as well as a few utility methods for using
+ * them.  Other utilities based on {@code Executors} include the
+ * concrete class {@link java.util.concurrent.FutureTask}
+ * providing a common extensible implementation of Futures, and
+ * {@link java.util.concurrent.ExecutorCompletionService}, that
+ * assists in coordinating the processing of groups of
+ * asynchronous tasks.
+ *
+ * <h2>Queues</h2>
+ *
+ * The {@link java.util.concurrent.ConcurrentLinkedQueue} class
+ * supplies an efficient scalable thread-safe non-blocking FIFO
+ * queue.
+ *
+ * <p>Five implementations in {@code java.util.concurrent} support
+ * the extended {@link java.util.concurrent.BlockingQueue}
+ * interface, that defines blocking versions of put and take:
+ * {@link java.util.concurrent.LinkedBlockingQueue},
+ * {@link java.util.concurrent.ArrayBlockingQueue},
+ * {@link java.util.concurrent.SynchronousQueue},
+ * {@link java.util.concurrent.PriorityBlockingQueue}, and
+ * {@link java.util.concurrent.DelayQueue}.
+ * The different classes cover the most common usage contexts
+ * for producer-consumer, messaging, parallel tasking, and
+ * related concurrent designs.
+ *
+ * <h2>Timing</h2>
+ *
+ * The {@link java.util.concurrent.TimeUnit} class provides
+ * multiple granularities (including nanoseconds) for
+ * specifying and controlling time-out based operations.  Most
+ * classes in the package contain operations based on time-outs
+ * in addition to indefinite waits.  In all cases that
+ * time-outs are used, the time-out specifies the minimum time
+ * that the method should wait before indicating that it
+ * timed-out.  Implementations make a &quot;best effort&quot;
+ * to detect time-outs as soon as possible after they occur.
+ * However, an indefinite amount of time may elapse between a
+ * time-out being detected and a thread actually executing
+ * again after that time-out.  All methods that accept timeout
+ * parameters treat values less than or equal to zero to mean
+ * not to wait at all.  To wait "forever", you can use a value
+ * of {@code Long.MAX_VALUE}.
+ *
+ * <h2>Synchronizers</h2>
+ *
+ * Four classes aid common special-purpose synchronization idioms.
+ * {@link java.util.concurrent.Semaphore} is a classic concurrency tool.
+ * {@link java.util.concurrent.CountDownLatch} is a very simple yet very
+ * common utility for blocking until a given number of signals, events,
+ * or conditions hold.  A {@link java.util.concurrent.CyclicBarrier} is a
+ * resettable multiway synchronization point useful in some styles of
+ * parallel programming.  An {@link java.util.concurrent.Exchanger} allows
+ * two threads to exchange objects at a rendezvous point, and is useful
+ * in several pipeline designs.
+ *
+ * <h2>Concurrent Collections</h2>
+ *
+ * Besides Queues, this package supplies Collection implementations
+ * designed for use in multithreaded contexts:
+ * {@link java.util.concurrent.ConcurrentHashMap},
+ * {@link java.util.concurrent.CopyOnWriteArrayList}, and
+ * {@link java.util.concurrent.CopyOnWriteArraySet}.
+ * When many threads are expected to access a given collection, a
+ * {@code ConcurrentHashMap} is normally preferable to a synchronized
+ * {@code HashMap}. A {@code CopyOnWriteArrayList} is preferable to a
+ * synchronized {@code ArrayList} when the expected number of reads and
+ * traversals greatly outnumber the number of updates to a list.
+
+ * <p>The "Concurrent" prefix used with some classes in this package
+ * is a shorthand indicating several differences from similar
+ * "synchronized" classes.  For example {@code java.util.Hashtable} and
+ * {@code Collections.synchronizedMap(new HashMap())} are
+ * synchronized.  But {@link
+ * java.util.concurrent.ConcurrentHashMap} is "concurrent".  A
+ * concurrent collection is thread-safe, but not governed by a
+ * single exclusion lock.  In the particular case of
+ * ConcurrentHashMap, it safely permits any number of
+ * concurrent reads as well as a tunable number of concurrent
+ * writes.  "Synchronized" classes can be useful when you need
+ * to prevent all access to a collection via a single lock, at
+ * the expense of poorer scalability.  In other cases in which
+ * multiple threads are expected to access a common collection,
+ * "concurrent" versions are normally preferable.  And
+ * unsynchronized collections are preferable when either
+ * collections are unshared, or are accessible only when
+ * holding other locks.
+ *
+ * <p>Most concurrent Collection implementations (including most
+ * Queues) also differ from the usual java.util conventions in that
+ * their Iterators provide <em>weakly consistent</em> rather than
+ * fast-fail traversal.  A weakly consistent iterator is thread-safe,
+ * but does not necessarily freeze the collection while iterating, so
+ * it may (or may not) reflect any updates since the iterator was
+ * created.
+ *
+ * <h2><a name="MemoryVisibility">Memory Consistency Properties</a></h2>
+ *
+ * <a href="http://java.sun.com/docs/books/jls/third_edition/html/memory.html">
+ * Chapter 17 of the Java Language Specification</a> defines the
+ * <i>happens-before</i> relation on memory operations such as reads and
+ * writes of shared variables.  The results of a write by one thread are
+ * guaranteed to be visible to a read by another thread only if the write
+ * operation <i>happens-before</i> the read operation.  The
+ * {@code synchronized} and {@code volatile} constructs, as well as the
+ * {@code Thread.start()} and {@code Thread.join()} methods, can form
+ * <i>happens-before</i> relationships.  In particular:
+ *
+ * <ul>
+ *   <li>Each action in a thread <i>happens-before</i> every action in that
+ *   thread that comes later in the program's order.
+ *
+ *   <li>An unlock ({@code synchronized} block or method exit) of a
+ *   monitor <i>happens-before</i> every subsequent lock ({@code synchronized}
+ *   block or method entry) of that same monitor.  And because
+ *   the <i>happens-before</i> relation is transitive, all actions
+ *   of a thread prior to unlocking <i>happen-before</i> all actions
+ *   subsequent to any thread locking that monitor.
+ *
+ *   <li>A write to a {@code volatile} field <i>happens-before</i> every
+ *   subsequent read of that same field.  Writes and reads of
+ *   {@code volatile} fields have similar memory consistency effects
+ *   as entering and exiting monitors, but do <em>not</em> entail
+ *   mutual exclusion locking.
+ *
+ *   <li>A call to {@code start} on a thread <i>happens-before</i> any
+ *   action in the started thread.
+ *
+ *   <li>All actions in a thread <i>happen-before</i> any other thread
+ *   successfully returns from a {@code join} on that thread.
+ *
+ * </ul>
+ *
+ *
+ * The methods of all classes in {@code java.util.concurrent} and its
+ * subpackages extend these guarantees to higher-level
+ * synchronization.  In particular:
+ *
+ * <ul>
+ *
+ *   <li>Actions in a thread prior to placing an object into any concurrent
+ *   collection <i>happen-before</i> actions subsequent to the access or
+ *   removal of that element from the collection in another thread.
+ *
+ *   <li>Actions in a thread prior to the submission of a {@code Runnable}
+ *   to an {@code Executor} <i>happen-before</i> its execution begins.
+ *   Similarly for {@code Callables} submitted to an {@code ExecutorService}.
+ *
+ *   <li>Actions taken by the asynchronous computation represented by a
+ *   {@code Future} <i>happen-before</i> actions subsequent to the
+ *   retrieval of the result via {@code Future.get()} in another thread.
+ *
+ *   <li>Actions prior to "releasing" synchronizer methods such as
+ *   {@code Lock.unlock}, {@code Semaphore.release}, and
+ *   {@code CountDownLatch.countDown} <i>happen-before</i> actions
+ *   subsequent to a successful "acquiring" method such as
+ *   {@code Lock.lock}, {@code Semaphore.acquire},
+ *   {@code Condition.await}, and {@code CountDownLatch.await} on the
+ *   same synchronizer object in another thread.
+ *
+ *   <li>For each pair of threads that successfully exchange objects via
+ *   an {@code Exchanger}, actions prior to the {@code exchange()}
+ *   in each thread <i>happen-before</i> those subsequent to the
+ *   corresponding {@code exchange()} in another thread.
+ *
+ *   <li>Actions prior to calling {@code CyclicBarrier.await}
+ *   <i>happen-before</i> actions performed by the barrier action, and
+ *   actions performed by the barrier action <i>happen-before</i> actions
+ *   subsequent to a successful return from the corresponding {@code await}
+ *   in other threads.
+ *
+ * </ul>
+ *
+ * @since 1.5
+ */
+package java.util.concurrent;

Propchange: harmony/enhanced/classlib/trunk/modules/concurrent/src/main/java/java/util/concurrent/package-info.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/main/java/java/util/concurrent/package.html
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/main/java/java/util/concurrent/package.html?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/main/java/java/util/concurrent/package.html (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/main/java/java/util/concurrent/package.html Thu Jul 16 14:01:15 2009
@@ -1,125 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
-<html> <head>
-<title>Concurrency Utilities</title>
-</head>
-
-<body>
-
-<p> Utility classes commonly useful in concurrent programming.  This
-package includes a few small standardized extensible frameworks, as
-well as some classes that provide useful functionality and are
-otherwise tedious or difficult to implement.  Here are brief
-descriptions of the main components. See also the <tt>locks</tt> and
-<tt>atomic</tt> packages.
-
-<h2>Executors</h2>
-
-<b>Interfaces.</b> {@link java.util.concurrent.Executor} is a simple
-standardized interface for defining custom thread-like subsystems,
-including thread pools, asynchronous IO, and lightweight task
-frameworks.  Depending on which concrete Executor class is being used,
-tasks may execute in a newly created thread, an existing
-task-execution thread, or the thread calling <tt>execute()</tt>, and
-may execute sequentially or concurrently.  {@link
-java.util.concurrent.ExecutorService} provides a more complete
-asynchronous task execution framework.  An ExecutorService manages
-queuing and scheduling of tasks, and allows controlled shutdown.  The
-{@link java.util.concurrent.ScheduledExecutorService} subinterface
-adds support for delayed and periodic task execution.
-ExecutorServices provide methods arranging asynchronous execution of
-any function expressed as {@link java.util.concurrent.Callable}, the
-result-bearing analog of {@link java.lang.Runnable}.  A {@link
-java.util.concurrent.Future} returns the results of a function, allows
-determination of whether execution has completed, and provides a means to
-cancel execution.
-
-<p>
-
-<b>Implementations.</b> Classes {@link
-java.util.concurrent.ThreadPoolExecutor} and {@link
-java.util.concurrent.ScheduledThreadPoolExecutor} provide tunable,
-flexible thread pools. The {@link java.util.concurrent.Executors}
-class provides factory methods for the most common kinds and
-configurations of Executors, as well as a few utility methods for
-using them. Other utilities based on Executors include the concrete
-class {@link java.util.concurrent.FutureTask} providing a common
-extensible implementation of Futures, and {@link
-java.util.concurrent.ExecutorCompletionService}, that assists in
-coordinating the processing of groups of asynchronous tasks.
-
-<h2>Queues</h2>
-
-The java.util.concurrent {@link
-java.util.concurrent.ConcurrentLinkedQueue} class supplies an
-efficient scalable thread-safe non-blocking FIFO queue.  Five
-implementations in java.util.concurrent support the extended {@link
-java.util.concurrent.BlockingQueue} interface, that defines blocking
-versions of put and take: {@link
-java.util.concurrent.LinkedBlockingQueue}, {@link
-java.util.concurrent.ArrayBlockingQueue}, {@link
-java.util.concurrent.SynchronousQueue}, {@link
-java.util.concurrent.PriorityBlockingQueue}, and {@link
-java.util.concurrent.DelayQueue}. The different classes cover the most
-common usage contexts for producer-consumer, messaging, parallel
-tasking, and related concurrent designs.
-
-
-<h2>Timing</h2>
-
-The {@link java.util.concurrent.TimeUnit} class provides multiple
-granularities (including nanoseconds) for specifying and controlling
-time-out based operations. Most classes in the package contain
-operations based on time-outs in addition to indefinite waits.  In all
-cases that time-outs are used, the time-out specifies the minimum time
-that the method should wait before indicating that it
-timed-out. Implementations make a &quot;best effort&quot; to detect
-time-outs as soon as possible after they occur. However, an indefinite
-amount of time may elapse between a time-out being detected and a
-thread actually executing again after that time-out.
-
-<h2>Synchronizers</h2>
-
-Four classes aid common special-purpose synchronization idioms.
-{@link java.util.concurrent.Semaphore} is a classic concurrency tool.
-{@link java.util.concurrent.CountDownLatch} is a very simple yet very
-common utility for blocking until a given number of signals, events,
-or conditions hold.  A {@link java.util.concurrent.CyclicBarrier} is a
-resettable multiway synchronization point useful in some styles of
-parallel programming. An {@link java.util.concurrent.Exchanger} allows
-two threads to exchange objects at a rendezvous point, and is useful
-in several pipeline designs.
-
-<h2>Concurrent Collections</h2>
-
-Besides Queues, this package supplies a few Collection implementations
-designed for use in multithreaded contexts: {@link
-java.util.concurrent.ConcurrentHashMap}, {@link
-java.util.concurrent.CopyOnWriteArrayList}, and {@link
-java.util.concurrent.CopyOnWriteArraySet}.
-
-<p>The "Concurrent" prefix used with some classes in this package is a
-shorthand indicating several differences from similar "synchronized"
-classes. For example <tt>java.util.Hashtable</tt> and
-<tt>Collections.synchronizedMap(new HashMap())</tt> are
-synchronized. But {@link java.util.concurrent.ConcurrentHashMap} is
-"concurrent".  A concurrent collection is thread-safe, but not
-governed by a single exclusion lock. In the particular case of
-ConcurrentHashMap, it safely permits any number of concurrent reads as
-well as a tunable number of concurrent writes.  "Synchronized" classes
-can be useful when you need to prevent all access to a collection via
-a single lock, at the expense of poorer scalability. In other cases in
-which multiple threads are expected to access a common collection,
-"concurrent" versions are normally preferable. And unsynchronized
-collections are preferable when either collections are unshared, or
-are accessible only when holding other locks.
-
-<p> Most concurrent Collection implementations (including most Queues)
-also differ from the usual java.util conventions in that their Iterators
-provide <em>weakly consistent</em> rather than fast-fail traversal. A
-weakly consistent iterator is thread-safe, but does not necessarily
-freeze the collection while iterating, so it may (or may not) reflect
-any updates since the iterator was created.
-
-@since 1.5
-
-</body> </html>

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AbstractQueuedSynchronizerTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AbstractQueuedSynchronizerTest.java?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AbstractQueuedSynchronizerTest.java (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AbstractQueuedSynchronizerTest.java Thu Jul 16 14:01:15 2009
@@ -461,7 +461,9 @@
 	Thread t = new Thread(new InterruptedSyncRunnable(sync));
         try {
             t.start();
+            Thread.sleep(SHORT_DELAY_MS);
             t.interrupt();
+            Thread.sleep(SHORT_DELAY_MS);
             sync.release(1);
             t.join();
         } catch(Exception e){
@@ -950,7 +952,6 @@
             sync.acquire(1);
             c.signal();
             sync.release(1);
-            assert(t.isInterrupted());
             t.join(SHORT_DELAY_MS);
             assertFalse(t.isAlive());
         }

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ArrayBlockingQueueTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ArrayBlockingQueueTest.java?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ArrayBlockingQueueTest.java (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ArrayBlockingQueueTest.java Thu Jul 16 14:01:15 2009
@@ -650,6 +650,7 @@
         assertEquals(SIZE, q.remainingCapacity());
         q.add(one);
         assertFalse(q.isEmpty());
+        assertTrue(q.contains(one));
         q.clear();
         assertTrue(q.isEmpty());
     }
@@ -970,6 +971,17 @@
         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));
     }
 
     /**
@@ -1028,15 +1040,18 @@
      * 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) {
-            ArrayBlockingQueue q = populatedQueue(SIZE);
+            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(q.size(), SIZE-k);
             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) ;
         }
     }
 

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicIntegerFieldUpdaterTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicIntegerFieldUpdaterTest.java?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicIntegerFieldUpdaterTest.java (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicIntegerFieldUpdaterTest.java Thu Jul 16 14:01:15 2009
@@ -60,6 +60,27 @@
         catch (RuntimeException rt) {}
     }
 
+    static class Base {
+        protected volatile int f = 0;
+    }
+    static class Sub1 extends Base {
+        AtomicIntegerFieldUpdater<Base> fUpdater
+                = AtomicIntegerFieldUpdater.newUpdater(Base.class, "f");
+    }
+    static class Sub2 extends Base {}
+
+    public void testProtectedFieldOnAnotherSubtype() {
+        Sub1 sub1 = new Sub1();
+        Sub2 sub2 = new Sub2();
+
+        sub1.fUpdater.set(sub1, 1);
+        try {
+            sub1.fUpdater.set(sub2, 2);
+            shouldThrow();
+        } 
+        catch (RuntimeException rt) {}
+    }
+
     /**
      *  get returns the last value set or assigned
      */
@@ -78,6 +99,7 @@
 	assertEquals(-3,a.get(this));
 	
     }
+
     /**
      * compareAndSet succeeds in changing value if equal to expected else fails
      */

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicIntegerTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicIntegerTest.java?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicIntegerTest.java (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicIntegerTest.java Thu Jul 16 14:01:15 2009
@@ -46,6 +46,7 @@
 	assertEquals(-3,ai.get());
 	
     }
+
     /**
      * compareAndSet succeeds in changing value if equal to expected else fails
      */

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicLongFieldUpdaterTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicLongFieldUpdaterTest.java?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicLongFieldUpdaterTest.java (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicLongFieldUpdaterTest.java Thu Jul 16 14:01:15 2009
@@ -62,6 +62,27 @@
         catch (RuntimeException rt) {}
     }
 
+    static class Base {
+        protected volatile long f = 0;
+    }
+    static class Sub1 extends Base {
+        AtomicLongFieldUpdater<Base> fUpdater
+                = AtomicLongFieldUpdater.newUpdater(Base.class, "f");
+    }
+    static class Sub2 extends Base {}
+
+    public void testProtectedFieldOnAnotherSubtype() {
+        Sub1 sub1 = new Sub1();
+        Sub2 sub2 = new Sub2();
+
+        sub1.fUpdater.set(sub1, 1);
+        try {
+            sub1.fUpdater.set(sub2, 2);
+            shouldThrow();
+        }
+        catch (RuntimeException rt) {}
+    }
+
     /**
      *  get returns the last value set or assigned
      */
@@ -78,7 +99,7 @@
 	assertEquals(2,a.get(this));
 	a.set(this,-3);
 	assertEquals(-3,a.get(this));
-	
+
     }
     /**
      * compareAndSet succeeds in changing value if equal to expected else fails

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicLongTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicLongTest.java?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicLongTest.java (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicLongTest.java Thu Jul 16 14:01:15 2009
@@ -46,6 +46,7 @@
 	assertEquals(-3,ai.get());
 	
     }
+
     /**
      * compareAndSet succeeds in changing value if equal to expected else fails
      */

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicReferenceFieldUpdaterTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicReferenceFieldUpdaterTest.java?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicReferenceFieldUpdaterTest.java (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicReferenceFieldUpdaterTest.java Thu Jul 16 14:01:15 2009
@@ -62,6 +62,27 @@
         catch (RuntimeException rt) {}
     }
 
+    static class Base {
+        protected volatile Object f = null;
+    }
+    static class Sub1 extends Base {
+        AtomicReferenceFieldUpdater<Base, Object> fUpdater
+                = AtomicReferenceFieldUpdater.newUpdater(Base.class, Object.class, "f");
+    }
+    static class Sub2 extends Base {}
+
+    public void testProtectedFieldOnAnotherSubtype() {
+        Sub1 sub1 = new Sub1();
+        Sub2 sub2 = new Sub2();
+
+        sub1.fUpdater.set(sub1, "f");
+        try {
+            sub1.fUpdater.set(sub2, "g");
+            shouldThrow();
+        }
+        catch (RuntimeException rt) {}
+    }
+
     /**
      *  get returns the last value set or assigned
      */
@@ -76,9 +97,8 @@
 	assertEquals(one,a.get(this));
 	a.set(this,two);
 	assertEquals(two,a.get(this));
-	a.set(this,-3);
-	assertEquals(-3,a.get(this).intValue());
-	
+	a.set(this,m3);
+	assertEquals(m3,a.get(this));
     }
     /**
      * compareAndSet succeeds in changing value if equal to expected else fails

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicReferenceTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicReferenceTest.java?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicReferenceTest.java (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/AtomicReferenceTest.java Thu Jul 16 14:01:15 2009
@@ -44,7 +44,7 @@
 	assertEquals(two,ai.get());
 	ai.set(m3);
 	assertEquals(m3,ai.get());
-	
+
     }
     /**
      * compareAndSet succeeds in changing value if equal to expected else fails

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ConcurrentHashMapTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ConcurrentHashMapTest.java?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ConcurrentHashMapTest.java (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ConcurrentHashMapTest.java Thu Jul 16 14:01:15 2009
@@ -81,8 +81,8 @@
      */
     public void testContainsValue() {
         ConcurrentHashMap map = map5();
-	assertTrue(map.contains("A"));
-        assertFalse(map.contains("Z"));
+	assertTrue(map.containsValue("A"));
+        assertFalse(map.containsValue("Z"));
     }
 
     /**
@@ -150,6 +150,49 @@
     }
 
     /**
+     *  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() {
@@ -501,6 +544,19 @@
     }
 
     /**
+     * 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() {

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/CyclicBarrierTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/CyclicBarrierTest.java?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/CyclicBarrierTest.java (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/CyclicBarrierTest.java Thu Jul 16 14:01:15 2009
@@ -9,6 +9,8 @@
 import junit.framework.*;
 import java.util.*;
 import java.util.concurrent.*;
+import java.util.concurrent.locks.*;
+import java.util.concurrent.atomic.*;
 
 public class CyclicBarrierTest extends JSR166TestCase{
     public static void main(String[] args) {
@@ -162,7 +164,7 @@
      * throw BrokenBarrierException
      */
     public void testAwait2_Interrupted_BrokenBarrier() {
-      final CyclicBarrier c = new CyclicBarrier(3);
+        final CyclicBarrier c = new CyclicBarrier(3);
         Thread t1 = new Thread(new Runnable() {
                 public void run() {
                     try {
@@ -227,7 +229,7 @@
      * throw BrokenBarrierException
      */
     public void testAwait4_Timeout_BrokenBarrier() {
-      final CyclicBarrier c = new CyclicBarrier(3);
+        final CyclicBarrier c = new CyclicBarrier(3);
         Thread t1 = new Thread(new Runnable() {
                 public void run() {
                     try {
@@ -265,7 +267,7 @@
      * throw BrokenBarrierException
      */
     public void testAwait5_Timeout_BrokenBarrier() {
-      final CyclicBarrier c = new CyclicBarrier(3);
+        final CyclicBarrier c = new CyclicBarrier(3);
         Thread t1 = new Thread(new Runnable() {
                 public void run() {
                     try {
@@ -374,4 +376,249 @@
         }
     }
 
+    /**
+     * 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();
+        }
+    }
 }

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/DelayQueueTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/DelayQueueTest.java?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/DelayQueueTest.java (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/DelayQueueTest.java Thu Jul 16 14:01:15 2009
@@ -6,17 +6,13 @@
  * Pat Fisher, Mike Judd. 
  */
 
-/*
- * Modified in Apache Harmony.
- */
-
 import junit.framework.*;
 import java.util.*;
 import java.util.concurrent.*;
 
 public class DelayQueueTest extends JSR166TestCase {
     public static void main(String[] args) {
-	junit.textui.TestRunner.run (suite());	
+	junit.textui.TestRunner.run (suite());
     }
 
     public static Test suite() {
@@ -29,11 +25,11 @@
      * 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 { 
+     */
+    static class PDelay implements Delayed {
         int pseudodelay;
         PDelay(int i) { pseudodelay = Integer.MIN_VALUE + i; }
-        public int compareTo(Delayed y) {
+        public int compareTo(PDelay y) {
             int i = pseudodelay;
             int j = ((PDelay)y).pseudodelay;
             if (i < j) return -1;
@@ -41,7 +37,7 @@
             return 0;
         }
 
-        public int compareTo(PDelay y) {
+        public int compareTo(Delayed y) {
             int i = pseudodelay;
             int j = ((PDelay)y).pseudodelay;
             if (i < j) return -1;
@@ -73,12 +69,12 @@
     /**
      * Delayed implementation that actually delays
      */
-    static class NanoDelay implements Delayed { 
+    static class NanoDelay implements Delayed {
         long trigger;
-        NanoDelay(long i) { 
+        NanoDelay(long i) {
             trigger = System.nanoTime() + i;
         }
-        public int compareTo(Delayed y) {
+        public int compareTo(NanoDelay y) {
             long i = trigger;
             long j = ((NanoDelay)y).trigger;
             if (i < j) return -1;
@@ -86,7 +82,7 @@
             return 0;
         }
 
-        public int compareTo(NanoDelay y) {
+        public int compareTo(Delayed y) {
             long i = trigger;
             long j = ((NanoDelay)y).trigger;
             if (i < j) return -1;
@@ -132,7 +128,7 @@
 	assertEquals(n, q.size());
         return q;
     }
- 
+
     /**
      * A new queue has unbounded capacity
      */
@@ -233,7 +229,7 @@
             DelayQueue q = new DelayQueue();
             q.offer(null);
             shouldThrow();
-        } catch (NullPointerException success) { }   
+        } catch (NullPointerException success) { }
     }
 
     /**
@@ -244,7 +240,7 @@
             DelayQueue q = new DelayQueue();
             q.add(null);
             shouldThrow();
-        } catch (NullPointerException success) { }   
+        } catch (NullPointerException success) { }
     }
 
     /**
@@ -346,9 +342,9 @@
             DelayQueue q = new DelayQueue();
             q.put(null);
             shouldThrow();
-        } 
+        }
         catch (NullPointerException success){
-	}   
+	}
      }
 
     /**
@@ -416,7 +412,7 @@
                     } finally { }
                 }
             });
-        
+
         try {
             t.start();
             Thread.sleep(SMALL_DELAY_MS);
@@ -438,7 +434,7 @@
             }
         } catch (InterruptedException e){
 	    unexpectedException();
-	}   
+	}
     }
 
     /**
@@ -451,7 +447,7 @@
                     try {
                         q.take();
 			threadShouldThrow();
-                    } catch (InterruptedException success){ }                
+                    } catch (InterruptedException success){ }
                 }
             });
         try {
@@ -478,11 +474,11 @@
                         q.take();
                         threadShouldThrow();
                     } catch (InterruptedException success){
-                    }   
+                    }
                 }});
         t.start();
-        try { 
-           Thread.sleep(SHORT_DELAY_MS); 
+        try {
+           Thread.sleep(SHORT_DELAY_MS);
            t.interrupt();
            t.join();
         }
@@ -515,7 +511,7 @@
             assertNull(q.poll(0, TimeUnit.MILLISECONDS));
         } catch (InterruptedException e){
 	    unexpectedException();
-	}   
+	}
     }
 
     /**
@@ -530,7 +526,7 @@
             assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
         } catch (InterruptedException e){
 	    unexpectedException();
-	}   
+	}
     }
 
     /**
@@ -547,11 +543,11 @@
                         }
                         threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
                     } catch (InterruptedException success){
-                    }   
+                    }
                 }});
         t.start();
-        try { 
-           Thread.sleep(SHORT_DELAY_MS); 
+        try {
+           Thread.sleep(SHORT_DELAY_MS);
            t.interrupt();
            t.join();
         }
@@ -573,7 +569,7 @@
                         q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
                         q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
 			threadFail("Should block");
-                    } catch (InterruptedException success) { }                
+                    } catch (InterruptedException success) { }
                 }
             });
         try {
@@ -585,7 +581,7 @@
         } catch (Exception e){
             unexpectedException();
         }
-    }  
+    }
 
 
     /**
@@ -596,8 +592,10 @@
         for (int i = 0; i < SIZE; ++i) {
             assertEquals(new PDelay(i), ((PDelay)q.peek()));
             q.poll();
-            assertTrue(q.peek() == null ||
-                       i != ((PDelay)q.peek()).intValue());
+            if (q.isEmpty())
+                assertNull(q.peek());
+            else
+                assertTrue(i != ((PDelay)q.peek()).intValue());
         }
 	assertNull(q.peek());
     }
@@ -630,7 +628,7 @@
             q.remove();
             shouldThrow();
         } catch (NoSuchElementException success){
-	}   
+	}
     }
 
     /**
@@ -647,7 +645,7 @@
         }
         assertTrue(q.isEmpty());
     }
-	
+
     /**
      * contains(x) reports true when elements added but not yet removed
      */
@@ -669,8 +667,10 @@
         assertTrue(q.isEmpty());
         assertEquals(0, q.size());
         assertEquals(NOCAP, q.remainingCapacity());
-        q.add(new PDelay(1));
+        PDelay x = new PDelay(1);
+        q.add(x);
         assertFalse(q.isEmpty());
+        assertTrue(q.contains(x));
         q.clear();
         assertTrue(q.isEmpty());
     }
@@ -736,7 +736,7 @@
 	    assertEquals(o[i], q.take());
 	} catch (InterruptedException e){
 	    unexpectedException();
-	}    
+	}
     }
 
     /**
@@ -752,7 +752,7 @@
 		assertEquals(ints[i], q.take());
 	} catch (InterruptedException e){
 	    unexpectedException();
-	}    
+	}
     }
 
 
@@ -777,7 +777,7 @@
 	    shouldThrow();
 	} catch(ArrayStoreException  success){}
     }
-    
+
     /**
      * iterator iterates through all elements
      */
@@ -819,7 +819,7 @@
         for (int i = 0; i < SIZE; ++i) {
             assertTrue(s.indexOf(String.valueOf(Integer.MIN_VALUE+i)) >= 0);
         }
-    }        
+    }
 
     /**
      * offer transfers elements across Executor tasks
@@ -875,7 +875,7 @@
                 NanoDelay e = (NanoDelay)(q.take());
                 long tt = e.getTriggerTime();
                 assertTrue(tt <= System.nanoTime());
-                if (i != 0) 
+                if (i != 0)
                     assertTrue(tt >= last);
                 last = tt;
             }
@@ -885,10 +885,41 @@
         }
     }
 
+    /**
+     * 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 {
@@ -900,7 +931,7 @@
 
     /**
      * drainTo(this) throws IAE
-     */ 
+     */
     public void testDrainToSelf() {
         DelayQueue q = populatedQueue(SIZE);
         try {
@@ -912,13 +943,30 @@
 
     /**
      * drainTo(c) empties queue into another collection c
-     */ 
+     */
     public void testDrainTo() {
-        DelayQueue q = populatedQueue(SIZE);
+        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);
-        assertEquals(l.size(), SIZE);
+        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]);
     }
 
     /**

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ExecutorCompletionServiceTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ExecutorCompletionServiceTest.java?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ExecutorCompletionServiceTest.java (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ExecutorCompletionServiceTest.java Thu Jul 16 14:01:15 2009
@@ -10,6 +10,7 @@
 import junit.framework.*;
 import java.util.*;
 import java.util.concurrent.*;
+import java.util.concurrent.atomic.*;
 import java.math.BigInteger;
 import java.security.*;
 
@@ -87,7 +88,7 @@
             Callable c = new StringTask();
             ecs.submit(c);
             Future f = ecs.take();
-            assert(f.isDone());
+            assertTrue(f.isDone());
         } catch (Exception ex) {
             unexpectedException();
         } finally {
@@ -127,7 +128,7 @@
             for (;;) {
                 Future f = ecs.poll();
                 if (f != null) {
-                    assert(f.isDone());
+                    assertTrue(f.isDone());
                     break;
                 }
             }
@@ -150,12 +151,11 @@
             ecs.submit(c);
             Future f = ecs.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
             if (f != null) 
-                assert(f.isDone());
+                assertTrue(f.isDone());
         } catch (Exception ex) {
             unexpectedException();
         } finally {
             joinPool(e);
         }
     }
-
 }

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ExecutorsTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ExecutorsTest.java?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ExecutorsTest.java (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ExecutorsTest.java Thu Jul 16 14:01:15 2009
@@ -337,7 +337,7 @@
 		    try {
 			Thread current = Thread.currentThread();
 			threadAssertTrue(!current.isDaemon());
-			threadAssertTrue(current.getPriority() == Thread.NORM_PRIORITY);
+			threadAssertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
 			ThreadGroup g = current.getThreadGroup();
 			SecurityManager s = System.getSecurityManager();
 			if (s != null)
@@ -392,7 +392,7 @@
 		    try {
 			Thread current = Thread.currentThread();
 			threadAssertTrue(!current.isDaemon());
-			threadAssertTrue(current.getPriority() == Thread.NORM_PRIORITY);
+			threadAssertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
 			ThreadGroup g = current.getThreadGroup();
 			SecurityManager s = System.getSecurityManager();
 			if (s != null)

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/JSR166TestCase.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/JSR166TestCase.java?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/JSR166TestCase.java (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/JSR166TestCase.java Thu Jul 16 14:01:15 2009
@@ -2,8 +2,8 @@
  * 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. 
+ * Other contributors include Andrew Wright, Jeffrey Hayes,
+ * Pat Fisher, Mike Judd.
  */
 
 import junit.framework.*;
@@ -17,13 +17,13 @@
  * 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 doe not otherwise arrange).  The rules for creating such
+ * JUnit does not otherwise arrange).  The rules for creating such
  * tests are:
  *
  * <ol>
  *
  * <li> All assertions in code running in generated threads must use
- * the forms {@link #threadFail} , {@link #threadAssertTrue} {@link
+ * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
  * #threadAssertEquals}, or {@link #threadAssertNull}, (not
  * <tt>fail</tt>, <tt>assertTrue</tt>, etc.) It is OK (but not
  * particularly recommended) for other code to use these forms too.
@@ -44,7 +44,7 @@
  * 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</li>
+ * in one spot to rerun tests on slower platforms.</li>
  *
  * <li> All threads generated must be joined inside each test case
  * method (or <tt>fail</tt> to do so) before returning from the
@@ -63,7 +63,7 @@
  * "normal" behaviors differ significantly. And sometimes testcases
  * cover multiple methods when they cannot be tested in
  * isolation.</li>
- * 
+ *
  * <li> 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
@@ -88,10 +88,10 @@
 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) 
+        if (args.length > 0)
             iters = Integer.parseInt(args[0]);
         Test s = suite();
         for (int i = 0; i < iters; ++i) {
@@ -104,26 +104,26 @@
 
     /**
      * 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(AbstractQueueTest.class));
         suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
         suite.addTest(new TestSuite(ArrayBlockingQueueTest.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(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(CopyOnWriteArrayListTest.class));
@@ -150,7 +150,7 @@
         suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
         suite.addTest(new TestSuite(ThreadTest.class));
         suite.addTest(new TestSuite(TimeUnitTest.class));
-		
+
         return suite;
     }
 
@@ -162,16 +162,16 @@
 
 
     /**
-     * Return the shortest timed delay. This could
+     * Returns the shortest timed delay. This could
      * be reimplemented to use for example a Property.
-     */ 
+     */
     protected long getShortDelay() {
         return 50;
     }
 
 
     /**
-     * Set delays as multiples of SHORT_DELAY.
+     * Sets delays as multiples of SHORT_DELAY.
      */
     protected  void setDelays() {
         SHORT_DELAY_MS = getShortDelay();
@@ -186,23 +186,23 @@
     volatile boolean threadFailed;
 
     /**
-     * Initialize test to indicate that no thread assertions have failed
+     * Initializes test to indicate that no thread assertions have failed
      */
-    public void setUp() { 
+    public void setUp() {
         setDelays();
-        threadFailed = false;  
+        threadFailed = false;
     }
 
     /**
-     * Trigger test case failure if any thread assertions have failed
+     * Triggers test case failure if any thread assertions have failed
      */
-    public void tearDown() { 
-        assertFalse(threadFailed);  
+    public void tearDown() {
+        assertFalse(threadFailed);
     }
 
     /**
      * Fail, also setting status to indicate current testcase should fail
-     */ 
+     */
     public void threadFail(String reason) {
         threadFailed = true;
         fail(reason);
@@ -211,7 +211,7 @@
     /**
      * If expression not true, set status to indicate current testcase
      * should fail
-     */ 
+     */
     public void threadAssertTrue(boolean b) {
         if (!b) {
             threadFailed = true;
@@ -222,7 +222,7 @@
     /**
      * If expression not false, set status to indicate current testcase
      * should fail
-     */ 
+     */
     public void threadAssertFalse(boolean b) {
         if (b) {
             threadFailed = true;
@@ -233,7 +233,7 @@
     /**
      * If argument not null, set status to indicate current testcase
      * should fail
-     */ 
+     */
     public void threadAssertNull(Object x) {
         if (x != null) {
             threadFailed = true;
@@ -244,7 +244,7 @@
     /**
      * If arguments not equal, set status to indicate current testcase
      * should fail
-     */ 
+     */
     public void threadAssertEquals(long x, long y) {
         if (x != y) {
             threadFailed = true;
@@ -255,7 +255,7 @@
     /**
      * 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;
@@ -267,8 +267,13 @@
      * threadFail with message "should throw exception"
      */ 
     public void threadShouldThrow() {
-        threadFailed = true;
-        fail("should throw exception");
+       try {
+           threadFailed = true;
+           fail("should throw exception");
+       } catch (AssertionFailedError e) {
+           e.printStackTrace();
+           throw e;
+       }
     }
 
     /**
@@ -279,6 +284,14 @@
         fail("Unexpected exception");
     }
 
+    /**
+     * threadFail with message "Unexpected exception", with argument
+     */
+    public void threadUnexpectedException(Throwable ex) {
+        threadFailed = true;
+        ex.printStackTrace();
+        fail("Unexpected exception: " + ex);
+    }
 
     /**
      * Wait out termination of a thread pool or fail doing so
@@ -297,7 +310,7 @@
 
     /**
      * fail with message "should throw exception"
-     */ 
+     */
     public void shouldThrow() {
         fail("Should throw exception");
     }
@@ -332,6 +345,7 @@
     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);
 
 
@@ -387,7 +401,7 @@
                 Thread.sleep(SHORT_DELAY_MS);
             }
             catch(Exception e) {
-                threadUnexpectedException();
+                threadUnexpectedException(e);
             }
         }
     }
@@ -409,7 +423,7 @@
                 Thread.sleep(SMALL_DELAY_MS);
             }
             catch(Exception e) {
-                threadUnexpectedException();
+                threadUnexpectedException(e);
             }
         }
     }
@@ -430,7 +444,7 @@
                 Thread.sleep(SMALL_DELAY_MS);
             }
             catch(Exception e) {
-                threadUnexpectedException();
+                threadUnexpectedException(e);
             }
             return Boolean.TRUE;
         }
@@ -454,7 +468,7 @@
                 Thread.sleep(MEDIUM_DELAY_MS);
             }
             catch(Exception e) {
-                threadUnexpectedException();
+                threadUnexpectedException(e);
             }
         }
     }
@@ -496,7 +510,7 @@
     static class SimpleThreadFactory implements ThreadFactory{
         public Thread newThread(Runnable r){
             return new Thread(r);
-        }   
+        }
     }
 
     static class TrackedShortRunnable implements Runnable {
@@ -556,8 +570,8 @@
      * For use as RejectedExecutionHandler in constructors
      */
     static class NoOpREHandler implements RejectedExecutionHandler{
-        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor){} 
+        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor){}
     }
- 
-    
+
+
 }

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/LinkedBlockingQueueTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/LinkedBlockingQueueTest.java?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/LinkedBlockingQueueTest.java (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/LinkedBlockingQueueTest.java Thu Jul 16 14:01:15 2009
@@ -614,6 +614,23 @@
         }
         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
@@ -638,6 +655,7 @@
         assertEquals(SIZE, q.remainingCapacity());
         q.add(one);
         assertFalse(q.isEmpty());
+        assertTrue(q.contains(one));
         q.clear();
         assertTrue(q.isEmpty());
     }
@@ -956,6 +974,17 @@
         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));
     }
 
     /**
@@ -1014,15 +1043,18 @@
      * 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) {
-            LinkedBlockingQueue q = populatedQueue(SIZE);
+            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(q.size(), SIZE-k);
             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) ;
         }
     }
 

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/LockSupportTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/LockSupportTest.java?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/LockSupportTest.java (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/LockSupportTest.java Thu Jul 16 14:01:15 2009
@@ -75,7 +75,6 @@
 		public void run() {
 		    try {
 			LockSupport.park();
-                        threadAssertTrue(Thread.interrupted());
 		    } catch(Exception e){
                         threadUnexpectedException();
                     }

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/PriorityBlockingQueueTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/PriorityBlockingQueueTest.java?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/PriorityBlockingQueueTest.java (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/PriorityBlockingQueueTest.java Thu Jul 16 14:01:15 2009
@@ -626,9 +626,9 @@
         q.clear();
         assertTrue(q.isEmpty());
         assertEquals(0, q.size());
-        assertEquals(NOCAP, q.remainingCapacity());
-        q.add(new Integer(1));
+        q.add(one);
         assertFalse(q.isEmpty());
+        assertTrue(q.contains(one));
         q.clear();
         assertTrue(q.isEmpty());
     }
@@ -871,6 +871,17 @@
         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));
     }
 
     /**
@@ -925,15 +936,18 @@
      * 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) {
-            PriorityBlockingQueue q = populatedQueue(SIZE);
+            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(q.size(), SIZE-k);
             assertEquals(l.size(), k);
+            assertEquals(q.size(), SIZE-k);
             for (int j = 0; j < k; ++j) 
-                assertTrue(l.contains(new Integer(j)));
+                assertEquals(l.get(j), new Integer(j));
+            while (q.poll() != null) ;
         }
     }
 

Modified: harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ReentrantLockTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ReentrantLockTest.java?rev=794678&r1=794677&r2=794678&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ReentrantLockTest.java (original)
+++ harmony/enhanced/classlib/trunk/modules/concurrent/src/test/java/ReentrantLockTest.java Thu Jul 16 14:01:15 2009
@@ -409,7 +409,9 @@
 	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){
@@ -498,7 +500,7 @@
         final Condition c = lock.newCondition();
         try {
             lock.lock();
-            assertFalse(c.await(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
+            c.await(SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
             lock.unlock();
         }
         catch (Exception ex) {
@@ -515,7 +517,7 @@
         try {
             lock.lock();
             java.util.Date d = new java.util.Date();
-            assertFalse(c.awaitUntil(new java.util.Date(d.getTime() + 10)));
+            c.awaitUntil(new java.util.Date(d.getTime() + 10));
             lock.unlock();
         }
         catch (Exception ex) {
@@ -863,34 +865,61 @@
         }
     }
 
-
+    /** 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 ReentrantLock lock = new ReentrantLock();
         final Condition c = lock.newCondition();
-	Thread t = new Thread(new Runnable() { 
-		public void run() {
-                    lock.lock();
-                    c.awaitUninterruptibly();
-                    lock.unlock();
-		}
-	    });
+        UninterruptableThread thread = new UninterruptableThread(lock, c);
 
         try {
-            t.start();
-            Thread.sleep(SHORT_DELAY_MS);
-            t.interrupt();
+            thread.start();
+
+            while (!thread.lockStarted) {
+                Thread.sleep(100);
+            }
+
             lock.lock();
-            c.signal();
-            lock.unlock();
-            assert(t.isInterrupted());
-            t.join(SHORT_DELAY_MS);
-            assertFalse(t.isAlive());
-        }
-        catch (Exception ex) {
+            try {
+                thread.interrupt();
+                thread.canAwake = true;
+                c.signal();
+            } finally {
+                lock.unlock();
+            }
+
+            thread.join();
+            assertTrue(thread.interrupted);
+            assertFalse(thread.isAlive());
+        } catch (Exception ex) {
             unexpectedException();
         }
     }
@@ -1039,6 +1068,61 @@
     }
 
     /**
+     * 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() {



Mime
View raw message