Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 0f70c24c1758668998eeed3090971a6df8c7c2cf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
/***********************************************s********************************
 * Copyright (c) 2006, 2012 Wind River Systems and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     Wind River Systems - initial API and implementation
 *******************************************************************************/
package org.eclipse.tcf.debug.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;

import junit.framework.Assert;
import junit.framework.TestCase;

import org.eclipse.tcf.debug.test.util.Callback;
import org.eclipse.tcf.debug.test.util.CallbackCache;
import org.eclipse.tcf.debug.test.util.DataCallback;
import org.eclipse.tcf.debug.test.util.Query;
import org.eclipse.tcf.protocol.Protocol;

/**
 * Tests that exercise the DataCache object.
 */
public class CacheTests extends TestCase {

    TestCache fTestCache;
    DataCallback<Integer> fRetrieveRm;
    
    class TestCache extends CallbackCache<Integer> {
        
        @Override
        protected void retrieve(DataCallback<Integer> rm) {
            synchronized(CacheTests.this) {
                fRetrieveRm = rm;
                CacheTests.this.notifyAll();
            }
        }
        
        @Override
        protected void handleCompleted(Integer data, Throwable error, boolean canceled) {
            // TODO Auto-generated method stub
            super.handleCompleted(data, error, canceled);
        }
        
    }

    class TestQuery extends Query<Integer> {
        @Override
        protected void execute(final DataCallback<Integer> rm) {
            fTestCache.update(new DataCallback<Integer>(rm) {
                @Override
                protected void handleSuccess() {
                    rm.setData(fTestCache.getData());
                    rm.done();
                }
            });
        }
    }
    
    /**
     * There's no rule on how quickly the cache has to start data retrieval
     * after it has been requested.  It could do it immediately, or it could
     * wait a dispatch cycle, etc..
     */
    private void waitForRetrieveRm() {
        synchronized(this) {
            while (fRetrieveRm == null) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    return;
                }
            }
        }
    }
    
    public void setUp() throws ExecutionException, InterruptedException {
        fTestCache = new TestCache();
    }   
    
    public void tearDown() throws ExecutionException, InterruptedException {
        fRetrieveRm = null;
        fTestCache = null;
    }

    private void assertCacheValidWithData(Object data) {
        Assert.assertTrue(fTestCache.isValid());
        Assert.assertEquals(data, fTestCache.getData());
        Assert.assertNull(fTestCache.getError());
    }

    private void assertCacheResetWithoutData() {
        Assert.assertFalse(fTestCache.isValid());
        try {
            fTestCache.getData();
            Assert.fail("Expected an IllegalStateException");
        } catch (IllegalStateException e) {}
        try {
            fTestCache.getError();
            Assert.fail("Expected an IllegalStateException");
        } catch (IllegalStateException e) {}
    }

    private void assertCacheValidWithoutData() {
        Assert.assertTrue(fTestCache.isValid());
        Assert.assertEquals(null, fTestCache.getData());
        Assert.assertNotNull(fTestCache.getError());
        Assert.assertEquals(fTestCache.getError(), ERROR_TARGET_RUNNING);
    }

    private void assertCacheWaiting() {
        Assert.assertFalse(fTestCache.isValid());
        try {
            fTestCache.getData();
            Assert.fail("Expected an IllegalStateException");
        } catch (IllegalStateException e) {}
        try {
            fTestCache.getError();
            Assert.fail("Expected an IllegalStateException");
        } catch (IllegalStateException e) {}
        Assert.assertFalse(fRetrieveRm.isCanceled());
    }

    private void assertCacheInvalidAndWithCanceledRM() {
        Assert.assertFalse(fTestCache.isValid());
        try {
            fTestCache.getData();
            Assert.fail("Expected an IllegalStateException");
        } catch (IllegalStateException e) {}
        try {
            fTestCache.getError();
            Assert.fail("Expected an IllegalStateException");
        } catch (IllegalStateException e) {}
        Assert.assertTrue(fRetrieveRm.isCanceled());
    }

    public void testGet() throws InterruptedException, ExecutionException {
        // Request data from cache
        Query<Integer> q = new TestQuery();
        
        // Check initial state
        Assert.assertFalse(fTestCache.isValid());

        q.invoke();
        
        // Wait until the cache requests the data.
        waitForRetrieveRm();
        
        // Check state while waiting for data
        Assert.assertFalse(fTestCache.isValid());

        // Complete the cache's retrieve data request.
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
                fRetrieveRm.setData(1);
                fRetrieveRm.done();
    
                // Check that the data is available in the cache immediately
                // (in the same dispatch cycle).
                Assert.assertEquals(1, (int)fTestCache.getData());
                Assert.assertTrue(fTestCache.isValid());
            }
        });
        
        Assert.assertEquals(1, (int)q.get());
        
        // Re-check final state
        assertCacheValidWithData(1);
    }

    public void testGetWithCompletionDelay() throws InterruptedException, ExecutionException {
        // Check initial state
        Assert.assertFalse(fTestCache.isValid());
        
        // Request data from cache
        Query<Integer> q = new TestQuery();
        q.invoke();
        
        // Wait until the cache starts data retrieval.
        waitForRetrieveRm();

        // Check state while waiting for data
        Assert.assertFalse(fTestCache.isValid());

        // Set the data to the callback  
        Protocol.invokeLater(
            100, 
            new Runnable() {
                public void run() {
                    fRetrieveRm.setData(1);
                    fRetrieveRm.done();
                    
                }
            });
        
        Assert.assertEquals(1, (int)q.get());

        // Check final state
        assertCacheValidWithData(1);
    }

    public void testGetWithTwoClients() throws InterruptedException, ExecutionException {
        // Check initial state
        Assert.assertFalse(fTestCache.isValid());
        
        // Request data from cache
        Query<Integer> q1 = new TestQuery();
        q1.invoke();

        // Request data from cache again
        Query<Integer> q2 = new TestQuery(); 
        q2.invoke();
        
        // Wait until the cache starts data retrieval.
        waitForRetrieveRm();

        // Check state while waiting for data
        Assert.assertFalse(fTestCache.isValid());

        // Set the data to the callback  
        Protocol.invokeLater(new Runnable() {
            public void run() {
                fRetrieveRm.setData(1);
                fRetrieveRm.done();
                
            }
        });
        
        Assert.assertEquals(1, (int)q1.get());
        Assert.assertEquals(1, (int)q2.get());

        // Check final state
        assertCacheValidWithData(1);
    }

    public void testGetWithManyClients() throws InterruptedException, ExecutionException {
        // Check initial state
        Assert.assertFalse(fTestCache.isValid());
        
        // Request data from cache
        List<Query<Integer>> qList = new ArrayList<Query<Integer>>(); 
        for (int i = 0; i < 10; i++) {
            Query<Integer> q = new TestQuery();
            q.invoke();
            qList.add(q);
        }
        // Wait until the cache starts data retrieval.
        waitForRetrieveRm();

        // Check state while waiting for data
        Assert.assertFalse(fTestCache.isValid());

        // Set the data to the callback  
        Protocol.invokeLater(new Runnable() {
            public void run() {
                fRetrieveRm.setData(1);
                fRetrieveRm.done();
                
            }
        });
        
        for (Query<Integer> q : qList) {
            Assert.assertEquals(1, (int)q.get());            
        }
        
        // Check final state
        assertCacheValidWithData(1);
    }
    
    private static final Exception ERROR_TARGET_RUNNING = new Exception("Target is running");
    
	// DISABLE TESTS
	//
	// We say a cache is "disabled" when its most recent attempt to update from
	// the source failed. Also, a cache may make itself disabled as a reaction
	// to a state change notification from its source (e.g., the target
	// resumed). In either case, the cache is in the valid state but it has no
	// data and the status reflects an error. Keep in mind that the 'valid'
	// state is not a reflection of the quality of the data, but merely whether
	// the cache object's representation of the data is stale or
	// not. A transaction that uses a "disabled" cache object will simply fail;
	// it will not ask the cache to update its data from the source. Only a
	// change in the source's state would cause the cache to put itself back in
	// the invalid state, thus opening the door to another update.

	/**
	 * Test behavior when a cache object is asked to update itself after it has
	 * become "disabled". Since a "disabled" cache is in the valid state, a
	 * request for it to update from the source should be ignored.  However, the 
	 * client callback is not completed until next state change in cache.
	 */
    public void testDisableBeforeRequest() throws InterruptedException, ExecutionException {
        // Disable the cache
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
                fTestCache.set(null, ERROR_TARGET_RUNNING, true);
            }
        });
        
        assertCacheValidWithoutData();
        
        // Try to request data from cache
        Query<Integer> q = new TestQuery();
        q.invoke();
        
        Thread.sleep(100);
        
        // Retrieval should never have been made.
        Assert.assertEquals(null, fRetrieveRm);

        // Disable the cache.  This should trigger the qery to complete.
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
                fTestCache.set(null, new Throwable("Cache invalid"), false);
            }
        });

        // The cache has no data so the query should have failed  
        try {
            q.get();
            Assert.fail("expected an exeption");
        } catch (ExecutionException e) {
            // expected the exception
        }
    }

	/**
	 * Test behavior when a cache object goes into the "disabled" state while an
	 * update request is ongoing. The subsequent completion of the request should 
	 * have no effect on the  cache
	 */
    public void testDisableWhilePending() throws InterruptedException, ExecutionException {
        // Request data from cache
        Query<Integer> q = new TestQuery();
        q.invoke();

        // Disable the cache
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
                fTestCache.set(null, ERROR_TARGET_RUNNING, true);
            }
        });
        
        assertCacheValidWithoutData();

		// Complete the retrieve RM. Note that the disabling of the cache above
		// disassociates it from its retrieval RM. Thus regardless of how that
		// request completes, it does not affect the cache.
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
                fRetrieveRm.setData(1);
                fRetrieveRm.done();
            }
        });
        
        // Validate that cache is still disabled without data.
        assertCacheValidWithoutData();
    }

	/**
	 * Test behavior when a cache object goes into the "disabled" state while
	 * it's in the valid state. The cache remains in the valid state but it
	 * loses its data and obtains an error status.
	 */
    public void testDisableWhileValid() throws InterruptedException, ExecutionException {
        // Request data from cache
        Query<Integer> q = new TestQuery(); 
        q.invoke();
        
        // Wait until the cache starts data retrieval.
        waitForRetrieveRm();
        
        // Complete the request
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
                fRetrieveRm.setData(1);
                fRetrieveRm.done();
            }
        });

        Assert.assertEquals(Integer.valueOf(1), q.get());
        
        // Disable the cache
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
                fTestCache.set(null, ERROR_TARGET_RUNNING, true);
            }
        });
        
        // Check final state
        assertCacheValidWithoutData();
    }

    public void testSetWithValue() throws InterruptedException, ExecutionException {
        // Disable the cache
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
                fTestCache.set(2, null, true);
            }
        });
        
        // Validate that cache is disabled without data.
        assertCacheValidWithData(2);
    }
    
    
    public void testCancelWhilePending() throws InterruptedException, ExecutionException {
        // Request data from cache 
        Query<Integer> q = new TestQuery();
        q.invoke();

        // Wait until the cache starts data retrieval.
        waitForRetrieveRm();

        // Cancel the client request
        q.cancel(true);
        try {
            q.get();
            Assert.fail("Expected a cancellation exception");
        } catch (CancellationException e) {} // Expected exception;
        
        assertCacheInvalidAndWithCanceledRM();

		// Simulate the retrieval completing successfully despite the cancel
		// request. Perhaps the retrieval logic isn't checking the RM status.
		// Even if it is checking, it may have gotten passed its last checkpoint
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
                fRetrieveRm.setData(1);
                fRetrieveRm.done();
            }
        });

        // Validate that cache didn't accept the result after its RM was canceled  
        assertCacheInvalidAndWithCanceledRM();
    }

    public void testCancelWhilePending2() throws InterruptedException, ExecutionException {
        // Request data from cache 
        Query<Integer> q = new TestQuery();
        q.invoke();

        // Wait until the cache starts data retrieval.
        waitForRetrieveRm();

        // Cancel the client request
        q.cancel(true);
        try {
            q.get();
            Assert.fail("Expected a cancellation exception");
        } catch (CancellationException e) {} // Expected exception;
        
        assertCacheInvalidAndWithCanceledRM();

		// Simulate retrieval logic that is regularly checking the RM's cancel
		// status and has discovered that the request has been canceled. It
		// technically does not need to explicitly set a cancel status object in
		// the RM, thanks to RequestMonitor.getStatus() automatically returning
		// Status.CANCEL_STATUS when its in the cancel state. So here we
		// simulate the retrieval logic just aborting its operations and
		// completing the RM. Note that it hasn't provided the data to the
		// cache. 
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
                fRetrieveRm.done();
            }
        });

        assertCacheInvalidAndWithCanceledRM();
    }

    public void testCancelWhilePending3() throws InterruptedException, ExecutionException {
        // Request data from cache 
        Query<Integer> q = new TestQuery();
        q.invoke();

        // Wait until the cache starts data retrieval.
        waitForRetrieveRm();

        // Cancel the client request
        q.cancel(true);
        try {
            q.get();
            Assert.fail("Expected a cancellation exception");
        } catch (CancellationException e) {} // Expected exception;
        
        assertCacheInvalidAndWithCanceledRM();

		// Simulate retrieval logic that is regularly checking the RM's cancel
		// status and has discovered that the request has been canceled. It
		// aborts its processing, sets STATUS.CANCEL_STATUS in the RM and
		// completes it. 
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
            	fRetrieveRm.setError(new CancellationException());
                fRetrieveRm.done();
            }
        });

        // Validate that cache didn't accept the result after its RM was canceled
        assertCacheInvalidAndWithCanceledRM();
    }

    public void testCancelWhilePendingWithoutClientNotification() throws InterruptedException, ExecutionException {
	    final boolean canceledCalled[] = new boolean[] { false };
	    
	    fTestCache = new TestCache() {
	        protected synchronized void canceled() {
	            canceledCalled[0] = true;
	        };
	    };
	    
        // Request data from cache 
        Query<Integer> q = new Query<Integer>() { 
            @Override
            protected void execute(final DataCallback<Integer> rm) {
                
                fTestCache.update(new Callback(rm) {
                    @Override
                    public synchronized void addCancelListener(ICanceledListener listener) {
                        // Do not add the cancel listener so that the cancel request is not
                        // propagated to the cache.
                    }
                    
                    @Override
                    protected void handleSuccess() {
                        rm.setData(fTestCache.getData());
                        rm.done();
                    }
                });
            }
        };
        q.invoke();

        // Wait until the cache starts data retrieval.
        waitForRetrieveRm();

        // Cancel the client request
        q.cancel(true);
        
        assertCacheInvalidAndWithCanceledRM();
        
        // AbstractCache.canceled() should be called after isCanceled() 
        // discovers that the client has canceled its request.  The canceled() method is 
        // called in a separate dispatch cycle, so we have to wait one cycle of the executor 
        // after is canceled is called.
        fRetrieveRm.isCanceled();
        Protocol.invokeAndWait(new Runnable() { public void run() {} }); 
        Assert.assertTrue(canceledCalled[0]);        

        try {
            q.get();
            Assert.fail("Expected a cancellation exception");
        } catch (CancellationException e) {} // Expected exception;


        // Completed the retrieve RM
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
                fRetrieveRm.setData(1);
                fRetrieveRm.done();
            }
        });

        // Validate that cache didn't accept the result after its RM was canceled
        assertCacheInvalidAndWithCanceledRM();
    }

    /**
     * This test forces a race condition where a client that requested data 
     * cancels.  While shortly after a second client starts a new request.
     * The first request's cancel should not interfere with the second 
     * request.  
     */
    public void testCancelAfterCompletedRaceCondition() throws InterruptedException, ExecutionException {

        // Create a client request with a badly behaved cancel implementation.
        final Callback[] rmBad = new Callback[1] ;
        final boolean qBadCanceled[] = new boolean[] { false };
        Query<Integer> qBad = new Query<Integer>() { 
            @Override
            protected void execute(final DataCallback<Integer> rm) {
                rmBad[0] = new Callback(rm) {
                    @Override
                    public synchronized void removeCancelListener(ICanceledListener listener) {
                        // Do not add the cancel listener so that the cancel request is not
                        // propagated to the cache.
                    }
                    
                    @Override
                    public void cancel() {
                        if (qBadCanceled[0]) {
                            super.cancel();
                        }
                    }
                    
                    @Override
                    public synchronized boolean isCanceled() {
                        return qBadCanceled[0];
                    }
                    
                    @Override
                    public synchronized void done() {
                        // Avoid clearing cancel listeners list
                    };
                    
                    @Override
					protected void handleSuccess() {
                        rm.setData(fTestCache.getData());
                        rm.done();
                    };
                };
                
                fTestCache.update(rmBad[0]);
            }
        };
        qBad.invoke();

        // Wait until the cache starts data retrieval.
        waitForRetrieveRm();

        // Reset the cache
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
                fRetrieveRm = null;
                fTestCache.set(null, null, true);
                fTestCache.reset();
            }
        });
        
        Query<Integer> qGood = new TestQuery();
        qGood.invoke();

        // Wait until the cache starts data retrieval.
        waitForRetrieveRm();
        
        qBadCanceled[0] = true;
        rmBad[0].cancel();

        Assert.assertFalse(fRetrieveRm.isCanceled());
        
        // Completed the retrieve RM
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
                fRetrieveRm.setData(1);
                fRetrieveRm.done();
            }
        });

        qGood.get();
        
        assertCacheValidWithData(1);
    }
    
    public void testCancelWhilePendingWithTwoClients() throws InterruptedException, ExecutionException {
    	
		// Request data from cache. Use an additional invokeAndWait to 
        // ensure both update requests are initiated before we wait 
        // for retrieval to start
        Query<Integer> q1 = new TestQuery();
        q1.invoke();   
        Protocol.invokeAndWait(new Runnable() { public void run() {} }); 

        // Request data from cache again
        Query<Integer> q2 = new TestQuery();
        q2.invoke();
        Protocol.invokeAndWait(new Runnable() { public void run() {} });         

        // Wait until the cache starts data retrieval.
        waitForRetrieveRm();

        // Cancel the first client request
        q1.cancel(true);
        try {
            q1.get();
            Assert.fail("Expected a cancellation exception");
        } catch (CancellationException e) {} // Expected exception;
        assertCacheWaiting();

        // Cancel the second request
        q2.cancel(true);
        try {
            q2.get();
            Assert.fail("Expected a cancellation exception");
        } catch (CancellationException e) {} // Expected exception;

        assertCacheInvalidAndWithCanceledRM();

        // Completed the retrieve RM
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
                fRetrieveRm.setData(1);
                fRetrieveRm.done();
            }
        });

        // Validate that cache didn't accept the result after its RM was canceled
        assertCacheInvalidAndWithCanceledRM();
    }

    public void testCancelWhilePendingWithManyClients() throws InterruptedException, ExecutionException {
        // Request data from cache 
        List<Query<Integer>> qList = new ArrayList<Query<Integer>>(); 
        for (int i = 0; i < 10; i++) {
            Query<Integer> q = new TestQuery();
            q.invoke();   
            Protocol.invokeAndWait(new Runnable() { public void run() {} }); 
            qList.add(q);
        }

        // Wait until the cache starts data retrieval.
        waitForRetrieveRm();

        // Cancel some client requests
        int[] toCancel = new int[] { 0, 2, 5, 9};
        for (int i = 0; i < toCancel.length; i++) {
            
            // Cancel request and verify that its canceled
            Query<Integer> q = qList.get(toCancel[i]);
            q.cancel(true);
            try {
                q.get();
                Assert.fail("Expected a cancellation exception");
            } catch (CancellationException e) {} // Expected exception;
            qList.set(toCancel[i], null);
            
            assertCacheWaiting();
        }

        // Replace canceled requests with new ones
        for (int i = 0; i < toCancel.length; i++) {
            Query<Integer> q = new TestQuery();
            q.invoke();   
            Protocol.invokeAndWait(new Runnable() { public void run() {} }); 
            qList.set(toCancel[i], q);
            assertCacheWaiting();
        }

        // Now cancel all requests
        for (int i = 0; i < (qList.size() - 1); i++) {
            // Validate that cache is still waiting and is not canceled
            assertCacheWaiting();
            qList.get(i).cancel(true);
        }
        qList.get(qList.size() - 1).cancel(true);
        assertCacheInvalidAndWithCanceledRM();

        // Completed the retrieve RM
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
                fRetrieveRm.setData(1);
                fRetrieveRm.done();
            }
        });

        // Validate that cache didn't accept the result after its RM was canceled
        assertCacheInvalidAndWithCanceledRM();
    }

    public void testResetWhileValid() throws InterruptedException, ExecutionException {
        // Request data from cache
        Query<Integer> q = new TestQuery();
        q.invoke();

        // Wait until the cache starts data retrieval.
        waitForRetrieveRm();
        
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
                fRetrieveRm.setData(1);
                fRetrieveRm.done();
            }
        });

        q.get();
        
        // Disable cache
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
                fTestCache.reset();
            }
        });
        
        // Check final state
        assertCacheResetWithoutData();
    }
    
    public void testSetAndReset() throws InterruptedException, ExecutionException {
        fTestCache = new TestCache() {
            @Override
            protected void handleCompleted(Integer data, Throwable error, boolean canceled) {
                if (!canceled) {
                    // USE 'false' for valid argument.  Cache should be left in 
                    // invalid state.
                    set(data, error, false);
                }
            }
        };
        
        // Request data from cache
        Query<Integer> q = new TestQuery();
        q.invoke();

        // Wait until the cache starts data retrieval.
        waitForRetrieveRm();
        
        Protocol.invokeAndWait(new Runnable() {
            public void run() {
                fRetrieveRm.setData(1);
                fRetrieveRm.done();
            }
        });

        // Query should complete with the data from request monitor.
        try {
            q.get();
            Assert.fail("Expected InvalidCacheException");
        } catch(ExecutionException e) {}

        // No need to disable cache, it should already be disabled.
        
        // Check final state
        assertCacheResetWithoutData();
    }

}

Back to the top