01: package abbot.util;
02:
03: import java.awt.*;
04: import java.awt.event.*;
05: import javax.swing.*;
06: import java.util.*;
07: import java.util.List;
08:
09: import abbot.Log;
10: import junit.extensions.abbot.*;
11:
12: public class WeakAWTEventListenerTest extends ComponentTestFixture {
13:
14: private class Listener implements AWTEventListener {
15: public List events = new ArrayList();
16: public List contexts = new ArrayList();
17:
18: public void eventDispatched(AWTEvent e) {
19: events.add(e);
20: class Context extends RuntimeException {
21: }
22: contexts.add(new Context());
23: }
24: }
25:
26: public void testAddAndRemove() {
27: ArrayList list = new ArrayList();
28: Toolkit toolkit = Toolkit.getDefaultToolkit();
29: int SIZE = 1000;
30: Listener l1 = new Listener();
31: toolkit.addAWTEventListener(l1, -1);
32:
33: for (int i = 0; i < SIZE; i++) {
34: Listener listener = new Listener();
35: list.add(listener);
36: new WeakAWTEventListener(listener, -1);
37: }
38: Listener l2 = new Listener();
39: toolkit.addAWTEventListener(l2, -1);
40: list.clear();
41: System.gc();
42:
43: // All unreferenced listeners should be removed on the next posted
44: // event.
45: showFrame(new JLabel(getName()));
46:
47: Throwable t1 = (Throwable) l1.contexts
48: .get(l1.contexts.size() - 1);
49: Throwable t2 = (Throwable) l2.contexts
50: .get(l2.contexts.size() - 1);
51:
52: try {
53: int MAX_STACK = 2000;
54: String stack1 = Log.getStack(t1);
55: assertTrue("Stack trace too long (" + stack1.length()
56: + "): " + stack1, stack1.length() < MAX_STACK);
57: String stack2 = Log.getStack(t2);
58: assertTrue("Stack trace too long (" + stack2.length()
59: + "): " + stack2, stack2.length() < MAX_STACK);
60: } finally {
61: toolkit.removeAWTEventListener(l1);
62: toolkit.removeAWTEventListener(l2);
63: }
64: }
65:
66: public WeakAWTEventListenerTest(String name) {
67: super (name);
68: }
69:
70: public static void main(String[] args) {
71: TestHelper.runTests(args, WeakAWTEventListenerTest.class);
72: }
73: }
|