1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 import java.lang.ref.WeakReference;
18 
19 public class Main {
20     static final int numWeakReferences = 16 * 1024;
21     static WeakReference[] weakReferences = new WeakReference[numWeakReferences];
22     static volatile boolean done = false;
23     static Object keepAlive;
24 
main(String[] args)25     public static void main(String[] args) throws Exception {
26         // Try to call Reference.get repeatedly while the GC is running.
27         Thread gcThread = new GcThread();
28         Thread[] readerThread = new ReaderThread[4];
29         for (int i = 0; i < readerThread.length; ++i) {
30             readerThread[i] = new ReaderThread();
31         }
32         gcThread.start();
33         for (int i = 0; i < readerThread.length; ++i) {
34             readerThread[i].start();
35         }
36         gcThread.join();
37         for (int i = 0; i < readerThread.length; ++i) {
38             readerThread[i].join();
39         }
40         System.out.println("PASS");
41     }
42 
43     static class GcThread extends Thread {
GcThread()44         GcThread() {
45             Object temp = new Object();
46             for (int j = 0; j < weakReferences.length; ++j) {
47                 weakReferences[j] = new WeakReference(temp);
48             }
49         }
run()50         public void run() {
51             for (int i = 0; i < 1000; ++i) {
52                 Object o = new Object();
53                 for (int j = 0; j < weakReferences.length; ++j) {
54                     weakReferences[j] = new WeakReference(o);
55                 }
56             }
57             done = true;
58         }
59     }
60 
61     static class ReaderThread extends Thread {
run()62         public void run() {
63             while (!done) {
64                 for (int j = 0; j < weakReferences.length; ++j) {
65                     keepAlive = weakReferences[j].get();
66                 }
67                 for (int j = 0; j < weakReferences.length; ++j) {
68                     weakReferences[j].clear();
69                 }
70             }
71         }
72     }
73 }
74