|
1 | 1 | /*
|
2 |
| - * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. |
| 2 | + * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved. |
3 | 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
4 | 4 | *
|
5 | 5 | * This code is free software; you can redistribute it and/or modify it
|
|
22 | 22 | */
|
23 | 23 |
|
24 | 24 | /* @test
|
25 |
| - * @bug 4268317 |
| 25 | + * @bug 4268317 8175797 |
26 | 26 | * @summary Test if Reference.enqueue() works properly with GC
|
| 27 | + * @run main ReferenceEnqueue |
27 | 28 | */
|
28 | 29 |
|
29 | 30 | import java.lang.ref.*;
|
| 31 | +import java.util.ArrayList; |
| 32 | +import java.util.List; |
30 | 33 |
|
31 | 34 | public class ReferenceEnqueue {
|
32 | 35 |
|
33 | 36 | public static void main(String args[]) throws Exception {
|
34 |
| - for (int i=0; i < 5; i++) |
| 37 | + for (int i=0; i < 5; i++) { |
35 | 38 | new WeakRef().run();
|
| 39 | + new ExplicitEnqueue().run(); |
| 40 | + } |
36 | 41 | System.out.println("Test passed.");
|
37 | 42 | }
|
38 | 43 |
|
@@ -76,4 +81,45 @@ void run() throws InterruptedException {
|
76 | 81 | }
|
77 | 82 | }
|
78 | 83 | }
|
| 84 | + |
| 85 | + static class ExplicitEnqueue { |
| 86 | + final ReferenceQueue<Object> queue = new ReferenceQueue<>(); |
| 87 | + final List<Reference<Object>> refs = new ArrayList<>(); |
| 88 | + final int iterations = 1000; |
| 89 | + |
| 90 | + ExplicitEnqueue() { |
| 91 | + this.refs.add(new SoftReference<>(new Object(), queue)); |
| 92 | + this.refs.add(new WeakReference<>(new Object(), queue)); |
| 93 | + // Can't test PhantomReference because get() always returns null. |
| 94 | + } |
| 95 | + |
| 96 | + void run() throws InterruptedException { |
| 97 | + for (Reference<Object> ref : refs) { |
| 98 | + if (ref.enqueue() == false) { |
| 99 | + throw new RuntimeException("Error: enqueue failed"); |
| 100 | + } |
| 101 | + if (ref.get() != null) { |
| 102 | + throw new RuntimeException("Error: referent must be cleared"); |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + System.gc(); |
| 107 | + for (int i = 0; refs.size() > 0 && i < iterations; i++) { |
| 108 | + Reference<Object> ref = (Reference<Object>)queue.poll(); |
| 109 | + if (ref == null) { |
| 110 | + System.gc(); |
| 111 | + Thread.sleep(100); |
| 112 | + continue; |
| 113 | + } |
| 114 | + |
| 115 | + if (refs.remove(ref) == false) { |
| 116 | + throw new RuntimeException("Error: unknown reference " + ref); |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + if (!refs.isEmpty()) { |
| 121 | + throw new RuntimeException("Error: not all references are removed"); |
| 122 | + } |
| 123 | + } |
| 124 | + } |
79 | 125 | }
|
0 commit comments