summaryrefslogtreecommitdiff
path: root/tests/tests/libcorefileio/src/android/cts/FileChannelInterProcessLockTest.java
blob: e5b25c93b9aba15ae48d9e1289ef679b8ebc5e7f (plain)
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
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

package android.cts;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Debug;
import android.os.Environment;
import android.test.AndroidTestCase;

import java.io.File;
import java.io.IOException;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;

import static java.util.concurrent.TimeUnit.SECONDS;

@SuppressWarnings("deprecation")
public class FileChannelInterProcessLockTest extends AndroidTestCase {

    /** The directory where file locks are created */
    final static String DIR_NAME = "CtsFileIOTest";

    /** The name of the file used when acquiring a lock. */
    final static String FILE_NAME = "file";

    /** The position in the lock file used when acquiring a region lock. */
    final static int LOCK_POSITION = 10;

    /** The extent of the lock file locked when acquiring a region lock. */
    final static int LOCK_SIZE = 10;

    /**
     * This is the maximum waiting time in seconds for the test to wait for a response from
     * the service. This provides ample amount of time for the service to receive the request from
     * the test, then act, and respond back.
     */
    final static int MAX_WAIT_TIME = 20;

    @Override
    public void tearDown() throws Exception {
        stopService();
        super.tearDown();
    }

    public void test_tryLock_syncChannel() throws Exception {
        doTest_tryLock(ChannelType.SYNC_CHANNEL, ChannelType.SYNC_CHANNEL);
    }

    public void test_tryLock_asyncChannel() throws Exception {
        doTest_tryLock(ChannelType.ASYNC_CHANNEL, ChannelType.ASYNC_CHANNEL);
    }

    public void test_tryLock_differentChannelTypes() throws Exception {
        checkTryLockBehavior(LockType.TRY_LOCK, LockType.TRY_LOCK,
                ChannelType.SYNC_CHANNEL, ChannelType.ASYNC_CHANNEL,
                false /* expectToGetLock */);

        checkTryLockBehavior(LockType.TRY_LOCK, LockType.TRY_LOCK,
                ChannelType.ASYNC_CHANNEL, ChannelType.SYNC_CHANNEL,
                false /* expectToGetLock */);
    }

    /**
     * java.nio.channels.[Asynchronouse]FileChannel#tryLock()
     *
     * Obtains a remote lock, then attempts to acquire a local lock on the same file,
     * and checks the behavior.
     * checkTryLockBehavior(localLockType, remoteLockType, expectedLocalLockResult)
     * expectedLockLockResult: {@code true} if the returned lock should be valid,
     * {@code false} otherwise.
     */
    private void doTest_tryLock(ChannelType localChannelType, ChannelType remoteChannelType)
            throws Exception {

        checkTryLockBehavior(LockType.TRY_LOCK, LockType.TRY_LOCK,
                localChannelType, remoteChannelType, false /* expectToGetLock */);
        checkTryLockBehavior(LockType.TRY_LOCK, LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, false /* expectToGetLock */);
        checkTryLockBehavior(LockType.TRY_LOCK, LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, false /* expectToGetLock */);
        checkTryLockBehavior(LockType.TRY_LOCK, LockType.LOCK,
                localChannelType, remoteChannelType, false /* expectToGetLock */);
        checkTryLockBehavior(LockType.TRY_LOCK, LockType.LOCK_ON_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, false /* expectToGetLock */);
        checkTryLockBehavior(LockType.TRY_LOCK, LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, false /* expectToGetLock */);
    }

    public void test_tryLockJJZ_Exclusive_syncChannel() throws Exception {
        doTest_tryLockJJZ_Exclusive(ChannelType.SYNC_CHANNEL, ChannelType.SYNC_CHANNEL);
    }

    public void test_tryLockJJZ_Exclusive_asyncChannel() throws Exception {
        doTest_tryLockJJZ_Exclusive(ChannelType.ASYNC_CHANNEL, ChannelType.ASYNC_CHANNEL);
    }

    public void test_tryLockJJZ_Exclusive_differentChannelTypes() throws Exception {
        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK, LockType.TRY_LOCK,
                ChannelType.SYNC_CHANNEL, ChannelType.ASYNC_CHANNEL, false /* expectToGetLock */);
        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK, LockType.TRY_LOCK,
                ChannelType.ASYNC_CHANNEL, ChannelType.SYNC_CHANNEL, false /* expectToGetLock */);

        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK,
                ChannelType.SYNC_CHANNEL, ChannelType.ASYNC_CHANNEL, true /* expectToGetLock */);
        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK,
                ChannelType.ASYNC_CHANNEL, ChannelType.SYNC_CHANNEL, true /* expectToGetLock */);
    }

    /**
     * java.nio.channels.[Asynchronous]FileChannel#tryLock(long, long, boolean)
     *
     * Obtains a remote lock, then attempts to acquire a local lock on the same file,
     * and checks the behavior.
     * checkTryLockBehavior(localLockType, remoteLockType, expectedLocalLockResult)
     * expectedLockLockResult: {@code true} if the returned lock should be valid,
     * {@code false} otherwise.
     */
    private void doTest_tryLockJJZ_Exclusive(ChannelType localChannelType,
            ChannelType remoteChannelType) throws Exception {
        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK, LockType.TRY_LOCK,
                localChannelType, remoteChannelType, false /* expectToGetLock */);
        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, false /* expectToGetLock */);
        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, true /* expectToGetLock */);
        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, false /* expectToGetLock */);
        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, true /* expectToGetLock */);

        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK, LockType.LOCK,
                localChannelType, remoteChannelType, false /* expectToGetLock */);
        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.LOCK_ON_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, false /* expectToGetLock */);
        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, true /* expectToGetLock */);
        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, false /* expectToGetLock */);
        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, true /* expectToGetLock */);
    }

    public void test_tryLockJJZ_Shared_syncChannel() throws Exception {
        doTest_tryLockJJZ_Shared(ChannelType.SYNC_CHANNEL, ChannelType.SYNC_CHANNEL);
    }

    public void test_tryLockJJZ_Shared_asyncChannel() throws Exception {
        doTest_tryLockJJZ_Shared(ChannelType.ASYNC_CHANNEL, ChannelType.ASYNC_CHANNEL);
    }

    public void test_tryLockJJZ_Shared_differentChannelTypes() throws Exception {
        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK, LockType.TRY_LOCK,
                ChannelType.SYNC_CHANNEL, ChannelType.ASYNC_CHANNEL, false /* expectToGetLock */);
        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK, LockType.TRY_LOCK,
                ChannelType.ASYNC_CHANNEL, ChannelType.SYNC_CHANNEL, false /* expectToGetLock */);

        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK,
                ChannelType.SYNC_CHANNEL, ChannelType.ASYNC_CHANNEL, true /* expectToGetLock */);
        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK,
                ChannelType.ASYNC_CHANNEL, ChannelType.SYNC_CHANNEL, true /* expectToGetLock */);
    }

    /**
     * java.nio.channels.[Asynchronous]FileChannel#tryLock(long, long, boolean)
     *
     * Obtains a remote lock, then attempts to acquire a local lock on the same file,
     * and checks the behavior.
     * checkTryLockBehavior(localLockType, remoteLockType, expectedLocalLockResult)
     * expectedLockLockResult: {@code true} if the returned lock should be valid,
     * {@code false} otherwise.
     */
    private void doTest_tryLockJJZ_Shared(ChannelType localChannelType,
            ChannelType remoteChannelType) throws Exception {
        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK, LockType.TRY_LOCK,
                localChannelType, remoteChannelType, false /* expectToGetLock */);
        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, false /* expectToGetLock */);
        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, true /* expectToGetLock */);
        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, true /* expectToGetLock */);
        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, true /* expectToGetLock */);

        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK, LockType.LOCK,
                localChannelType, remoteChannelType, false /* expectToGetLock */);
        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.LOCK_ON_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, false /* expectToGetLock */);
        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, true /* expectToGetLock */);
        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, true /* expectToGetLock */);
        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
                LockType.SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, true /* expectToGetLock */);
    }

    public void test_lock_syncChannel() throws Exception {
        doTest_lock(ChannelType.SYNC_CHANNEL, ChannelType.SYNC_CHANNEL);
    }

    public void test_lock_asyncChannel() throws Exception {
        doTest_lock(ChannelType.ASYNC_CHANNEL, ChannelType.ASYNC_CHANNEL);
    }

    public void test_lock_differentChannelTypes() throws Exception {
        checkLockBehavior(LockType.LOCK, LockType.LOCK,
                ChannelType.SYNC_CHANNEL, ChannelType.ASYNC_CHANNEL, true /* expectToWait */);
        checkLockBehavior(LockType.LOCK, LockType.LOCK,
                ChannelType.ASYNC_CHANNEL, ChannelType.SYNC_CHANNEL, true /* expectToWait */);

        checkLockBehavior(LockType.LOCK, LockType.TRY_LOCK,
                ChannelType.SYNC_CHANNEL, ChannelType.ASYNC_CHANNEL, true /* expectToWait */);
        checkLockBehavior(LockType.LOCK, LockType.TRY_LOCK,
                ChannelType.ASYNC_CHANNEL, ChannelType.SYNC_CHANNEL, true /* expectToWait */);
    }

    /**
     * java.nio.channels.[Asynchronous]FileChannel#lock()
     *
     * Obtains a remote lock, then attempts to acquire a local lock on the same file,
     * and checks the behavior.
     * checkTryLockBehavior(localLockType, remoteLockType, expectedLocalLockResult)
     * expectedLockLockResult: {@code true} if it blocks the local thread, {@code false} otherwise.
     */
    private void doTest_lock(ChannelType localChannelType, ChannelType remoteChannelType)
            throws Exception {
        checkLockBehavior(LockType.LOCK, LockType.LOCK,
                localChannelType, remoteChannelType, true /* expectToWait */);
        checkLockBehavior(LockType.LOCK, LockType.LOCK_ON_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, true /* expectToWait */);
        checkLockBehavior(LockType.LOCK, LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, true /* expectToWait */);

        checkLockBehavior(LockType.LOCK, LockType.TRY_LOCK,
                localChannelType, remoteChannelType, true /* expectToWait */);
        checkLockBehavior(LockType.LOCK, LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, true /* expectToWait */);
        checkLockBehavior(LockType.LOCK, LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, true /* expectToWait */);
    }

    public void test_lockJJZ_Exclusive_syncChannel() throws Exception {
        doTest_lockJJZ_Exclusive(ChannelType.SYNC_CHANNEL, ChannelType.SYNC_CHANNEL);
    }

    public void test_lockJJZ_Exclusive_asyncChannel() throws Exception {
        doTest_lockJJZ_Exclusive(ChannelType.ASYNC_CHANNEL, ChannelType.ASYNC_CHANNEL);
    }

    public void test_lockJJZ_Exclusive_differentChannelTypes() throws Exception {
        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK, LockType.LOCK,
                ChannelType.SYNC_CHANNEL, ChannelType.ASYNC_CHANNEL, true /* expectToWait */);
        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK, LockType.LOCK,
                ChannelType.ASYNC_CHANNEL, ChannelType.SYNC_CHANNEL, true /* expectToWait */);

        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK,
                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,
                ChannelType.SYNC_CHANNEL, ChannelType.ASYNC_CHANNEL, false /* expectToWait */);
        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK,
                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,
                ChannelType.ASYNC_CHANNEL, ChannelType.SYNC_CHANNEL, false /* expectToWait */);
    }

    /**
     * java.nio.channels.[Asynchronous]FileChannel#lock(long, long, boolean)
     *
     * Obtains a remote lock, then attempts to acquire a local lock on the same file,
     * and checks the behavior.
     * checkTryLockBehavior(localLockType, remoteLockType, expectedLocalLockResult)
     * expectedLockLockResult: {@code true} if blocks the local thread, {@code false} otherwise.
     */
    private void doTest_lockJJZ_Exclusive(ChannelType localChannelType,
            ChannelType remoteChannelType) throws Exception {
        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK, LockType.LOCK,
                localChannelType, remoteChannelType, true /* expectToWait */);
        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK, LockType.LOCK_ON_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, true /* expectToWait */);
        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK,
                LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, true /* expectToWait */);
        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK,
                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, false /* expectToWait */);
        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK,
                LockType.SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, false /* expectToWait */);

        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK, LockType.TRY_LOCK,
                localChannelType, remoteChannelType, true /* expectToWait */);
        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK, LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, true /* expectToWait */);
        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK,
                LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, true /* expectToWait */);
        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK,
                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, false /* expectToWait */);
        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK,
                LockType.SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, false /* expectToWait */);
    }

    public void test_lockJJZ_Shared_syncChannel() throws Exception {
        doTest_lockJJZ_Shared(ChannelType.SYNC_CHANNEL, ChannelType.SYNC_CHANNEL);
    }

    public void test_lockJJZ_Shared_asyncChannel() throws Exception {
        doTest_lockJJZ_Shared(ChannelType.ASYNC_CHANNEL, ChannelType.ASYNC_CHANNEL);
    }

    public void test_lockJJZ_Shared_differentChannelTypes() throws Exception {
        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK, LockType.LOCK,
                ChannelType.SYNC_CHANNEL, ChannelType.ASYNC_CHANNEL, true /* expectToWait */);
        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK, LockType.LOCK,
                ChannelType.ASYNC_CHANNEL, ChannelType.SYNC_CHANNEL, true /* expectToWait */);

        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,
                ChannelType.SYNC_CHANNEL, ChannelType.ASYNC_CHANNEL, false /* expectToWait */);
        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,
                ChannelType.ASYNC_CHANNEL, ChannelType.SYNC_CHANNEL, false /* expectToWait */);
    }

    /**
     * java.nio.channels.[Asynchronous]FileChannel#lock(long, long, boolean)
     *
     * Obtains a remote lock, then attempts to acquire a local lock on the same file,
     * and checks the behavior.
     * checkTryLockBehavior(localLockType, remoteLockType, expectedLocalLockResult)
     * expectedLockLockResult: {@code true} if blocks the local thread, {@code false} otherwise.
     */
    private void doTest_lockJJZ_Shared(ChannelType localChannelType,
            ChannelType remoteChannelType) throws Exception {
        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK, LockType.LOCK,
                localChannelType, remoteChannelType, true /* expectToWait */);
        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
                LockType.LOCK_ON_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, true /* expectToWait */);
        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
                LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, false /* expectToWait */);
        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, false /* expectToWait */);
        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
                LockType.SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK,
                localChannelType, remoteChannelType, false /* expectToWait */);

        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK, LockType.TRY_LOCK,
                localChannelType, remoteChannelType, true /* expectToWait */);
        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
                LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, true /* expectToWait */);
        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
                LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, false /* expectToWait */);
        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, false /* expectToWait */);
        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
                LockType.SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,
                localChannelType, remoteChannelType, false /* expectToWait */);
    }

    /**
     * Checks the behavior of java.nio.Channels.[Asynchronous]FileChannel#tryLock()
     * and #tryLock(J, J, Z)
     *
     * @param localLockType the type of lock to be acquired by the test.
     * @param remoteLockType the type of lock to be acquired by the remote service.
     * @param localChannelType the type of the channel that acquires the lock locally.
     * @param remoteChannelType the type of channel that acquires the lock remotely.
     * @param expectToGetLock {@code true}, if the lock should be acquired even when the
     *         service holds a {@code remoteLockType} lock, false otherwise.
     */
    private void checkTryLockBehavior(LockType localLockType, LockType remoteLockType,
            ChannelType localChannelType, ChannelType remoteChannelType,
            boolean expectToGetLock) throws Exception {
        try {
            IntentReceiver.resetReceiverState();

            // Request that the remote lock be obtained.
            getContext().startService(new Intent(getContext(), LockHoldingService.class)
                    .putExtra(LockHoldingService.LOCK_TYPE_KEY, remoteLockType)
                    .putExtra(LockHoldingService.CHANNEL_TYPE_KEY, remoteChannelType));

            // Wait for a signal that the remote lock is definitely held.
            assertTrue(IntentReceiver.lockHeldLatch.await(MAX_WAIT_TIME, SECONDS));

            // Try to acquire the local lock in all cases and check whether it could be acquired or
            // not as expected.
            if (expectToGetLock) {
                FileLock fileLock = acquire(getContext(), localLockType, localChannelType);
                assertNotNull(fileLock);
                assertTrue(fileLock.isValid());
            } else {
                assertNull(acquire(getContext(), localLockType, localChannelType));
            }
            // Release the remote lock.
        } finally {
            stopService();
        }
    }

    /**
     * Checks the java.nio.channels.[Asynchronous]FileChannel.lock()/lock(J, J, Z) behavior.
     *
     * @param localLockType type of lock to be acquired by the tes.t
     * @param remoteLockType type of lock to be acquired by the remote service..
     * @param localChannelType the type of the channel that acquires the lock locally.
     * @param remoteChannelType the type of channel that acquires the lock remotely.
     * @param expectToWait {@code true}, if the local thread must wait for the remote
     *         service to release the lock, {@code false} otherwise.
     */
    private void checkLockBehavior(LockType localLockType, LockType remoteLockType,
            ChannelType localChannelType, ChannelType remoteChannelType,
            boolean expectToWait) throws Exception {
        try {
            IntentReceiver.resetReceiverState();

            // The amount of time the remote service should hold lock.
            long remoteLockHoldTimeMillis = 7000;

            // The amount of time test should get to try to acquire the lock.
            long sufficientOverlappingTimeInMillis = 2000;

            // This is the allowable delta in the time between the time recorded after the service
            // released the lock and the time recorded after the test obtained the lock.
            long lockReleasedAndReacquiredTimeDeltaInMillis = 1000;

            // Tell the service to acquire a remote lock.
            Intent sendIntent = new Intent(getContext(), LockHoldingService.class)
                    .putExtra(LockHoldingService.TIME_TO_HOLD_LOCK_KEY, remoteLockHoldTimeMillis)
                    .putExtra(LockHoldingService.LOCK_TYPE_KEY, remoteLockType)
                    .putExtra(LockHoldingService.CHANNEL_TYPE_KEY, remoteChannelType)
                    .putExtra(LockHoldingService.LOCK_BEHAVIOR_RELEASE_AND_NOTIFY_KEY, true);

            getContext().startService(sendIntent);

            // Wait for the service to hold the lock and notify for the same.
            assertTrue("No remote lock held notification",
                    IntentReceiver.lockHeldLatch.await(MAX_WAIT_TIME, SECONDS));

            long localLockNotObtainedTime = System.currentTimeMillis();

            // Acquire the lock locally.
            FileLock fileLock = acquire(getContext(), localLockType, localChannelType);
            long localLockObtainedTime = System.currentTimeMillis();

            // Wait until the remote lock has definitely been released.
            assertTrue("No remote lock release notification",
                    IntentReceiver.lockReleasedLatch.await(MAX_WAIT_TIME, SECONDS));

            Bundle remoteLockReleasedBundle = IntentReceiver.lockReleasedBundle;
            long remoteLockNotReleasedTime =
                    remoteLockReleasedBundle.getLong(LockHoldingService.LOCK_NOT_YET_RELEASED_TIMESTAMP);
            long remoteLockReleasedTime =
                    remoteLockReleasedBundle.getLong(LockHoldingService.LOCK_DEFINITELY_RELEASED_TIMESTAMP);

            // We want the test to be notified well before the service releases the lock, so that
            // we can be sure that it tried obtaining the lock before the service actually released it.
            // Therefore, a two seconds time interval provides the test to get prepare and try to obtain
            // the lock. If this fails, it doesn't mean they definitely didn't overlap
            // but we can't be sure and the test may not be valid. This is why we hold the lock
            // remotely for a long time compared to the delays we expect for intents to propagate
            // between processes.
            assertTrue(String.format("Remote lock release start (%d), " +
                        "too soon after local lock notification time (%d). " +
                        "Need at least %d ms",
                        remoteLockReleasedTime,
                        localLockNotObtainedTime,
                        sufficientOverlappingTimeInMillis
                    ),
                    remoteLockNotReleasedTime - localLockNotObtainedTime >
                    sufficientOverlappingTimeInMillis);

            if (expectToWait) {

                // The remoteLockReleaseTime is captured after the lock was released by the
                // service. The localLockObtainedTime is captured after the lock was obtained by this
                // thread. Therefore, there is a degree of slop inherent in the two times. We assert
                // that they are "close" to each other, but we cannot assert any ordering.
                assertTrue(String.format("Local lock obtained (%d) too long " +
                            "from remote lock release time (%d). " +
                            "Expected at most %d ms.",
                            localLockObtainedTime, remoteLockReleasedTime,
                            lockReleasedAndReacquiredTimeDeltaInMillis),
                    Math.abs(localLockObtainedTime - remoteLockReleasedTime) <
                        lockReleasedAndReacquiredTimeDeltaInMillis);
            } else {
                // The remoteLockNotReleaseTime is captured before the lock was released by the
                // service. The localLockObtainedTime is captured after the lock was obtained by this
                // thread. The local thread should be able to get the lock before the remote thread
                // definitely release it. If this test fails it may not indicate a problem, but it
                // indicates we cannot be sure the test was successful the local lock attempt and the
                // remote lock attempt did not overlap.
                assertTrue(String.format("Local lock obtained (%d) after " +
                            "remote lock release start (%d)",
                            localLockObtainedTime, remoteLockNotReleasedTime),
                    localLockObtainedTime < remoteLockNotReleasedTime);
            }

            // Asserting if the fileLock is valid.
            assertTrue(fileLock.isValid());
        } finally {
            stopService();
        }
    }

    /**
     * Requests and waits for the service to stop
     */
    void stopService() throws Exception {
        getContext().stopService(new Intent(getContext(), LockHoldingService.class));
        // onStopLatch can be null if we never start the service, possibly because of
        // an earlier failure in the test.
        if (IntentReceiver.onStopLatch != null) {
            assertTrue(IntentReceiver.onStopLatch.await(MAX_WAIT_TIME, SECONDS));
        }

        deleteDir(getContext());
    }

    static enum LockType {

        /** Equivalent to {@code tryLock()} */
        TRY_LOCK,

        /** Equivalent to  {@code tryLock({@link #LOCK_POSITION}, {@link #LOCK_SIZE}, false)} */
        LOCK_ON_REGION_WITH_TRY_LOCK,

        /**
         * Equivalent to  {@code tryLock({@code {@link #LOCK_POSITION} + {@link #LOCK_SIZE}},
         * {@link #LOCK_SIZE}, false)}
         */
        LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,

        /** Equivalent to  {@code tryLock({@link #LOCK_POSITION}, {@link #LOCK_SIZE}, true)} */
        SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,

        /**
         * Equivalent to  {@code tryLock({@code {@link #LOCK_POSITION} + {@link #LOCK_SIZE}},
         * {@link #LOCK_SIZE}, true)}
         */
        SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,

        /** Equivalent to  {@code lock()} */
        LOCK,

        /** Equivalent to  {code lock({@link #LOCK_POSITION}, {@link #LOCK_SIZE}, false)} */
        LOCK_ON_REGION_WITH_LOCK,

        /**
         * Equivalent to  {@code lock({@code {@link #LOCK_POSITION} + {@link #LOCK_SIZE}},
         * {@link #LOCK_SIZE}, false)}
         */
        LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK,

        /** Equivalent to  {@code lock({@link #LOCK_POSITION}, {@link #LOCK_SIZE}, true)} */
        SHARED_LOCK_ON_REGION_WITH_LOCK,

        /**
         * Equivalent to {@code lock({@code {@link #LOCK_POSITION} + {@link #LOCK_SIZE}},
         * {@link #LOCK_SIZE}, true)}
         */
        SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK,
    }

    static enum ChannelType {
        /** Represents an {@code java.nio.channels.FileChannel} */
        SYNC_CHANNEL,
        /** Represents an {@code java.nio.channels.AsynchronousFileChannel} */
        ASYNC_CHANNEL,
    }

    /**
     * Tries to acquire a lock of {@code lockType} on the file returned by
     * {@link #createFileInDir()} method.
     *
     * @param lockType a {@link LockType} enum.
     *         Permitted lock types:
     *         {@link LockType#TRY_LOCK}
     *         {@link LockType#LOCK_ON_REGION_WITH_TRY_LOCK}
     *         {@link LockType#LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK}
     *         {@link LockType#SHARED_LOCK_ON_REGION_WITH_TRY_LOCK}
     *         {@link LockType#SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK}
     *         {@link LockType#LOCK}
     *         {@link LockType#LOCK_ON_REGION_WITH_LOCK}
     *         {@link LockType#LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK}
     *         {@link LockType#SHARED_LOCK_ON_REGION_WITH_LOCK}
     *         {@link LockType#SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK}
     * @param channelType the type of channel used to acquire the lock.
     * @return the lock returned by the lock method.
     * @throws UnsupportedOperationException
     *         If the {@code lockType} is of non recognized type.
     */
    static FileLock acquire(Context context, LockType lockType, ChannelType channelType) throws
            IOException, InterruptedException, ExecutionException {
        File file = createFileInDir(context);
        file.createNewFile();

        FileChannel fc = null;
        AsynchronousFileChannel afc = null;
        if (channelType == ChannelType.SYNC_CHANNEL) {
            fc = FileChannel.open(file.toPath(),
                    StandardOpenOption.WRITE, StandardOpenOption.READ);
        } else if (channelType == ChannelType.ASYNC_CHANNEL) {
            afc = AsynchronousFileChannel.open(file.toPath(),
                StandardOpenOption.WRITE, StandardOpenOption.READ);
        }

        switch (lockType) {
            case TRY_LOCK:
                if (fc != null) {
                    return fc.tryLock();
                } else {
                    return afc.tryLock();
                }
            case LOCK_ON_REGION_WITH_TRY_LOCK:
                if (fc != null) {
                    return fc.tryLock(LOCK_POSITION, LOCK_SIZE, false /*isShared*/);
                } else {
                    return afc.tryLock(LOCK_POSITION, LOCK_SIZE, false /*isShared*/);
                }
            case LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK:
                if (fc != null) {
                    return fc.tryLock(LOCK_POSITION + LOCK_SIZE, LOCK_SIZE, false /*isShared*/);
                } else {
                    return afc.tryLock(LOCK_POSITION + LOCK_SIZE, LOCK_SIZE, false /*isShared*/);
                }
            case SHARED_LOCK_ON_REGION_WITH_TRY_LOCK:
                if (fc != null) {
                    return fc.tryLock(LOCK_POSITION, LOCK_SIZE, true /*isShared*/);
                } else {
                    return afc.tryLock(LOCK_POSITION, LOCK_SIZE, true /*isShared*/);
                }
            case SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK:
                if (fc != null) {
                    return fc.tryLock(LOCK_POSITION + LOCK_SIZE, LOCK_SIZE, true /*isShared*/);
                } else {
                    return afc.tryLock(LOCK_POSITION + LOCK_SIZE, LOCK_SIZE, true /*isShared*/);
                }
            case LOCK:
                if (fc != null) {
                    return fc.lock();
                } else {
                    return afc.lock().get();
                }
            case LOCK_ON_REGION_WITH_LOCK:
                if (fc != null) {
                    return fc.lock(LOCK_POSITION, LOCK_SIZE, false /*isShared*/);
                } else {
                    return afc.lock(LOCK_POSITION, LOCK_SIZE, false /*isShared*/).get();
                }
            case LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK:
                if (fc != null) {
                    return fc.lock(LOCK_POSITION + LOCK_SIZE, LOCK_SIZE, false /*isShared*/);
                } else {
                    return afc.lock(LOCK_POSITION + LOCK_SIZE, LOCK_SIZE, false /*isShared*/).get();
                }
            case SHARED_LOCK_ON_REGION_WITH_LOCK:
                if (fc != null) {
                    return fc.lock(LOCK_POSITION, LOCK_SIZE, true /*isShared*/);
                } else {
                    return afc.lock(LOCK_POSITION, LOCK_SIZE, true /*isShared*/).get();
                }
            case SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK:
                if (fc != null) {
                    return fc.lock(LOCK_POSITION + LOCK_SIZE, LOCK_SIZE, true /*isShared*/);
                } else {
                    return afc.lock(LOCK_POSITION + LOCK_SIZE, LOCK_SIZE, true /*isShared*/).get();
                }
            default:
                throw new UnsupportedOperationException("Unknown lock type");
        }
    }

    /**
     * Creates a file named {@link #FILE_NAME} inside a directory named {@link #DIR_NAME} on
     * the external storage directory.
     */
    static File createFileInDir(Context context) throws IOException {
        File dir = new File(context.getExternalFilesDir(null), DIR_NAME);
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            throw new IOException("External storage is not mounted");
        } else if (!dir.mkdirs() && !dir.isDirectory()) {
            throw new IOException("Cannot create directory for device info files");
        } else {
            return new File(dir, FILE_NAME);
        }
    }

    /**
     * Deletes the folder {@link #DIR_NAME} on the external storage directory along with all the
     * files inside it.
     */
    static void deleteDir(Context context) {
        File dir = new File(context.getExternalFilesDir(null), DIR_NAME);
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (String child : children) {
                new File(dir, child).delete();
            }
            dir.delete();
        }
    }

    /**
     * Listens to broadcasts sent by the LockHoldingService and records information / provides
     * latches so the test code can synchronize until it is informed the service has acted on
     * requests it has sent.
     */
    public static class IntentReceiver extends BroadcastReceiver {

        static CountDownLatch onStartLatch;

        static CountDownLatch onStopLatch;

        static CountDownLatch lockHeldLatch;

        static volatile Bundle lockHeldBundle;

        static CountDownLatch lockReleasedLatch;

        static volatile Bundle lockReleasedBundle;

        /**
         * Reset the IntentReceiver for a new test. Assumes no intents will be received from prior
         *  tests.
         */
        public static synchronized void resetReceiverState() {
            onStartLatch = new CountDownLatch(1);
            onStopLatch = new CountDownLatch(1);
            lockHeldLatch = new CountDownLatch(1);
            lockReleasedLatch = new CountDownLatch(1);
            lockHeldBundle = null;
            lockReleasedBundle = null;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String msg = intent.getStringExtra(LockHoldingService.NOTIFICATION_KEY);
            switch (msg) {
                case LockHoldingService.NOTIFICATION_START:
                    onStartLatch.countDown();
                    break;
                case LockHoldingService.NOTIFICATION_STOP:
                    onStopLatch.countDown();
                    break;
                case LockHoldingService.NOTIFICATION_LOCK_HELD:
                    lockHeldBundle = intent.getExtras();
                    lockHeldLatch.countDown();
                    break;
                case LockHoldingService.NOTIFICATION_LOCK_RELEASED:
                    lockReleasedBundle = intent.getExtras();
                    lockReleasedLatch.countDown();
                    break;
            }
        }
    }
}