Use nanoTime rather than currentTimeMillis in ReferenceQueue.remove()

Some other side effects of this change:
 - we no longer make a time lookup when we don't need to
 - we time out after 'n' milliseconds, not 'n+1' milliseconds
 - we duplicate code from Thread.join(). I opened http://b/5053948 to dedup this.

Bug: http://b/5050245
Change-Id: I20375119cfa06be559b6aa5c209375b3d3a541f9
diff --git a/luni/src/main/java/java/lang/ref/ReferenceQueue.java b/luni/src/main/java/java/lang/ref/ReferenceQueue.java
index 494cc97..6c9b4d5 100644
--- a/luni/src/main/java/java/lang/ref/ReferenceQueue.java
+++ b/luni/src/main/java/java/lang/ref/ReferenceQueue.java
@@ -25,6 +25,7 @@
  * @since 1.2
  */
 public class ReferenceQueue<T> {
+    private static final int NANOS_PER_MILLI = 1000000;
 
     private Reference<? extends T> head;
 
@@ -66,10 +67,7 @@
      * Returns the next available reference from the queue, removing it in the
      * process. Waits indefinitely for a reference to become available.
      *
-     * @return the next available reference
-     *
-     * @throws InterruptedException
-     *             if the blocking call was interrupted for some reason
+     * @throws InterruptedException if the blocking call was interrupted
      */
     public Reference<? extends T> remove() throws InterruptedException {
         return remove(0L);
@@ -80,36 +78,51 @@
      * process. Waits for a reference to become available or the given timeout
      * period to elapse, whichever happens first.
      *
-     * @param timeout
-     *            maximum time (in ms) to spend waiting for a reference object
-     *            to become available. A value of zero results in the method
-     *            waiting indefinitely.
+     * @param timeoutMillis maximum time to spend waiting for a reference object
+     *     to become available. A value of {@code 0} results in the method
+     *     waiting indefinitely.
      * @return the next available reference, or {@code null} if no reference
-     *         becomes available within the timeout period
-     * @throws IllegalArgumentException
-     *             if the wait period is negative.
-     * @throws InterruptedException
-     *             if the blocking call was interrupted for some reason
+     *     becomes available within the timeout period
+     * @throws IllegalArgumentException if {@code timeoutMillis < 0}.
+     * @throws InterruptedException if the blocking call was interrupted
      */
-    public synchronized Reference<? extends T> remove(long timeout) throws IllegalArgumentException,
-            InterruptedException {
-        if (timeout < 0) {
-            throw new IllegalArgumentException();
+    public synchronized Reference<? extends T> remove(long timeoutMillis)
+            throws InterruptedException {
+        if (timeoutMillis < 0) {
+            throw new IllegalArgumentException("timeout < 0: " + timeoutMillis);
         }
 
-        if (timeout == 0L) {
-            while (head == null) {
-                wait(0L);
-            }
-        } else {
-            long now = System.currentTimeMillis();
-            long wakeupTime = now + timeout + 1L;
-            while (head == null && now < wakeupTime) {
-                wait(wakeupTime - now);
-                now = System.currentTimeMillis();
-            }
+        if (head != null) {
+            return poll();
         }
 
+        // avoid overflow: if total > 292 years, just wait forever
+        if (timeoutMillis == 0 || (timeoutMillis > Long.MAX_VALUE / NANOS_PER_MILLI)) {
+            do {
+                wait(0);
+            } while (head == null);
+            return poll();
+        }
+
+        // guaranteed to not overflow
+        long nanosToWait = timeoutMillis * NANOS_PER_MILLI;
+        int timeoutNanos = 0;
+
+        // wait until notified or the timeout has elapsed
+        long startTime = System.nanoTime();
+        while (true) {
+            wait(timeoutMillis, timeoutNanos);
+            if (head != null) {
+                break;
+            }
+            long nanosElapsed = System.nanoTime() - startTime;
+            long nanosRemaining = nanosToWait - nanosElapsed;
+            if (nanosRemaining <= 0) {
+                break;
+            }
+            timeoutMillis = nanosRemaining / NANOS_PER_MILLI;
+            timeoutNanos = (int) (nanosRemaining - timeoutMillis * NANOS_PER_MILLI);
+        }
         return poll();
     }
 
diff --git a/luni/src/test/java/libcore/java/lang/ref/ReferenceQueueTest.java b/luni/src/test/java/libcore/java/lang/ref/ReferenceQueueTest.java
new file mode 100644
index 0000000..69e1a1f
--- /dev/null
+++ b/luni/src/test/java/libcore/java/lang/ref/ReferenceQueueTest.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package libcore.java.lang.ref;
+
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.WeakReference;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import junit.framework.TestCase;
+
+public final class ReferenceQueueTest extends TestCase {
+
+    public void testRemoveWithInvalidTimeout() throws Exception {
+        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<Object>();
+        try {
+            referenceQueue.remove(-1);
+            fail();
+        } catch (IllegalArgumentException expected) {
+        }
+    }
+
+    public void testRemoveWithVeryLargeTimeout() throws Exception {
+        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<Object>();
+        enqueueLater(referenceQueue, 500);
+        referenceQueue.remove(Long.MAX_VALUE);
+    }
+
+    public void testRemoveWithSpuriousNotify() throws Exception {
+        final ReferenceQueue<Object> referenceQueue = new ReferenceQueue<Object>();
+
+        runLater(new Runnable() {
+            @Override public void run() {
+                synchronized (referenceQueue) {
+                    referenceQueue.notifyAll();
+                }
+            }
+        }, 500);
+
+        long startNanos = System.nanoTime();
+        referenceQueue.remove(1000);
+        long durationNanos = System.nanoTime() - startNanos;
+        long durationMillis = TimeUnit.NANOSECONDS.toMillis(durationNanos);
+        assertTrue(durationMillis > 750 && durationMillis < 1250);
+    }
+
+    public void testRemoveWithImmediateResultAndNoTimeout() throws Exception {
+        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<Object>();
+        enqueue(referenceQueue);
+        assertNotNull(referenceQueue.remove());
+    }
+
+    public void testRemoveWithImmediateResultAndTimeout() throws Exception {
+        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<Object>();
+        enqueue(referenceQueue);
+        assertNotNull(referenceQueue.remove(1000));
+    }
+
+    public void testRemoveWithDelayedResultAndNoTimeout() throws Exception {
+        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<Object>();
+        enqueueLater(referenceQueue, 500);
+        long startNanos = System.nanoTime();
+        referenceQueue.remove();
+        long durationNanos = System.nanoTime() - startNanos;
+        long durationMillis = TimeUnit.NANOSECONDS.toMillis(durationNanos);
+        assertTrue(durationMillis > 250 && durationMillis < 750);
+    }
+
+    public void testRemoveWithDelayedResultAndTimeout() throws Exception {
+        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<Object>();
+        enqueueLater(referenceQueue, 500);
+        long startNanos = System.nanoTime();
+        referenceQueue.remove(1000);
+        long durationNanos = System.nanoTime() - startNanos;
+        long durationMillis = TimeUnit.NANOSECONDS.toMillis(durationNanos);
+        assertTrue(durationMillis > 250 && durationMillis < 750);
+    }
+
+    private void runLater(Runnable runnable, int delayMillis) {
+        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
+        executor.schedule(runnable, delayMillis, TimeUnit.MILLISECONDS);
+        executor.shutdown();
+    }
+
+    private void enqueueLater(final ReferenceQueue<Object> queue, int delayMillis) {
+        runLater(new Runnable() {
+            @Override public void run() {
+                enqueue(queue);
+            }
+        }, delayMillis);
+    }
+
+    private void enqueue(ReferenceQueue<Object> queue) {
+        new WeakReference<Object>(new Object(), queue).enqueue();
+    }
+}