KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openide > util > RequestProcessorTest


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.openide.util;
21
22 import java.lang.ref.*;
23 import java.util.*;
24 import org.openide.ErrorManager;
25 import junit.framework.*;
26 import org.netbeans.junit.*;
27 import org.openide.util.Task;
28
29 public class RequestProcessorTest extends NbTestCase {
30     static {
31         System.setProperty("org.openide.util.Lookup", "org.openide.util.RequestProcessorTest$Lkp");
32     }
33
34     private ErrorManager log;
35
36     public RequestProcessorTest(java.lang.String JavaDoc testName) {
37         super(testName);
38     }
39
40     protected void setUp () throws Exception JavaDoc {
41         super.setUp();
42         
43         log = ErrorManager.getDefault().getInstance("TEST-" + getName());
44     }
45
46     protected void runTest() throws Throwable JavaDoc {
47         assertNotNull ("ErrManager has to be in lookup", org.openide.util.Lookup.getDefault ().lookup (ErrManager.class));
48         ErrManager.messages.setLength(0);
49         
50         try {
51             super.runTest();
52         } catch (Throwable JavaDoc ex) {
53             throw new junit.framework.AssertionFailedError (
54                 ex.getMessage() + "\n" + ErrManager.messages.toString()
55             ).initCause(ex);
56         }
57     }
58     
59     
60     /** A test to check that objects are executed in the right order.
61      */

62     public void testOrder () throws Exception JavaDoc {
63         final int[] count = new int[1];
64         final String JavaDoc[] fail = new String JavaDoc[1];
65         
66         class X extends Object JavaDoc
67         implements Runnable JavaDoc, Comparable JavaDoc {
68             public int order;
69             
70             public void run () {
71                 if (order != count[0]++) {
72                     if (fail[0] == null) {
73                         fail[0] = "Executing task " + order + " instead of " + count[0];
74                     }
75                 }
76             }
77             
78             public int compareTo (Object JavaDoc o) {
79                 X x = (X)o;
80                 
81                 return System.identityHashCode (x) - System.identityHashCode (this);
82             }
83             
84             public String JavaDoc toString () {
85                 return "O: " + order;
86             }
87         };
88         
89         // prepare the tasks
90
X[] arr = new X[10];
91         for (int i = 0; i < arr.length; i++) {
92             arr[i] = new X ();
93         }
94         
95         // sort it
96
// Arrays.sort (arr);
97

98         for (int i = 0; i < arr.length; i++) {
99             arr[i].order = i;
100         }
101         
102         // execute the task as quickly as possible (only those with the same time
103
// can have wrong order
104
RequestProcessor.Task[] wait = new RequestProcessor.Task[arr.length];
105         for (int i = 0; i < arr.length; i++) {
106             wait[i] = RequestProcessor.postRequest (arr[i]);
107         }
108         
109         // wait to all tasks to finish
110
for (int i = 0; i < arr.length; i++) {
111             wait[i].waitFinished ();
112         }
113         
114         if (fail[0] != null) {
115             fail (fail[0]);
116         }
117             
118     }
119     
120     public void testTaskLeakWhenCancelled() throws Exception JavaDoc {
121         Runnable JavaDoc r = new Runnable JavaDoc() {public void run() {}};
122
123         // schedule (1hour) and cancel immediatelly
124
new RequestProcessor(getName()).post(r, 3600*1000).cancel();
125         
126         WeakReference<Runnable JavaDoc> wr = new WeakReference<Runnable JavaDoc>(r);
127         r = null;
128         assertGC("runnable should be collected", wr);
129     }
130
131     /* This might be issue as well, but taking into account the typical lifecycle
132         of a RP and its size, I won't invest in fixing this now.
133      */
/*
134     public void testRPLeakWhenLastTaskCancelled() throws Exception {
135         Runnable r = new Runnable() {public void run() {}};
136
137         // schedule (1hour) and cancel immediatelly
138         RequestProcessor rp = new RequestProcessor(getName());
139         rp.post(r, 3600*1000).cancel();
140         
141         WeakReference wr = new WeakReference(rp);
142         rp = null;
143         assertGC("runnable should be collected", wr);
144     } /**/

145     
146     public void testScheduleAndIsFinished() throws InterruptedException JavaDoc {
147         class Run implements Runnable JavaDoc {
148             public boolean run;
149             public boolean second;
150             
151             public synchronized void run() {
152                 if (run) {
153                     second = true;
154                     return;
155                 }
156                 
157                 try {
158                     notifyAll();
159                     wait();
160                 } catch (InterruptedException JavaDoc ex) {
161                     fail(ex.getMessage());
162                 }
163                 run = true;
164             }
165         }
166         
167         
168         Run r = new Run();
169         RequestProcessor.Task task;
170         synchronized (r) {
171             task = new RequestProcessor(getName()).post(r);
172             r.wait();
173             task.schedule(200);
174             r.notifyAll();
175         }
176
177         Thread.sleep(100);
178         assertTrue("Run successfully", r.run);
179         assertFalse("Not for the second time1", r.second);
180         assertFalse("Not finished as it is scheduled", task.isFinished());
181         assertFalse("Not for the second time2", r.second);
182         
183         task.waitFinished();
184         assertTrue("Finished now", task.isFinished());
185         assertTrue("Run again", r.second);
186         
187     }
188
189     /**
190      * A test that check that priorities are handled well.
191      */

192     public void testPriorityQueue() throws Exception JavaDoc {
193         
194         final Runnable JavaDoc[] arr = new Runnable JavaDoc[5];
195         
196         class R implements Runnable JavaDoc {
197             
198             public int index;
199             
200             public R (int i) {
201                 index = i;
202             }
203             
204             public synchronized void run () {
205                 for (int i = 0; /*i < arr.length*/; i++) {
206                     if (arr[i] == null) {
207                         arr[i] = this;
208                         break;
209                     }
210                 }
211                 
212             }
213             
214             public String JavaDoc toString () {
215                 return " R index " + index;
216             }
217         }
218
219         Runnable JavaDoc r[] = new Runnable JavaDoc[5];
220         // expected order of execution
221
for (int i = 0; i<5; i++) {
222             r[i] = new R(i);
223         }
224         
225         RequestProcessor rp = new RequestProcessor("PrioriyTest");
226         
227         RequestProcessor.Task t[] = new RequestProcessor.Task[5];
228         synchronized (r[0]) {
229             t[4] = rp.post(r[0], 0, 3);
230             t[0] = rp.post(r[4], 0, 1);
231             t[1] = rp.post(r[2], 0, 2);
232             t[2] = rp.post(r[1], 0, 2);
233             t[3] = rp.post(r[3], 0, 2);
234             t[2].setPriority(3);
235         }
236         
237         for (int i = 0; i<5; i++) {
238             t[i].waitFinished();
239         }
240         
241         for (int i = 0; i<5; i++) {
242             R next = (R) arr[i];
243             if (next.index != i) fail("Expected at " + i + " but was " + next.index);
244         }
245     }
246     
247     /** Test bug http://www.netbeans.org/issues/show_bug.cgi?id=31906
248      */

249     public void testBug31906_SimulateDataFolderTest () {
250         RequestProcessor rp = new RequestProcessor ("dataFolderTest");
251         
252         class X implements Runnable JavaDoc {
253             private RequestProcessor.Task wait;
254             private int cnt;
255             
256             public synchronized void run () {
257                 if (wait != null) {
258                     wait.waitFinished ();
259                     cnt++;
260                 } else {
261                     cnt++;
262                 }
263             }
264             
265             public synchronized void assertCnt (String JavaDoc msg, int cnt) {
266                 assertEquals (msg, cnt, this.cnt);
267                 this.cnt = 0;
268             }
269             
270             public synchronized void waitFor (RequestProcessor.Task t) {
271                 wait = t;
272             }
273             
274         }
275         X[] arr = { new X(), new X() };
276         RequestProcessor.Task[] tasks = {
277             rp.create (arr[0]),
278             rp.create (arr[1])
279         };
280         tasks[0].setPriority(Thread.NORM_PRIORITY - 1);
281         tasks[1].setPriority(Thread.NORM_PRIORITY + 1);
282         
283         tasks[0].schedule(0);
284         tasks[1].schedule(0);
285
286         tasks[0].waitFinished();
287         arr[0].assertCnt (" Once", 1);
288         tasks[1].waitFinished ();
289         arr[1].assertCnt (" Once as well", 1);
290
291         tasks[0].schedule(100);
292         tasks[1].schedule(100);
293         tasks[0].schedule(10);
294         tasks[1].schedule(10);
295
296         tasks[0].waitFinished();
297         tasks[1].waitFinished();
298
299         arr[0].assertCnt (" 1a", 1);
300         arr[1].assertCnt (" 1b", 1);
301
302         arr[0].waitFor (tasks[1]);
303         tasks[1].schedule(100);
304         tasks[0].schedule(10);
305         tasks[0].waitFinished ();
306         arr[0].assertCnt (" task 0 is executed", 1);
307         arr[1].assertCnt (" but it also executes task 1", 1);
308
309         tasks[0].schedule(10);
310         tasks[0].waitFinished ();
311         arr[0].assertCnt (" task O is executed", 1);
312         arr[1].assertCnt (" but it does not execute 1", 0);
313     }
314     
315     
316     /** Test priority inversion and whether it is properly notified
317      */

318     public void testPriorityInversionProblemAndItsDiagnosis () throws Exception JavaDoc {
319         RequestProcessor rp = new RequestProcessor ("testPriorityInversionProblemAndItsDiagnosis");
320         
321         final Runnable JavaDoc[] arr = new Runnable JavaDoc[3];
322         
323         class R implements Runnable JavaDoc {
324             
325             public int index;
326             public Task t;
327             
328             public R (int i) {
329                 index = i;
330             }
331             
332             public synchronized void run () {
333                 for (int i = 0; /*i < arr.length*/; i++) {
334                     if (arr[i] == null) {
335                         arr[i] = this;
336                         break;
337                     }
338                 }
339                 
340                 if (t != null) {
341                     t.waitFinished ();
342                 }
343             }
344             
345             public String JavaDoc toString () {
346                 return " R index " + index;
347             }
348         }
349          
350         R r1 = new R (1);
351         R r2 = new R (2);
352         R r3 = new R (3);
353         
354         Task t1;
355         Task t2;
356         Task t3;
357         
358         synchronized (r1) {
359             t1 = rp.post (r1);
360             t2 = rp.post (r2);
361             
362             // r1 will call the waitFinished of r3
363
r1.t = t3 = rp.post (r3);
364         }
365         
366         t1.waitFinished ();
367         t2.waitFinished ();
368         t3.waitFinished ();
369         
370         assertEquals ("First started is t1", r1, arr[0]);
371         assertEquals ("Second started is t3", r3, arr[1]);
372         assertEquals ("Last started is t2", r2, arr[2]);
373         
374         // now we should ensure that the RP warned everyone about the
375
// priority inheritance and all its possible complications (t2 running
376
// later than t3)
377
}
378     
379     /** Test of finalize method, of class org.openide.util.RequestProcessor. */
380     public void testFinalize() throws Exception JavaDoc {
381         RequestProcessor rp = new RequestProcessor ("toGarbageCollect");
382         Reference<RequestProcessor> ref = new WeakReference<RequestProcessor> (rp);
383         Reference<Task> task;
384         
385         final Object JavaDoc lock = new Object JavaDoc ();
386         
387         
388         synchronized (lock) {
389             task = new WeakReference<Task> (rp.post (new Runnable JavaDoc () {
390                 public void run () {
391                     synchronized (lock) {
392                         lock.notify ();
393                     }
394                 }
395             }));
396             
397             
398             rp = null;
399
400             doGc (10, null);
401             
402             if (ref.get () == null) {
403                 fail ("garbage collected even a task is planed."); // NOI18N
404
}
405             
406             // run the task
407
lock.wait ();
408             
409         }
410         
411         doGc (1000, task);
412         
413         if (task.get () != null) {
414             fail ("task is not garbage collected.");
415         }
416         
417         doGc (1000, ref);
418         if (ref.get () != null) {
419             fail ("not garbage collected at all."); // NOI18N
420
}
421         
422     }
423     
424     /** Check whether task is finished when it should be.
425      */

426     public void testCheckFinished () {
427         doCheckFinished(false);
428     }
429     public void testCheckFinishedWithFalse () {
430         doCheckFinished(true);
431     }
432     
433     private void doCheckFinished(boolean usefalse) {
434         RequestProcessor rp = new RequestProcessor ("Finish");
435
436 class R extends Object JavaDoc implements Runnable JavaDoc {
437     RequestProcessor.Task t;
438     
439     public void run () {
440         if (t.isFinished ()) {
441             fail ("Finished when running");
442         }
443     }
444 }
445         
446         R r = new R ();
447         RequestProcessor.Task task = usefalse ? rp.create(r, false) : rp.create (r);
448         r.t = task;
449
450         if (task.isFinished ()) {
451             fail ("Finished after creation");
452         }
453      
454         doCommonTestWithScheduling(task);
455     }
456
457     private void doCommonTestWithScheduling(final RequestProcessor.Task task) {
458      
459         task.schedule (200);
460         
461         if (task.isFinished ()) {
462             fail ("Finished when planed");
463         }
464         
465         task.waitFinished ();
466         
467         if (!task.isFinished ()) {
468             fail ("Not finished after waitFinished");
469         }
470         
471         task.schedule (200);
472         
473         if (task.isFinished ()) {
474             fail ("Finished when planed");
475         }
476     }
477
478     public void testCheckFinishedWithTrue () {
479         RequestProcessor rp = new RequestProcessor ("Finish");
480         
481         class R extends Object JavaDoc implements Runnable JavaDoc {
482             RequestProcessor.Task t;
483             
484             public void run () {
485                 if (t.isFinished ()) {
486                     fail ("Finished when running");
487                 }
488             }
489         }
490         
491         R r = new R ();
492         RequestProcessor.Task task = rp.create(r, true);
493         r.t = task;
494
495         assertTrue("It has to be finished after creation", task.isFinished());
496
497         task.waitFinished();
498
499         // rest is the same
500
doCommonTestWithScheduling(task);
501     }
502         
503
504     /** Test to check the waiting in request processor.
505     */

506     public void testWaitFinishedOnNotStartedTask () throws Exception JavaDoc {
507         Counter x = new Counter ();
508         final RequestProcessor.Task task = RequestProcessor.getDefault().create (x);
509         
510         //
511
// Following code tests whether the RP.create().waitFinished really blocks
512
// until somebody schedules the task.
513
//
514
class WaitThread extends Thread JavaDoc {
515             public boolean finished;
516             
517             public void run () {
518                 task.waitFinished ();
519                 synchronized (this) {
520                     finished = true;
521                     notifyAll ();
522                 }
523             }
524             
525             public synchronized void w (int timeOut) throws Exception JavaDoc {
526                 if (!finished) {
527                     wait (timeOut);
528                 }
529             }
530         }
531         WaitThread wt = new WaitThread ();
532         wt.start ();
533         wt.w (100);
534         assertTrue ("The waitFinished has not ended, because the task has not been planned", !wt.finished);
535         task.schedule (0);
536         wt.w (0);
537         assertTrue ("The waitFinished finished, as the task is now planned", wt.finished);
538         x.assertCnt ("The task has been executed", 1);
539     }
540     
541     /** Test to check the waiting in request processor.
542     */

543     public void testWaitFinishedOnNotStartedTaskFromRPThread () throws Exception JavaDoc {
544         Counter x = new Counter ();
545         RequestProcessor rp = new RequestProcessor ("testWaitFinishedOnNotStartedTaskFromRPThread");
546         final RequestProcessor.Task task = rp.create (x);
547         
548         //
549
// Following code tests whether the RP.create().waitFinished really blocks
550
// until somebody schedules the task.
551
//
552
class WaitTask implements Runnable JavaDoc {
553             public boolean finished;
554             
555             public synchronized void run () {
556                 task.waitFinished ();
557                 finished = true;
558                 notifyAll ();
559             }
560             
561             public synchronized void w (int timeOut) throws Exception JavaDoc {
562                 if (!finished) {
563                     wait (timeOut);
564                 }
565             }
566         }
567         WaitTask wt = new WaitTask ();
568         rp.post (wt);
569         wt.w (0);
570         assertTrue ("The task.waitFinished has to finish, otherwise the RequestProcessor thread will stay occupied forever", wt.finished);
571         x.assertCnt ("The task has been executed - wait from RP made it start", 1);
572     }
573         
574     public void testWaitFinished2 () {
575         Counter x = new Counter ();
576         final RequestProcessor.Task task = RequestProcessor.getDefault().create (x);
577         task.schedule (500);
578         if (task.cancel ()) {
579             // ok, task is canceled
580
task.waitFinished ();
581         }
582
583         // does a task that is scheduled means that it is not finished?
584
task.schedule (200);
585         task.waitFinished();
586         x.assertCnt ("Wait does not wait for finish of scheduled tasks, that already has been posted", 1);
587     }
588     
589     /** Ensure that it is safe to call schedule() while the task is running
590      * (should finish the task and run it again).
591      */

592     public void testScheduleWhileRunning() throws Exception JavaDoc {
593         class X implements Runnable JavaDoc {
594             public synchronized void run() {
595                 try {
596                     if (cnt == 0) {
597                         this.notify(); // #1
598
this.wait(9999); // #2
599
cnt++;
600                     } else {
601                         cnt++;
602                         this.notify(); // #3
603
}
604                 } catch (InterruptedException JavaDoc ie) {
605                     ie.printStackTrace();
606                 }
607             }
608             public int cnt = 0;
609         }
610         X x = new X();
611         synchronized (x) {
612             RequestProcessor.Task task = RequestProcessor.postRequest(x);
613             x.wait(9999); // #1
614
assertEquals(0, x.cnt);
615             task.schedule(0);
616             x.notify(); // #2
617
x.wait(9999); // #3
618
assertEquals(2, x.cnt);
619         }
620     }
621     
622     /** Make sure it is safe to call waitFinished() on a task from within
623      * a task listener.
624      */

625     public void testWaitFinishedFromNotification() throws Exception JavaDoc {
626         class X implements Runnable JavaDoc {
627             private Task task;
628             private int cnt;
629             public synchronized Task start() {
630                 if (task == null) {
631                     task = RequestProcessor.postRequest(this);
632                 }
633                 return task;
634             }
635             public void run() {
636                 cnt++;
637             }
638             public int getCount() {
639                 return cnt;
640             }
641             public void block() {
642                 start().waitFinished();
643             }
644         }
645         final X x = new X();
646         final Object JavaDoc lock = "wait for task to finish";
647         final boolean[] finished = new boolean[1];
648         x.start().addTaskListener(new TaskListener() {
649             public void taskFinished(Task t) {
650                 x.block();
651                 finished[0] = true;
652                 synchronized (lock) {
653                     lock.notify();
654                 }
655             }
656         });
657         synchronized (lock) {
658             lock.wait(5000);
659         }
660         assertTrue(finished[0]);
661         assertEquals(1, x.getCount());
662     }
663
664     /** Make sure that successfully canceled task is not performed.
665      */

666     public void testCancel() throws Exception JavaDoc {
667         class X implements Runnable JavaDoc {
668             public boolean performed = false;
669             public void run() {
670                 performed = true;
671             }
672         }
673         
674         X x = new X();
675         final boolean[] finished = new boolean[1];
676         finished[0] = false;
677         
678         // post task with some delay
679
RequestProcessor.Task task = RequestProcessor.postRequest(x, 1000);
680         task.addTaskListener(new TaskListener() {
681             public void taskFinished(Task t) {
682                 finished[0] = true;
683             }
684         });
685
686         boolean canceled = task.cancel();
687         assertTrue("Task was not canceled", canceled);
688         assertTrue("The taskFinished was not called for canceled task", finished[0]);
689         Thread.sleep(1500); // wait longer than task delay
690
assertTrue("Task was performed even if it is canceled", !x.performed);
691     }
692     
693     public void testWaitWithTimeOutCanFinishEvenTheTaskHasNotRun () throws Exception JavaDoc {
694         class Run implements Runnable JavaDoc {
695             public boolean runned;
696             public synchronized void run () {
697                 runned = true;
698             }
699         }
700         
701         Run run = new Run ();
702         
703         synchronized (run) {
704             RequestProcessor.Task task = RequestProcessor.getDefault ().post (run);
705             task.waitFinished (100);
706             assertFalse ("We are here and the task has not finished", run.runned);
707             assertFalse ("Not finished", task.isFinished ());
708         }
709     }
710     
711     public void testWhenWaitingForALimitedTimeFromTheSameProcessorThenInterruptedExceptionIsThrownImmediatelly () throws Exception JavaDoc {
712         Counter x = new Counter ();
713         RequestProcessor rp = new RequestProcessor ("testWaitFinishedOnNotStartedTaskFromRPThread");
714         final RequestProcessor.Task task = rp.create (x);
715         
716         class WaitTask implements Runnable JavaDoc {
717             public boolean finished;
718             
719             public synchronized void run () {
720                 long time = System.currentTimeMillis ();
721                 try {
722                     task.waitFinished (1000);
723                     fail ("This should throw an exception. Btw time was: " + (System.currentTimeMillis () - time));
724                 } catch (InterruptedException JavaDoc ex) {
725                     // ok, this is expected
726
} finally {
727                     time = System.currentTimeMillis () - time;
728                     notifyAll ();
729                 }
730                 if (time > 100) {
731                     fail ("Exception should be thrown quickly. Was: " + time);
732                 }
733                 finished = true;
734             }
735             
736         }
737         WaitTask wt = new WaitTask ();
738         synchronized (wt) {
739             rp.post (wt);
740             wt.wait ();
741         }
742         assertTrue ("The task.waitFinished has to finish", wt.finished);
743         x.assertCnt ("The task has NOT been executed", 0);
744     }
745     
746     public void testWhenWaitingForAlreadyFinishedTaskWithTimeOutTheResultIsGood () throws Exception JavaDoc {
747         Counter x = new Counter ();
748         RequestProcessor rp = new RequestProcessor ("testWaitFinishedOnStartedTaskFromRPThread");
749         final RequestProcessor.Task task = rp.post (x);
750         task.waitFinished ();
751         x.assertCnt ("The task has been executed before", 1);
752         
753         class WaitTask implements Runnable JavaDoc {
754             public boolean finished;
755             
756             public synchronized void run () {
757                 notifyAll ();
758                 try {
759                     assertTrue ("The task has been already finished", task.waitFinished (1000));
760                 } catch (InterruptedException JavaDoc ex) {
761                     ex.printStackTrace();
762                     fail ("Should not happen");
763                 }
764                 finished = true;
765             }
766             
767         }
768         WaitTask wt = new WaitTask ();
769         synchronized (wt) {
770             rp.post (wt);
771             wt.wait ();
772         }
773         assertTrue ("The task.waitFinished has to finish", wt.finished);
774     }
775     
776     /**
777      * A processing thread must survive throwable thrown during
778      * execution of given taks. RuntimeException
779      */

780     public void testSurvivesException() throws Exception JavaDoc {
781         doSurviveTest(false); // NPE
782
doSurviveTest(true); // AssertionError
783
}
784
785
786     private void doSurviveTest(final boolean error) throws Exception JavaDoc {
787         RequestProcessor rp = new RequestProcessor("SurvivesTest");
788         Counter x = new Counter ();
789         
790         final Locker lock = new Locker();
791         
792         rp.post (new Runnable JavaDoc() {
793             public void run() {
794                 lock.waitOn();
795                 
796                 if (error) {
797                     throw new AssertionError JavaDoc();
798                 } else {
799                     throw new NullPointerException JavaDoc();
800                 }
801             }
802         });
803         
804         rp.post(x);
805         lock.notifyOn();
806         
807         x.assertCntWaiting("Second task not performed after " +
808                      (error ? "error" : "exception"), 1);
809     }
810     
811     public void testCancelInterruptsTheRunningThread () throws Exception JavaDoc {
812         RequestProcessor rp = new RequestProcessor ("Cancellable", 1, true);
813         
814         class R implements Runnable JavaDoc {
815             private String JavaDoc name;
816             
817             public boolean checkBefore;
818             public boolean checkAfter;
819             public boolean interrupted;
820             
821             public R (String JavaDoc n) {
822                 this.name = n;
823             }
824             
825             public synchronized void run () {
826                 checkBefore = Thread.interrupted();
827                 
828                 log.log("in runnable " + name + " check before: " + checkBefore);
829                 
830                 notifyAll ();
831
832                 log.log("in runnable " + name + " after notify");
833                 
834                 try {
835                     wait ();
836                     log.log("in runnable " + name + " after wait, not interrupted");
837                     interrupted = false;
838                 } catch (InterruptedException JavaDoc ex) {
839                     interrupted = true;
840                     log.log("in runnable " + name + " after wait, interrupted");
841                 }
842                 
843                 notifyAll ();
844                 
845                 log.log("in runnable " + name + " after notifyAll");
846
847                 try {
848                     wait ();
849                     log.log("in runnable " + name + " after second wait, not interrupted");
850                     checkAfter = Thread.interrupted();
851                 } catch (InterruptedException JavaDoc ex) {
852                     log.log("in runnable " + name + " after second wait, interrupted");
853                     checkAfter = true;
854                 }
855                 
856                 log.log("in runnable " + name + " checkAfter: " + checkAfter);
857                 
858                 notifyAll ();
859             }
860         }
861         
862         R r = new R ("First");
863         RequestProcessor.Task t;
864         synchronized (r) {
865             t = rp.post (r);
866             r.wait ();
867             assertTrue ("The task is already running", !t.cancel ());
868             log.log("Main checkpoint1");
869             r.wait ();
870             log.log("Main checkpoint2");
871             r.notifyAll ();
872             log.log("Main checkpoint3");
873             r.wait ();
874             log.log("Main checkpoint4");
875             assertTrue ("The task has been interrupted", r.interrupted);
876             assertTrue ("Not before", !r.checkBefore);
877             assertTrue ("Not after - as the notification was thru InterruptedException", !r.checkAfter);
878         }
879         log.log("Main checkpoint5");
880         t.waitFinished();
881         log.log("Main checkpoint6");
882         /*
883         try {
884             assertGC("no", new java.lang.ref.WeakReference(this));
885         } catch (Error e) {
886             // ok
887         }
888          */

889         
890         // interrupt after the task has finished
891
r = new R ("Second");
892         synchronized (r) {
893             t = rp.post (r);
894             log.log("Second checkpoint1");
895             r.wait ();
896             r.notifyAll ();
897             log.log("Second checkpoint2");
898             r.wait ();
899             log.log("Second checkpoint3");
900             assertTrue ("The task is already running", !t.cancel ());
901             log.log("Second checkpoint4");
902             r.notifyAll ();
903             log.log("Second checkpoint5");
904             r.wait ();
905             assertTrue ("The task has not been interrupted by exception", !r.interrupted);
906             assertTrue ("Not interupted before", !r.checkBefore);
907             assertTrue ("But interupted after", r.checkAfter);
908         }
909         log.log("Second checkpoint6");
910         t.waitFinished();
911         log.log("Second checkpoint7");
912     }
913
914     public void testCancelDoesNotInterruptTheRunningThread () throws Exception JavaDoc {
915         RequestProcessor rp = new RequestProcessor ("Not Cancellable", 1, false);
916         
917         class R implements Runnable JavaDoc {
918             public boolean checkBefore;
919             public boolean checkAfter;
920             public boolean interrupted;
921             
922             public synchronized void run () {
923                 checkBefore = Thread.interrupted();
924                 
925                 notifyAll ();
926                 
927                 try {
928                     wait ();
929                     interrupted = false;
930                 } catch (InterruptedException JavaDoc ex) {
931                     interrupted = true;
932                 }
933                 
934                 notifyAll ();
935                 
936                 try {
937                     wait ();
938                 } catch (InterruptedException JavaDoc ex) {
939                 }
940                 
941                 checkAfter = Thread.interrupted();
942                 
943                 notifyAll ();
944             }
945         }
946         
947         R r = new R ();
948         synchronized (r) {
949             RequestProcessor.Task t = rp.post (r);
950             r.wait ();
951             assertTrue ("The task is already running", !t.cancel ());
952             r.notifyAll ();
953             r.wait ();
954             r.notifyAll ();
955             r.wait ();
956             assertFalse ("The task has not been interrupted", r.interrupted);
957             assertTrue ("Not before", !r.checkBefore);
958             assertTrue ("Not after - as the notification was thru InterruptedException", !r.checkAfter);
959         }
960         
961         // interrupt after the task has finished
962
r = new R ();
963         synchronized (r) {
964             RequestProcessor.Task t = rp.post (r);
965             r.wait ();
966             r.notifyAll ();
967             r.wait ();
968             assertTrue ("The task is already running", !t.cancel ());
969             r.notifyAll ();
970             r.wait ();
971             assertTrue ("The task has not been interrupted by exception", !r.interrupted);
972             assertFalse ("Not interupted before", r.checkBefore);
973             assertFalse ("Not interupted after", r.checkAfter);
974         }
975     }
976     
977     public void testInterruptedStatusIsClearedBetweenTwoTaskExecution () throws Exception JavaDoc {
978         RequestProcessor rp = new RequestProcessor ("testInterruptedStatusIsClearedBetweenTwoTaskExecution", 1, true);
979         
980         final RequestProcessor.Task[] task = new RequestProcessor.Task[1];
981         // test interrupted status is cleared after task ends
982
class Fail implements Runnable JavaDoc {
983             public boolean checkBefore;
984             public Thread JavaDoc runIn;
985             public boolean goodThread;
986             
987             public synchronized void run () {
988                 if (runIn == null) {
989                     runIn = Thread.currentThread();
990                     task[0].schedule (0);
991                     
992                     // wait to make sure the task is scheduled
993
try {
994                         Thread.sleep(100);
995                     } catch (InterruptedException JavaDoc ex) {
996                         ex.printStackTrace();
997                     }
998                 } else {
999                     goodThread = Thread.currentThread () == runIn;
1000                }
1001                    
1002                checkBefore = runIn.isInterrupted();
1003                // set the flag for next execution
1004
runIn.interrupt();
1005                
1006                notifyAll ();
1007            }
1008        }
1009        
1010        Fail f = new Fail ();
1011        synchronized (f) {
1012            task[0] = rp.post (f);
1013            
1014            // wait for the first execution
1015
f.wait ();
1016        }
1017        // wait for the second
1018
task[0].waitFinished ();
1019        
1020        /* Shall be true, but sometimes the threads get GCed, so we cannot really check that.
1021        assertTrue ("This shall be always true, but if not, than it does not mean too much"
1022            + " just that the tasks were not executed in the same thread. In such case it "
1023            + " this test does not do anything useful as it needs to execute the task twice "
1024            + " in the same thread", f.goodThread);
1025        */

1026        
1027        if (f.goodThread) {
1028            assertTrue ("Interrupted state has been cleared between two executions of the task", !f.checkBefore);
1029        }
1030    }
1031    
1032    public void testInterruptedStatusWorksInInversedTasks() throws Exception JavaDoc {
1033        RequestProcessor rp = new RequestProcessor ("testInterruptedStatusWorksInInversedTasks", 1, true);
1034        
1035        class Fail implements Runnable JavaDoc {
1036            public Fail (String JavaDoc n) {
1037                name = n;
1038            }
1039            
1040            private String JavaDoc name;
1041            public RequestProcessor.Task wait;
1042            public Object JavaDoc lock;
1043            public Exception JavaDoc ex;
1044            
1045            public boolean checkBefore;
1046            public boolean checkAfter;
1047            
1048            public void run () {
1049                synchronized (this) {
1050                    checkBefore = Thread.interrupted();
1051                    log("checkBefore: " + checkBefore);
1052                    notifyAll();
1053                }
1054                if (lock != null) {
1055                    synchronized (lock) {
1056                        lock.notify();
1057                        try {
1058                            lock.wait();
1059                        } catch (InterruptedException JavaDoc ex) {
1060                            this.ex = ex;
1061                            ex.printStackTrace();
1062                            fail ("No InterruptedException");
1063                        }
1064                        log.log("wait for lock over");
1065                    }
1066                }
1067                
1068                if (wait != null) {
1069                    wait.schedule(100);
1070                    wait.waitFinished();
1071                }
1072                
1073                synchronized (this) {
1074                    checkAfter = Thread.interrupted();
1075                    log.log("checkAfter: " + checkAfter);
1076                    notifyAll();
1077                }
1078            }
1079            
1080            public String JavaDoc toString () {
1081                return name;
1082            }
1083        }
1084        
1085        Object JavaDoc initLock = new Object JavaDoc();
1086        
1087        Fail smaller = new Fail("smaller");
1088        smaller.lock = initLock;
1089        Fail bigger = new Fail("BIGGER");
1090        RequestProcessor.Task smallerTask, biggerTask;
1091        
1092        
1093        smallerTask = rp.create (smaller);
1094        biggerTask = rp.create (bigger);
1095        
1096        bigger.wait = smallerTask;
1097        
1098        synchronized (initLock) {
1099            log.log("schedule 0");
1100            biggerTask.schedule(0);
1101            initLock.wait();
1102            initLock.notifyAll();
1103            log.log("doing cancel");
1104            assertFalse ("Already running", biggerTask.cancel());
1105            log.log("biggerTask cancelled");
1106        }
1107
1108        biggerTask.waitFinished();
1109        log.log("waitFinished over");
1110        
1111        assertFalse("bigger not interrupted at begining", bigger.checkBefore);
1112        assertFalse("smaller not interrupted at all", smaller.checkBefore);
1113        assertFalse("smaller not interrupted at all2", smaller.checkAfter);
1114        assertTrue("bigger interrupted at end", bigger.checkAfter);
1115        
1116    }
1117
1118    public void testInterruptedStatusWorksInInversedTasksWhenInterruptedSoon() throws Exception JavaDoc {
1119        RequestProcessor rp = new RequestProcessor ("testInterruptedStatusWorksInInversedTasksWhenInterruptedSoon", 1, true);
1120        
1121        class Fail implements Runnable JavaDoc {
1122            public Fail(String JavaDoc n) {
1123                name = n;
1124            }
1125            
1126            private String JavaDoc name;
1127            public RequestProcessor.Task wait;
1128            public Object JavaDoc lock;
1129            
1130            public boolean checkBefore;
1131            public boolean checkAfter;
1132            
1133            public volatile boolean alreadyCanceled;
1134            
1135            public void run () {
1136                synchronized (this) {
1137                    checkBefore = Thread.interrupted();
1138                    log.log(name + " checkBefore: " + checkBefore);
1139                    notifyAll();
1140                }
1141                if (lock != null) {
1142                    synchronized (lock) {
1143                        lock.notify();
1144                    }
1145                }
1146                
1147                if (wait != null) {
1148                    // we cannot call Thread.sleep, so lets slow things own
1149
// in other way
1150

1151                    log(name + " do waitFinished");
1152                    wait.waitFinished();
1153                    log(name + " waitFinished in task is over");
1154                    
1155                    log.log(name + " slowing by using System.gc");
1156                    while (!alreadyCanceled) {
1157                        System.gc ();
1158                    }
1159                    log.log(name + " ended slowing");
1160                    
1161                }
1162                
1163                synchronized (this) {
1164                    checkAfter = Thread.interrupted();
1165                    log.log(name + " checkAfter: " + checkAfter);
1166                    notifyAll();
1167                }
1168            }
1169        }
1170        
1171        Object JavaDoc initLock = new Object JavaDoc();
1172        
1173        Fail smaller = new Fail("smaller");
1174        Fail bigger = new Fail("bigger");
1175        RequestProcessor.Task smallerTask, biggerTask;
1176        
1177        
1178        smallerTask = rp.create (smaller);
1179        biggerTask = rp.create (bigger);
1180
1181        
1182        bigger.lock = initLock;
1183        bigger.wait = smallerTask;
1184        
1185        synchronized (initLock) {
1186            log.log("Do schedule");
1187            biggerTask.schedule(0);
1188            initLock.wait();
1189            log.log("do cancel");
1190            assertFalse ("Already running", biggerTask.cancel());
1191            bigger.alreadyCanceled = true;
1192            log.log("cancel done");
1193        }
1194
1195        biggerTask.waitFinished();
1196        log.log("waitFinished is over");
1197        
1198        assertFalse("bigger not interrupted at begining", bigger.checkBefore);
1199        assertFalse("smaller not interrupted at all", smaller.checkBefore);
1200        assertFalse("smaller not interrupted at all2", smaller.checkAfter);
1201        assertTrue("bigger interrupted at end", bigger.checkAfter);
1202    }
1203    
1204    public void testTaskFinishedOnCancelFiredAfterTaskHasReallyFinished() throws Exception JavaDoc {
1205        RequestProcessor rp = new RequestProcessor("Cancellable", 1, true);
1206        
1207        class X implements Runnable JavaDoc {
1208            
1209            volatile boolean reallyFinished = false;
1210            
1211            public synchronized void run() {
1212                notifyAll();
1213                
1214                try {
1215                    wait();
1216                } catch (InterruptedException JavaDoc e) {
1217                    // interrupted by Task.cancel()
1218
}
1219                
1220                notifyAll();
1221                
1222                try {
1223                    wait();
1224                } catch (InterruptedException JavaDoc e) {
1225                }
1226                
1227                reallyFinished = true;
1228            }
1229        }
1230        
1231        final X x = new X();
1232        synchronized (x) {
1233            RequestProcessor.Task t = rp.post(x);
1234            t.addTaskListener(new TaskListener() {
1235                public void taskFinished(Task t) {
1236                    assertTrue(x.reallyFinished);
1237                }
1238            });
1239            x.wait();
1240            t.cancel();
1241            x.wait();
1242            x.notifyAll();
1243        }
1244    }
1245    
1246    private static void doGc (int count, Reference toClear) {
1247        java.util.ArrayList JavaDoc<byte[]> l = new java.util.ArrayList JavaDoc<byte[]> (count);
1248        while (count-- > 0) {
1249            if (toClear != null && toClear.get () == null) break;
1250            
1251            l.add (new byte[1000]);
1252            System.gc ();
1253            System.runFinalization();
1254        try {
1255            Thread.sleep(10);
1256        } catch (InterruptedException JavaDoc e) {}
1257        }
1258    }
1259
1260    private static class Counter extends Object JavaDoc implements Runnable JavaDoc {
1261        private int count = 0;
1262
1263        public synchronized void run () {
1264            count++;
1265        }
1266        
1267        public synchronized void assertCnt (String JavaDoc msg, int cnt) {
1268            assertEquals (msg, cnt, this.count);
1269            this.count = 0;
1270        }
1271
1272        public synchronized void assertCntWaiting(String JavaDoc msg, int cnt) {
1273            // have to wait actively to recognize starvation :-(
1274
for (int i=1; i<10; i++) {
1275                try { wait(20*i*i); } catch (InterruptedException JavaDoc e) {}
1276                if (count == cnt) { // passed
1277
count = 0;
1278                    return;
1279                }
1280            }
1281            assertEquals (msg, cnt, count); // let it fail
1282
}
1283    }
1284
1285    private static class Locker {
1286        boolean ready = false;
1287        
1288        public synchronized void waitOn() {
1289            while (ready == false) {
1290                try {
1291                    wait();
1292                } catch (InterruptedException JavaDoc e) {}
1293            }
1294        }
1295        
1296        public synchronized void notifyOn() {
1297            ready = true;
1298            notifyAll();
1299        }
1300    }
1301    
1302    //
1303
// Our fake lookup
1304
//
1305
public static final class Lkp extends org.openide.util.lookup.AbstractLookup {
1306        private ErrManager err = new ErrManager ();
1307        private org.openide.util.lookup.InstanceContent ic;
1308        
1309        public Lkp () {
1310            this (new org.openide.util.lookup.InstanceContent ());
1311        }
1312        
1313        private Lkp (org.openide.util.lookup.InstanceContent ic) {
1314            super (ic);
1315            ic.add (err);
1316            this.ic = ic;
1317        }
1318        
1319        public static void turn (boolean on) {
1320            Lkp lkp = (Lkp)org.openide.util.Lookup.getDefault ();
1321            if (on) {
1322                lkp.ic.add (lkp.err);
1323            } else {
1324                lkp.ic.remove (lkp.err);
1325            }
1326        }
1327    }
1328    
1329    //
1330
// Manager to delegate to
1331
//
1332
public static final class ErrManager extends org.openide.ErrorManager {
1333        public static final StringBuffer JavaDoc messages = new StringBuffer JavaDoc ();
1334        
1335        private String JavaDoc prefix;
1336        
1337        public ErrManager () {
1338            this (null);
1339        }
1340        public ErrManager (String JavaDoc prefix) {
1341            this.prefix = prefix;
1342        }
1343        
1344        public static ErrManager get () {
1345            return (ErrManager)org.openide.util.Lookup.getDefault ().lookup (ErrManager.class);
1346        }
1347        
1348        public Throwable JavaDoc annotate (Throwable JavaDoc t, int severity, String JavaDoc message, String JavaDoc localizedMessage, Throwable JavaDoc stackTrace, java.util.Date JavaDoc date) {
1349            return t;
1350        }
1351        
1352        public Throwable JavaDoc attachAnnotations (Throwable JavaDoc t, org.openide.ErrorManager.Annotation[] arr) {
1353            return t;
1354        }
1355        
1356        public org.openide.ErrorManager.Annotation[] findAnnotations (Throwable JavaDoc t) {
1357            return null;
1358        }
1359        
1360        public org.openide.ErrorManager getInstance (String JavaDoc name) {
1361            if (
1362                name.startsWith ("org.openide.util.RequestProcessor") ||
1363                name.startsWith("TEST")
1364            ) {
1365                return new ErrManager ('[' + name + ']');
1366            } else {
1367                // either new non-logging or myself if I am non-logging
1368
return new ErrManager ();
1369            }
1370        }
1371        
1372        public void log (int severity, String JavaDoc s) {
1373            lastSeverity = severity;
1374            lastText = s;
1375            if (this != get()) {
1376                messages.append(prefix);
1377                messages.append(s);
1378                messages.append('\n');
1379            }
1380        }
1381        
1382        public void notify (int severity, Throwable JavaDoc t) {
1383            lastThrowable = t;
1384            lastSeverity = severity;
1385        }
1386        private static int lastSeverity;
1387        private static Throwable JavaDoc lastThrowable;
1388        private static String JavaDoc lastText;
1389
1390        public static void assertNotify (int sev, Throwable JavaDoc t) {
1391            assertEquals ("Severity is same", sev, lastSeverity);
1392            assertSame ("Throwable is the same", t, lastThrowable);
1393            lastThrowable = null;
1394            lastSeverity = -1;
1395        }
1396        
1397        public static void assertLog (int sev, String JavaDoc t) {
1398            assertEquals ("Severity is same", sev, lastSeverity);
1399            assertEquals ("Text is the same", t, lastText);
1400            lastText = null;
1401            lastSeverity = -1;
1402        }
1403        
1404    }
1405    
1406}
1407
Popular Tags