32 * @key randomness |
32 * @key randomness |
33 */ |
33 */ |
34 |
34 |
35 import jdk.test.lib.RandomFactory; |
35 import jdk.test.lib.RandomFactory; |
36 |
36 |
|
37 import java.lang.ref.ReferenceQueue; |
37 import java.lang.ref.WeakReference; |
38 import java.lang.ref.WeakReference; |
38 import java.util.Arrays; |
39 import java.util.Arrays; |
39 import java.util.Iterator; |
40 import java.util.Iterator; |
40 import java.util.Map; |
41 import java.util.Map; |
41 import java.util.NoSuchElementException; |
42 import java.util.NoSuchElementException; |
42 import java.util.Random; |
43 import java.util.Random; |
43 import java.util.WeakHashMap; |
44 import java.util.WeakHashMap; |
44 import java.util.concurrent.CountDownLatch; |
45 import java.util.concurrent.CountDownLatch; |
45 import java.util.function.BooleanSupplier; |
46 import java.util.function.BooleanSupplier; |
46 |
47 |
47 import static java.util.concurrent.TimeUnit.SECONDS; |
48 import static java.util.concurrent.TimeUnit.MILLISECONDS; |
48 |
49 |
49 public class GCDuringIteration { |
50 public class GCDuringIteration { |
50 |
51 |
51 /** No guarantees, but effective in practice. */ |
52 /** No guarantees, but effective in practice. */ |
52 static void forceFullGc() { |
53 static void forceFullGc() { |
53 CountDownLatch finalizeDone = new CountDownLatch(1); |
54 long timeoutMillis = 1000L; |
54 WeakReference<?> ref = new WeakReference<Object>(new Object() { |
55 CountDownLatch finalized = new CountDownLatch(1); |
55 protected void finalize() { finalizeDone.countDown(); }}); |
56 ReferenceQueue<Object> queue = new ReferenceQueue<>(); |
|
57 WeakReference<Object> ref = new WeakReference<>( |
|
58 new Object() { protected void finalize() { finalized.countDown(); }}, |
|
59 queue); |
56 try { |
60 try { |
57 for (int i = 0; i < 10; i++) { |
61 for (int tries = 3; tries--> 0; ) { |
58 System.gc(); |
62 System.gc(); |
59 if (finalizeDone.await(1L, SECONDS) && ref.get() == null) { |
63 if (finalized.await(timeoutMillis, MILLISECONDS) |
|
64 && queue.remove(timeoutMillis) != null |
|
65 && ref.get() == null) { |
60 System.runFinalization(); // try to pick up stragglers |
66 System.runFinalization(); // try to pick up stragglers |
61 return; |
67 return; |
62 } |
68 } |
|
69 timeoutMillis *= 4; |
63 } |
70 } |
64 } catch (InterruptedException unexpected) { |
71 } catch (InterruptedException unexpected) { |
65 throw new AssertionError("unexpected InterruptedException"); |
72 throw new AssertionError("unexpected InterruptedException"); |
66 } |
73 } |
67 throw new AssertionError("failed to do a \"full\" gc"); |
74 throw new AssertionError("failed to do a \"full\" gc"); |