* configure.ac: New switch for disabling -O2 (--disable-optimizations).
[cacao.git] / tests / weakref.java
1 import java.lang.ref.*;
2 import java.util.HashSet;
3
4 class weakref {
5         class OtherThread extends Thread {
6                 public volatile boolean quitNow = false;
7                 private final ReferenceQueue q;
8                 private final HashSet h;
9                 public OtherThread(ReferenceQueue q, HashSet h) {
10                         this.q = q;
11                         this.h = h;
12                 }
13                 public void run() {
14                         while (!quitNow) {
15                                 try {
16                                         MyRef r = (MyRef) q.remove();
17                                         h.remove(r);
18                                         System.out.println("Integer: " + Integer.toString(r.val));
19                                 } catch (InterruptedException e) {
20                                 }
21                         }
22                 }
23         }
24
25         class MyRef extends WeakReference {
26                 public final int val;
27                 MyRef(Object o, ReferenceQueue q, int val) {
28                         super(o, q);
29                         this.val = val;
30                 }
31         }
32
33         private void test() {
34                 System.out.println("This should print a long list of Integers if weak references are working.");
35                 ReferenceQueue q = new ReferenceQueue();
36                 HashSet h = new HashSet();
37                 OtherThread t = new OtherThread(q, h);
38                 t.start();
39                 for (int i=0; i<1000000; i++) {
40                         Object o = new Integer(i);
41                         Reference r = new MyRef(o, q, i);
42                         h.add(r);
43                 }
44                 Runtime.getRuntime().gc();
45                 try {
46                         Thread.sleep(1000);
47                         t.quitNow = true;
48                         t.interrupt();
49                         t.join();
50                 } catch (InterruptedException e) {
51                 }
52         }
53
54         public static void main(String[] args) {
55                 new weakref().test();
56         }
57 }
58
59 /*
60  * These are local overrides for various environment variables in Emacs.
61  * Please do not remove this and leave it at the end of the file, where
62  * Emacs will automagically detect them.
63  * ---------------------------------------------------------------------
64  * Local variables:
65  * mode: java
66  * indent-tabs-mode: t
67  * c-basic-offset: 4
68  * tab-width: 4
69  * End:
70  * vim:noexpandtab:sw=4:ts=4:
71  */