1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.
   7  *
   8  * This code is distributed in the hope that it will be useful, but WITHOUT
   9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  11  * version 2 for more details (a copy is included in the LICENSE file that
  12  * accompanied this code).
  13  *
  14  * You should have received a copy of the GNU General Public License version
  15  * 2 along with this work; if not, write to the Free Software Foundation,
  16  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  17  *
  18  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  19  * or visit www.oracle.com if you need additional information or have any
  20  * questions.
  21  */
  22 
  23 /*
  24  * This file is available under and governed by the GNU General Public
  25  * License version 2 only, as published by the Free Software Foundation.
  26  * However, the following notice accompanied the original version of this
  27  * file:
  28  *
  29  * Written by Doug Lea and Martin Buchholz with assistance from members of
  30  * JCP JSR-166 Expert Group and released to the public domain, as explained
  31  * at http://creativecommons.org/publicdomain/zero/1.0/
  32  */
  33 
  34 /*
  35  * @test
  36  * @summary Ensure that waiting pool threads don't retain refs to tasks.
  37  */
  38 
  39 import java.lang.ref.ReferenceQueue;
  40 import java.lang.ref.WeakReference;
  41 import java.util.ArrayList;
  42 import java.util.List;
  43 import java.util.concurrent.Delayed;
  44 import java.util.concurrent.ExecutionException;
  45 import java.util.concurrent.Future;
  46 import java.util.concurrent.RunnableScheduledFuture;
  47 import java.util.concurrent.ScheduledThreadPoolExecutor;
  48 import java.util.concurrent.TimeUnit;
  49 import java.util.concurrent.TimeoutException;
  50 
  51 public class GCRetention {
  52 
  53     /**
  54      * A custom thread pool with a custom RunnableScheduledFuture, for the
  55      * sole purpose of ensuring that the task retains a strong reference to
  56      * the Runnable even after cancellation.
  57      */
  58     static class CustomPool extends ScheduledThreadPoolExecutor {
  59         CustomPool(int n) { super(n); }
  60         protected <V> RunnableScheduledFuture<V> decorateTask(
  61             final Runnable r,
  62             final RunnableScheduledFuture<V> task) {
  63             return new RunnableScheduledFuture<V>() {
  64                 public void run() { System.err.println(r); task.run(); }
  65                 public boolean isPeriodic() { return task.isPeriodic(); }
  66                 public V get()
  67                     throws InterruptedException,ExecutionException
  68                     { return task.get(); }
  69                 public V get(long x, TimeUnit y)
  70                     throws InterruptedException,ExecutionException,TimeoutException
  71                     { return task.get(x, y); }
  72                 public boolean isDone() { return task.isDone(); }
  73                 public boolean isCancelled() { return task.isCancelled(); }
  74                 public boolean cancel(boolean x) { return task.cancel(x); }
  75                 public long getDelay(TimeUnit x) { return task.getDelay(x); }
  76                 public int compareTo(Delayed x) { return task.compareTo(x); }
  77             };
  78         }
  79     }
  80 
  81     void removeAll(ReferenceQueue<?> q, int n) throws InterruptedException {
  82         for (int j = n; j--> 0; ) {
  83             if (q.poll() == null) {
  84                 for (;;) {
  85                     System.gc();
  86                     if (q.remove(1000) != null)
  87                         break;
  88                     System.out.printf(
  89                         "%d/%d unqueued references remaining%n", j + 1, n);
  90                 }
  91             }
  92         }
  93         check(q.poll() == null);
  94     }
  95 
  96     void test(String[] args) throws Throwable {
  97         final CustomPool pool = new CustomPool(10);
  98         final int size = 100;
  99         final ReferenceQueue<Object> q = new ReferenceQueue<>();
 100         final List<WeakReference<?>> refs = new ArrayList<>(size);
 101         final List<Future<?>> futures = new ArrayList<>(size);
 102 
 103         // Schedule custom tasks with strong references.
 104         class Task implements Runnable {
 105             final Object x;
 106             Task() { refs.add(new WeakReference<>(x = new Object(), q)); }
 107             public void run() { System.out.println(x); }
 108         }
 109         // Give tasks added later earlier expiration, to ensure
 110         // multiple residents of queue head.
 111         for (int i = size; i--> 0; )
 112             futures.add(pool.schedule(new Task(), i + 1, TimeUnit.MINUTES));
 113         futures.forEach(future -> future.cancel(false));
 114         futures.clear();
 115 
 116         pool.purge();
 117         removeAll(q, size);
 118         for (WeakReference<?> ref : refs) check(ref.get() == null);
 119 
 120         pool.shutdown();
 121         // rely on test harness to handle timeout
 122         pool.awaitTermination(1L, TimeUnit.DAYS);
 123     }
 124 
 125     //--------------------- Infrastructure ---------------------------
 126     volatile int passed = 0, failed = 0;
 127     void pass() {passed++;}
 128     void fail() {failed++; Thread.dumpStack();}
 129     void fail(String msg) {System.err.println(msg); fail();}
 130     void unexpected(Throwable t) {failed++; t.printStackTrace();}
 131     void check(boolean cond) {if (cond) pass(); else fail();}
 132     void equal(Object x, Object y) {
 133         if (x == null ? y == null : x.equals(y)) pass();
 134         else fail(x + " not equal to " + y);}
 135     public static void main(String[] args) throws Throwable {
 136         new GCRetention().instanceMain(args);}
 137     void instanceMain(String[] args) throws Throwable {
 138         try {test(args);} catch (Throwable t) {unexpected(t);}
 139         System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
 140         if (failed > 0) throw new AssertionError("Some tests failed");}
 141 }