File: ParallelArray.java

package info (click to toggle)
libjsr166y-java 0.1.20080107-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, squeeze, wheezy
  • size: 904 kB
  • ctags: 2,811
  • sloc: java: 11,474; xml: 13; sh: 11; makefile: 8
file content (3309 lines) | stat: -rw-r--r-- 122,925 bytes parent folder | download
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
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
/*
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/licenses/publicdomain
 */

package jsr166y.forkjoin;
import static jsr166y.forkjoin.Ops.*;
import java.util.*;
import java.util.concurrent.atomic.*;
import java.lang.reflect.Array;

/**
 * An array supporting parallel operations.
 *
 * <p>A ParallelArray maintains a {@link ForkJoinExecutor} and an
 * array in order to provide parallel aggregate operations.  The main
 * operations are to <em>apply</em> some procedure to each element, to
 * <em>map</em> each element to a new element, to <em>replace</em>
 * each element, to <em>select</em> a subset of elements based on
 * matching a predicate or ranges of indices, and to <em>reduce</em>
 * all elements into a single value such as a sum.
 *
 * <p> A ParallelArray is constructed by allocating, using, or copying
 * an array, using one of the static factory methods {@link #create},
 * {@link #createEmpty}, {@link #createUsingHandoff} and {@link
 * #createFromCopy}. Upon construction, the encapsulated array managed
 * by the ParallelArray must not be shared between threads without
 * external synchronization. In particular, as is the case with any
 * array, access by another thread of an element of a ParallelArray
 * while another operation is in progress has undefined effects.
 *
 * <p> The ForkJoinExecutor used to construct a ParallelArray can be
 * shared safely by other threads (and used in other
 * ParallelArrays). To avoid the overhead associated with creating
 * multiple executors, it is often a good idea to use the {@link
 * #defaultExecutor()} across all ParallelArrays. However, you might
 * choose to use different ones for the sake of controlling processor
 * usage, isolating faults, and/or ensuring progress.
 *
 * <p>A ParallelArray is not a List. It relies on random access across
 * array elements to support efficient parallel operations.  However,
 * a ParallelArray can be viewed and manipulated as a List, via method
 * {@link ParallelArray#asList}. The <tt>asList</tt> view allows
 * incremental insertion and modification of elements while setting up
 * a ParallelArray, generally before using it for parallel
 * operations. Similarly, the list view may be useful when accessing
 * the results of computations in sequential contexts.  A
 * ParallelArray may also be created using the elements of any other
 * Collection, by constructing from the array returned by the
 * Collection's <tt>toArray</tt> method. The effects of mutative
 * <tt>asList</tt> operations may also be achieved directly using
 * method {@link #setLimit} along with element-by-element access
 * methods {@link #get}</tt> and {@link #set}.
 *
 * <p> Most operations can be prefixed with range bounds, filters, and
 * mappings using <tt>withBounds</tt>, <tt>withFilter</tt>, and
 * <tt>withMapping</tt>, respectively. For example,
 * <tt>aParallelArray.withFilter(aPredicate).all()</tt> creates a new
 * ParallelArray containing only those elements matching the
 * predicate.  As illustrated below, a <em>mapping</em> often
 * represents accessing some field or invoking some method of an
 * element.  These versions are typically more efficient than
 * performing selections, then mappings, then other operations in
 * multiple (parallel) steps. The basic ideas and usages of filtering
 * and mapping are similar to those in database query systems such as
 * SQL, but take a more restrictive form.  Series of filter and
 * mapping prefixes may each be cascaded, but all filter prefixes
 * must precede all mapping prefixes, to ensure efficient execution in
 * s single parallel step.  Instances of <tt>WithFilter</tt> etc are
 * useful only as operation prefixes, and should not normally be
 * stored in variables for future use.
 *
 * <p>This class includes some reductions, such as <tt>min</tt>, that
 * are commonly useful for most element types, as well as a combined
 * version, <tt>summary</tt>, that computes all of them in a single
 * parallel step, which is normally more efficient that computing each
 * in turn.
 *
 * <p>While ParallelArrays can be based on any kind of an object
 * array, including "boxed" types such as Long, parallel operations on
 * scalar "unboxed" type are likely to be substantially more
 * efficient. For this reason, classes {@link ParallelLongArray}, and
 * {@link ParallelDoubleArray} are also supplied, and designed to
 * smoothly interoperate with ParallelArrays. You should also use a
 * ParallelLongArray for processing other integral scalar data
 * (<tt>int</tt>, <tt>short</tt>, etc).  And similarly use a
 * ParallelDoubleArray for <tt>float</tt> data.  (Further
 * specializations for these other types would add clutter without
 * significantly improving performance beyond that of the Long and
 * Double versions.)
 *
 * <p>The methods in this class are designed to perform efficiently
 * with both large and small pools, even with single-thread pools on
 * uniprocessors.  However, there is some overhead in parallelizing
 * operations, so short computations on small arrays might not execute
 * faster than sequential versions, and might even be slower.
 *
 * <p><b>Sample usages</b>.
 *
 * The main difference between programming with plain arrays and
 * programming with aggregates is that you must separately define each
 * of the component functions on elements. For example, the following
 * returns the maximum Grade Point Average across all senior students,
 * given a (fictional) <tt>Student</tt> class:
 *
 * <pre>
 * import static Ops.*;
 * class StudentStatistics {
 *   ParallelArray&lt;Student&gt; students = ...
 *   // ...
 *   public double getMaxSeniorGpa() {
 *     return students.withFilter(isSenior).withMapping(gpaField).max();
 *   }
 *
 *   // helpers:
 *   static final class IsSenior implements Predicate&lt;Student&gt; {
 *     public boolean evaluate(Student s) { return s.credits &gt; 90; }
 *   }
 *   static final IsSenior isSenior = new IsSenior();
 *   static final class GpaField implements MapperToDouble&lt;Student&gt {
 *     public double map(Student s) { return s.gpa; }
 *   }
 *   static final GpaField gpaField = new GpaField();
 * }
 * </pre>
 *
 */
public class ParallelArray<T> implements Iterable<T> {
    /*
     * See class PAS for most of the underlying parallel execution
     * code and explanation.
     */

    /**
     * Returns a common default executor for use in ParallelArrays.
     * This executor arranges enough parallelism to use most, but not
     * necessarily all, of the avaliable processors on this system.
     * @return the executor
     */
    public static ForkJoinExecutor defaultExecutor() {
        return PAS.defaultExecutor();
    }

    /** The executor */
    final ForkJoinExecutor ex;
    /** The array -- can be replaced within AsList operations */
    T[] array;
    /** upper bound of effective region usef dor parallel operations */
    int limit;
    /** Lazily constructed list view */
    AsList listView;

    /**
     * Constructor for use by subclasses to create a new ParallelArray
     * using the given executor, and initially using the supplied
     * array, with effective size bound by the given limit. This
     * constructor is designed to enable extensions via
     * subclassing. To create a ParallelArray, use {@link #create},
     * {@link #createEmpty}, {@link #createUsingHandoff} or {@link
     * #createFromCopy}.
     * @param executor the executor
     * @param array the array
     * @param limit the upper bound limit
     */
    protected ParallelArray(ForkJoinExecutor executor, T[] array,
                            int limit) {
        if (executor == null || array == null)
            throw new NullPointerException();
        if (limit < 0 || limit > array.length)
            throw new IllegalArgumentException();
        this.ex = executor;
        this.array = array;
        this.limit = limit;
    }

    /**
     * Trusted internal version of protected constructor.
     */
    ParallelArray(ForkJoinExecutor executor, T[] array) {
        this.ex = executor;
        this.array = array;
        this.limit = array.length;
    }

    /**
     * Creates a new ParallelArray using the given executor and
     * an array of the given size constructed using the
     * indicated base element type.
     * @param size the array size
     * @param elementType the type of the elements
     * @param executor the executor
     */
    public static <T> ParallelArray<T> create
        (int size, Class<? super T> elementType,
         ForkJoinExecutor executor) {
        T[] array = (T[])Array.newInstance(elementType, size);
        return new ParallelArray<T>(executor, array, size);
    }

    /**
     * Creates a new ParallelArray initially using the given array and
     * executor. In general, the handed off array should not be used
     * for other purposes once constructing this ParallelArray.  The
     * given array may be internally replaced by another array in the
     * course of methods that add or remove elements.
     * @param handoff the array
     * @param executor the executor
     */
    public static <T> ParallelArray<T> createUsingHandoff
        (T[] handoff, ForkJoinExecutor executor) {
        return new ParallelArray<T>(executor, handoff, handoff.length);
    }

    /**
     * Creates a new ParallelArray using the given executor and
     * initially holding copies of the given
     * source elements.
     * @param source the source of initial elements
     * @param executor the executor
     */
    public static <T> ParallelArray<T> createFromCopy
        (T[] source, ForkJoinExecutor executor) {
        // For now, avoid copyOf so people can compile with Java5
        int size = source.length;
        T[] array = (T[])Array.newInstance
            (source.getClass().getComponentType(), size);
        System.arraycopy(source, 0, array, 0, size);
        return new ParallelArray<T>(executor, array, size);
    }

    /**
     * Creates a new ParallelArray using an array of the given size,
     * initially holding copies of the given source truncated or
     * padded with nulls to obtain the specified length.
     * @param source the source of initial elements
     * @param size the array size
     * @param executor the executor
     */
    public static <T> ParallelArray<T> createFromCopy
        (int size, T[] source, ForkJoinExecutor executor) {
        // For now, avoid copyOf so people can compile with Java5
        T[] array = (T[])Array.newInstance
            (source.getClass().getComponentType(), size);
        System.arraycopy(source, 0, array, 0,
                         Math.min(source.length, size));
        return new ParallelArray<T>(executor, array, size);
    }

    /**
     * Creates a new ParallelArray using the given executor and an
     * array of the given size constructed using the indicated base
     * element type, but with an initial effective size of zero,
     * enabling incremental insertion via {@link ParallelArray#asList}
     * operations.
     * @param size the array size
     * @param elementType the type of the elements
     * @param executor the executor
     */
    public static <T> ParallelArray<T> createEmpty
        (int size, Class<? super T> elementType,
         ForkJoinExecutor executor) {
        T[] array = (T[])Array.newInstance(elementType, size);
        return new ParallelArray<T>(executor, array, 0);
    }

    /**
     * Summary statistics for a possibly bounded, filtered, and/or
     * mapped ParallelArray.
     */
    public static interface SummaryStatistics<T> {
        /** Return the number of elements */
        public int size();
        /** Return the minimum element, or null if empty */
        public T min();
        /** Return the maximum element, or null if empty */
        public T max();
        /** Return the index of the minimum element, or -1 if empty */
        public int indexOfMin();
        /** Return the index of the maximum element, or -1 if empty */
        public int indexOfMax();
    }

    /**
     * Returns the executor used for computations
     * @return the executor
     */
    public ForkJoinExecutor getExecutor() { return ex; }

    /**
     * Applies the given procedure to elements
     * @param procedure the procedure
     */
    public void apply(Procedure<? super T> procedure) {
        new WithBounds<T>(this).apply(procedure);
    }

    /**
     * Returns reduction of elements
     * @param reducer the reducer
     * @param base the result for an empty array
     * @return reduction
     */
    public T reduce(Reducer<T> reducer, T base) {
        return new WithBounds<T>(this).reduce(reducer, base);
    }

    /**
     * Returns a new ParallelArray holding all elements
     * @return a new ParallelArray holding all elements
     */
    public ParallelArray<T> all() {
        return new WithBounds<T>(this).all();
    }

    /**
     * Returns a new ParallelArray with the given element type holding
     * all elements
     * @param elementType the type of the elements
     * @return a new ParallelArray holding all elements
     */
    public ParallelArray<T> all(Class<? super T> elementType) {
        return new WithBounds<T>(this).all(elementType);
    }

    /**
     * Returns a ParallelArray containing results of
     * applying <tt>combine(thisElement, otherElement)</tt>
     * for each element.
     * @param other the other array
     * @param combiner the combiner
     * @return the array of mappings
     * @throws ArrayIndexOutOfBoundsException if other array is
     * shorter than this array.
     */
    public <U,V> ParallelArray<V> combine
        (U[] other,
         Combiner<? super T, ? super U, ? extends V> combiner) {
        return new WithBounds<T>(this).combine(other, combiner);
    }

    /**
     * Returns a ParallelArray containing results of
     * applying <tt>combine(thisElement, otherElement)</tt>
     * for each element.
     * @param other the other array
     * @param combiner the combiner
     * @return the array of mappings
     * @throws ArrayIndexOutOfBoundsException if other array is not
     * the same length as this array.
     */
    public <U,V> ParallelArray<V> combine
        (ParallelArray<? extends U> other,
         Combiner<? super T, ? super U, ? extends V> combiner) {
        return new WithBounds<T>(this).combine(other, combiner);
    }

    /**
     * Returns a ParallelArray containing results of
     * applying <tt>combine(thisElement, otherElement)</tt>
     * for each element.
     * @param other the other array
     * @param combiner the combiner
     * @param elementType the type of elements of returned array
     * @return the array of mappings
     * @throws ArrayIndexOutOfBoundsException if other array is
     * shorter than this array.
     */
    public <U,V> ParallelArray<V> combine
        (U[] other,
         Combiner<? super T, ? super U, ? extends V> combiner,
         Class<? super V> elementType) {
        return new WithBounds<T>(this).combine(other, combiner, elementType);
    }

    /**
     * Returns a ParallelArray containing results of
     * applying <tt>combine(thisElement, otherElement)</tt>
     * for each element.
     * @param other the other array segment
     * @param combiner the combiner
     * @return the array of mappings
     * @throws ArrayIndexOutOfBoundsException if other segment is
     * shorter than this array.
     */
    public <U,V> ParallelArray<V> combine
        (ParallelArray.WithBounds<? extends U> other,
         Combiner<? super T, ? super U, ? extends V> combiner) {
        return new WithBounds<T>(this).combine(other, combiner);
    }

    /**
     * Returns a ParallelArray containing results of
     * applying <tt>combine(thisElement, otherElement)</tt>
     * for each element.
     * @param other the other array segment
     * @param combiner the combiner
     * @param elementType the type of elements of returned array
     * @return the array of mappings
     * @throws ArrayIndexOutOfBoundsException if other array is
     * shorter than this array.
     */
    public <U,V> ParallelArray<V> combine
        (ParallelArray.WithBounds<? extends U> other,
         Combiner<? super T, ? super U, ? extends V> combiner,
         Class<? super V> elementType) {
        return new WithBounds<T>(this).combine(other, combiner, elementType);
    }

    /**
     * Returns a ParallelArray containing results of
     * applying <tt>combine(thisElement, otherElement)</tt>
     * for each element.
     * @param other the other array
     * @param combiner the combiner
     * @param elementType the type of elements of returned array
     * @return the array of mappings
     * @throws ArrayIndexOutOfBoundsException if other array is not
     * the same length as this array.
     */
    public <U,V> ParallelArray<V> combine
        (ParallelArray<? extends U> other,
         Combiner<? super T, ? super U, ? extends V> combiner,
         Class<? super V> elementType) {
        return new WithBounds<T>(this).combine(other.array,
                                               combiner, elementType);
    }

    /**
     * Replaces elements with the results of applying the given mapper
     * to their current values.
     * @param mapper the mapper
     */
    public void replaceWithTransform(Mapper<? super T, ? extends T> mapper) {
        new WithBounds<T>(this).replaceWithTransform(mapper);
    }

    /**
     * Replaces elements with the results of applying the given
     * mapper to their indices.
     * @param mapper the mapper
     */
    public void replaceWithMappedIndex(MapperFromInt<? extends T> mapper) {
        new WithBounds<T>(this).replaceWithMappedIndex(mapper);
    }

    /**
     * Replaces elements with the results of applying the given
     * generator.
     * @param generator the generator
     */
    public void replaceWithGeneratedValue(Generator<? extends T> generator) {
        new WithBounds<T>(this).replaceWithGeneratedValue(generator);
    }

    /**
     * Replaces elements with the given value.
     * @param value the value
     */
    public void replaceWithValue(T value) {
        new WithBounds<T>(this).replaceWithValue(value);
    }

    /**
     * Replaces elements with results of applying
     * <tt>combine(thisElement, otherElement)</tt>
     * @param other the other array
     * @param combiner the combiner
     * @throws ArrayIndexOutOfBoundsException if other array has
     * fewer elements than this array.
     */
    public void replaceWithCombination
        (ParallelArray<? extends T> other, Reducer<T> combiner) {
        new WithBounds<T>(this).replaceWithCombination(other.array, combiner);
    }

    /**
     * Replaces elements with results of applying
     * <tt>combine(thisElement, otherElement)</tt>
     * @param other the other array
     * @param combiner the combiner
     * @throws ArrayIndexOutOfBoundsException if other array has
     * fewer elements than this array.
     */
    public void replaceWithCombination(T[] other, Reducer<T> combiner) {
        new WithBounds<T>(this).replaceWithCombination(other, combiner);
    }

    /**
     * Replaces elements with results of applying
     * <tt>combine(thisElement, otherElement)</tt>
     * @param other the other array segment
     * @param combiner the combiner
     * @throws ArrayIndexOutOfBoundsException if other segment has
     * fewer elements.than this array,
     */
    public void replaceWithCombination
        (ParallelArray.WithBounds<? extends T> other,
         Reducer<T> combiner) {
        new WithBounds<T>(this).replaceWithCombination(other, combiner);
    }

    /**
     * Returns the index of some element equal to given target,
     * or -1 if not present
     * @param target the element to search for
     * @return the index or -1 if not present
     */
    public int indexOf(T target) {
        return new WithBounds<T>(this).indexOf(target);
    }

    /**
     * Assuming this array is sorted, returns the index of an element
     * equal to given target, or -1 if not present. If the array
     * is not sorted, the results are undefined.
     * @param target the element to search for
     * @return the index or -1 if not present
     */
    public int binarySearch(T target) {
        int lo = 0;
        int hi = limit - 1;
        while (lo <= hi) {
            int mid = (lo + hi) >>> 1;
            int c = ((Comparable)target).compareTo((Comparable)(array[mid]));
            if (c == 0)
                return mid;
            else if (c < 0)
                hi = mid - 1;
            else
                lo = mid + 1;
        }
        return -1;
    }

    /**
     * Assuming this array is sorted with respect to the given
     * comparator, returns the index of an element equal to given
     * target, or -1 if not present. If the array is not sorted, the
     * results are undefined.
     * @param target the element to search for
     * @param comparator the comparator
     * @return the index or -1 if not present
     */
    public int binarySearch(T target, Comparator<? super T> comparator) {
        int lo = 0;
        int hi = limit - 1;
        while (lo <= hi) {
            int mid = (lo + hi) >>> 1;
            int c = comparator.compare(target, array[mid]);
            if (c == 0)
                return mid;
            else if (c < 0)
                hi = mid - 1;
            else
                lo = mid + 1;
        }
        return -1;
    }

    /**
     * Returns summary statistics, using the given comparator
     * to locate minimum and maximum elements.
     * @param comparator the comparator to use for
     * locating minimum and maximum elements
     * @return the summary.
     */
    public ParallelArray.SummaryStatistics<T> summary
        (Comparator<? super T> comparator) {
        return new WithBounds<T>(this).summary(comparator);
    }

    /**
     * Returns summary statistics, assuming that all elements are
     * Comparables
     * @return the summary.
     */
    public ParallelArray.SummaryStatistics<T> summary() {
        return new WithBounds<T>(this).summary();
    }

    /**
     * Returns the minimum element, or null if empty
     * @param comparator the comparator
     * @return minimum element, or null if empty
     */
    public T min(Comparator<? super T> comparator) {
        return new WithBounds<T>(this).min(comparator);
    }

    /**
     * Returns the minimum element, or null if empty,
     * assuming that all elements are Comparables
     * @return minimum element, or null if empty
     * @throws ClassCastException if any element is not Comparable.
     */
    public T min() {
        return new WithBounds<T>(this).min();
    }

    /**
     * Returns the maximum element, or null if empty
     * @param comparator the comparator
     * @return maximum element, or null if empty
     */
    public T max(Comparator<? super T> comparator) {
        return new WithBounds<T>(this).max(comparator);
    }

    /**
     * Returns the maximum element, or null if empty
     * assuming that all elements are Comparables
     * @return maximum element, or null if empty
     * @throws ClassCastException if any element is not Comparable.
     */
    public T max() {
        return new WithBounds<T>(this).max();
    }

    /**
     * Replaces each element with the running cumulation of applying
     * the given reducer. For example, if the contents are the numbers
     * <tt>1, 2, 3</tt>, and the reducer operation adds numbers, then
     * after invocation of this method, the contents would be <tt>1,
     * 3, 6</tt> (that is, <tt>1, 1+2, 1+2+3</tt>);
     * @param reducer the reducer
     * @param base the result for an empty array
     */
    public void cumulate(Reducer<T> reducer, T base) {
        new WithBounds<T>(this).cumulate(reducer, base);
    }

    /**
     * Replaces each element with the cumulation of applying the given
     * reducer to all previous values, and returns the total
     * reduction. For example, if the contents are the numbers <tt>1,
     * 2, 3</tt>, and the reducer operation adds numbers, then after
     * invocation of this method, the contents would be <tt>0, 1,
     * 3</tt> (that is, <tt>0, 0+1, 0+1+2</tt>, and the return value
     * would be 6 (that is, <tt> 1+2+3</tt>);
     * @param reducer the reducer
     * @param base the result for an empty array
     * @return the total reduction
     */
    public T precumulate(Reducer<T> reducer, T base) {
        return (T)(new WithBounds<T>(this).precumulate(reducer, base));
    }

    /**
     * Sorts the array. Unlike Arrays.sort, this sort does
     * not guarantee that elements with equal keys maintain their
     * relative position in the array.
     * @param comparator the comparator to use
     */
    public void sort(Comparator<? super T> comparator) {
        new WithBounds<T>(this).sort(comparator);
    }

    /**
     * Sorts the array, assuming all elements are Comparable. Unlike
     * Arrays.sort, this sort does not guarantee that elements
     * with equal keys maintain their relative position in the array.
     * @throws ClassCastException if any element is not Comparable.
     */
    public void sort() {
        new WithBounds<T>(this).sort();
    }

    /**
     * Removes consecutive elements that are equal (or null), shifting
     * others leftward, and possibly decreasing size.  This method
     * uses each non-null element's <tt>equals</tt> method to test for
     * duplication. This method may be used after sorting to ensure
     * that this ParallelArray contains a set of unique elements.
     */
    public void removeConsecutiveDuplicates() {
        new WithBounds<T>(this).removeConsecutiveDuplicates();
    }

    /**
     * Removes null elements, shifting others leftward, and possibly
     * decreasing size.
     */
    public void removeNulls() {
        new WithBounds<T>(this).removeNulls();
    }

    /**
     * Returns a new ParallelArray containing only the non-null unique
     * elements of this array (that is, without any duplicates). This
     * method uses each element's <tt>equals</tt> method to test for
     * duplication.
     * @return the new ParallelArray
     */
    public ParallelArray<T> allUniqueElements() {
        return new WithBounds<T>(this).allUniqueElements();
    }

    /**
     * Returns a new ParallelArray containing only the non-null unique
     * elements of this array (that is, without any duplicates). This
     * method uses reference identity to test for duplication.
     * @return the new ParallelArray
     */
    public ParallelArray<T> allNonidenticalElements() {
        return new WithBounds<T>(this).allNonidenticalElements();
    }

    /**
     * Returns an operation prefix that causes a method to
     * operate only on the elements of the array between
     * firstIndex (inclusive) and upperBound (exclusive).
     * @param firstIndex the lower bound (inclusive)
     * @param upperBound the upper bound (exclusive)
     * @return operation prefix
     */
    public WithBounds<T> withBounds(int firstIndex, int upperBound) {
        if (firstIndex > upperBound)
            throw new IllegalArgumentException
                ("firstIndex(" + firstIndex +
                 ") > upperBound(" + upperBound+")");
        if (firstIndex < 0)
            throw new ArrayIndexOutOfBoundsException(firstIndex);
        if (upperBound > this.limit)
            throw new ArrayIndexOutOfBoundsException(upperBound);
        return new WithBounds<T>(this, firstIndex, upperBound);
    }

    /**
     * Returns an operation prefix that causes a method to operate
     * only on the elements of the array for which the given selector
     * returns true
     * @param selector the selector
     * @return operation prefix
     */
    public WithFilter<T> withFilter(Predicate<? super T> selector) {
        return new WithBoundedFilter<T>(this, 0, limit, selector);
    }

    /**
     * Returns an operation prefix that causes a method to operate
     * on mapped elements of the array using the given mapper.
     * @param mapper the mapper
     * @return operation prefix
     */
    public <U> WithMapping<T, U> withMapping
        (Mapper<? super T, ? extends U> mapper) {
        return new WithBoundedMapping<T,U>(this, 0, limit, mapper);
    }

    /**
     * Returns an operation prefix that causes a method to operate
     * on mapped elements of the array using the given mapper.
     * @param mapper the mapper
     * @return operation prefix
     */
    public WithDoubleMapping<T> withMapping
        (MapperToDouble<? super T> mapper) {
        return new WithBoundedDoubleMapping<T>(this, 0, limit, mapper);
    }

    /**
     * Returns an operation prefix that causes a method to operate
     * on mapped elements of the array using the given mapper.
     * @param mapper the mapper
     * @return operation prefix
     */
    public WithLongMapping<T> withMapping
        (MapperToLong<? super T> mapper) {
        return new WithBoundedLongMapping<T>(this, 0, limit, mapper);
    }

    /**
     * A modifier for parallel array operations to apply to mappings
     * of elements, not to the elements themselves
     */
    public static abstract class WithMapping<T,U> extends PAS.RPrefix {
        WithMapping(ParallelArray<T> pa, int firstIndex, int upperBound) {
            super(pa, firstIndex, upperBound);
        }

        /**
         * Applies the given procedure to elements
         * @param procedure the procedure
         */
        public void apply(Procedure<? super U> procedure) {
            ex.invoke(new PAS.FJRApply(this, firstIndex, upperBound, null,
                                       procedure));
        }

        /**
         * Returns reduction of elements
         * @param reducer the reducer
         * @param base the result for an empty array
         * @return reduction
         */
        public U reduce(Reducer<U> reducer, U base) {
            PAS.FJRReduce f = new PAS.FJRReduce
                (this, firstIndex, upperBound, null, reducer, base);
            ex.invoke(f);
            return (U)(f.result);
        }

        /**
         * Returns the index of some element matching bound and filter
         * constraints, or -1 if none.
         * @return index of matching element, or -1 if none.
         */
        public abstract int anyIndex();

        /**
         * Returns some element matching bound and filter
         * constraints, or null if none.
         * @return an element, or null if none.
         */
        public abstract U any();

        /**
         * Returns the minimum element, or null if empty
         * @param comparator the comparator
         * @return minimum element, or null if empty
         */
        public U min(Comparator<? super U> comparator) {
            return reduce(Ops.<U>minReducer(comparator), null);
        }

        /**
         * Returns the minimum element, or null if empty,
         * assuming that all elements are Comparables
         * @return minimum element, or null if empty
         * @throws ClassCastException if any element is not Comparable.
         */
        public U min() {
            return reduce((Reducer<U>)(Ops.castedMinReducer()), null);
        }

        /**
         * Returns the maximum element, or null if empty
         * @param comparator the comparator
         * @return maximum element, or null if empty
         */
        public U max(Comparator<? super U> comparator) {
            return reduce(Ops.<U>maxReducer(comparator), null);
        }

        /**
         * Returns the maximum element, or null if empty
         * assuming that all elements are Comparables
         * @return maximum element, or null if empty
         * @throws ClassCastException if any element is not Comparable.
         */
        public U max() {
            return reduce((Reducer<U>)(Ops.castedMaxReducer()), null);
        }

        /**
         * Returns summary statistics, using the given comparator
         * to locate minimum and maximum elements.
         * @param comparator the comparator to use for
         * locating minimum and maximum elements
         * @return the summary.
         */
        public ParallelArray.SummaryStatistics<U> summary
            (Comparator<? super U> comparator) {
            PAS.FJRStats f = new PAS.FJRStats
                (this, firstIndex, upperBound, null, comparator);
            ex.invoke(f);
            return (ParallelArray.SummaryStatistics<U>)f;
        }

        /**
         * Returns summary statistics, assuming that all elements are
         * Comparables
         * @return the summary.
         */
        public ParallelArray.SummaryStatistics<U> summary() {
            PAS.FJRStats f = new PAS.FJRStats
                (this, firstIndex, upperBound, null,
                 (Comparator<? super U>)(Ops.castedComparator()));
            ex.invoke(f);
            return (ParallelArray.SummaryStatistics<U>)f;
        }

        /**
         * Returns a new ParallelArray holding elements
         * @return a new ParallelArray holding elements
         */
        public abstract ParallelArray<U> all();

        /**
         * Returns a new ParallelArray with the given element type
         * holding elements
         * @param elementType the type of the elements
         * @return a new ParallelArray holding elements
         */
        public abstract ParallelArray<U> all(Class<? super U> elementType);

        /**
         * Return the number of elements selected using bound or
         * filter restrictions. Note that this method must evaluate
         * all selectors to return its result.
         * @return the number of elements
         */
        public abstract int size();

        /**
         * Returns an operation prefix that causes a method to operate
         * on mapped elements of the array using the given mapper
         * applied to current mapper's results
         * @param mapper the mapper
         * @return operation prefix
         */
        public abstract <V> WithMapping<T, V> withMapping
            (Mapper<? super U, ? extends V> mapper);

        /**
         * Returns an operation prefix that causes a method to operate
         * on mapped elements of the array using the given mapper
         * applied to current mapper's results
         * @param mapper the mapper
         * @return operation prefix
         */
        public abstract WithDoubleMapping<T> withMapping
            (MapperToDouble<? super U> mapper);

        /**
         * Returns an operation prefix that causes a method to operate
         * on mapped elements of the array using the given mapper
         * applied to current mapper's results
         * @param mapper the mapper
         * @return operation prefix
         */
        public abstract WithLongMapping<T> withMapping
            (MapperToLong<? super U> mapper);

    }

    /**
     * A restriction of parallel array operations to apply only to
     * elements for which a selector returns true
     */
    public static abstract class WithFilter<T> extends WithMapping<T,T>{
        WithFilter(ParallelArray<T> pa, int firstIndex, int upperBound) {
            super(pa, firstIndex, upperBound);
        }

        public void apply(Procedure<? super T> procedure) {
            ex.invoke(new PAS.FJRApply
                      (this, firstIndex, upperBound, null, procedure));
        }

        public T reduce(Reducer<T> reducer, T base) {
            PAS.FJRReduce f = new PAS.FJRReduce
                (this, firstIndex, upperBound, null, reducer, base);
            ex.invoke(f);
            return (T)(f.result);
        }

        public T min(Comparator<? super T> comparator) {
            return reduce(Ops.<T>minReducer(comparator), null);
        }

        public T min() {
            return reduce((Reducer<T>)(Ops.castedMinReducer()), null);
        }

        public T max(Comparator<? super T> comparator) {
            return reduce(Ops.<T>maxReducer(comparator), null);
        }

        public T max() {
            return reduce((Reducer<T>)(Ops.castedMaxReducer()), null);
        }

        public ParallelArray.SummaryStatistics<T> summary
            (Comparator<? super T> comparator) {
            PAS.FJRStats f = new PAS.FJRStats
                (this, firstIndex, upperBound, null, comparator);
            ex.invoke(f);
            return (ParallelArray.SummaryStatistics<T>)f;
        }

        public ParallelArray.SummaryStatistics<T> summary() {
            PAS.FJRStats f = new PAS.FJRStats
                (this, firstIndex, upperBound, null,
                 (Comparator<? super T>)(Ops.castedComparator()));
            ex.invoke(f);
            return (ParallelArray.SummaryStatistics<T>)f;
        }

        /**
         * Replaces elements with the results of applying the given
         * mapper to their current values.
         * @param mapper the mapper
         */
        public void replaceWithTransform
            (Mapper<? super T, ? extends T> mapper) {
            ex.invoke(new PAS.FJRTransform(this, firstIndex, upperBound,
                                           null, mapper));
        }

        /**
         * Replaces elements with the results of applying the given
         * mapper to their indices
         * @param mapper the mapper
         */
        public void replaceWithMappedIndex
            (MapperFromInt<? extends T> mapper) {
            ex.invoke(new PAS.FJRIndexMap(this, firstIndex, upperBound,
                                          null, mapper));
        }

        /**
         * Replaces elements with results of applying the given
         * generator.
         * @param generator the generator
         */
        public void replaceWithGeneratedValue
            (Generator<? extends T> generator) {
            ex.invoke(new PAS.FJRGenerate
                      (this, firstIndex, upperBound, null, generator));
        }

        /**
         * Replaces elements with the given value.
         * @param value the value
         */
        public void replaceWithValue(T value) {
            ex.invoke(new PAS.FJRFill(this, firstIndex, upperBound,
                                      null, value));
        }

        /**
         * Replaces elements with results of applying
         * <tt>combine(thisElement, otherElement)</tt>
         * @param other the other array
         * @param combiner the combiner
         * @throws ArrayIndexOutOfBoundsException if other array has
         * fewer than <tt>upperBound</tt> elements.
         */
        public void replaceWithCombination
            (ParallelArray<? extends T> other, Reducer<T> combiner) {
            if (other.size() < size())
                throw new ArrayIndexOutOfBoundsException();
            ex.invoke(new PAS.FJRCombineInPlace
                      (this, firstIndex, upperBound, null,
                       other.array, 0, combiner));
        }

        /**
         * Replaces elements with results of applying
         * <tt>combine(thisElement, otherElement)</tt>
         * @param other the other array segment
         * @param combiner the combiner
         * @throws ArrayIndexOutOfBoundsException if other array has
         * fewer than <tt>upperBound</tt> elements.
         */
        public void replaceWithCombination
            (ParallelArray.WithBounds<? extends T> other,
             Reducer<T> combiner) {
            if (other.size() < size())
                throw new ArrayIndexOutOfBoundsException();
            ex.invoke(new PAS.FJRCombineInPlace
                      (this, firstIndex, upperBound, null,
                       other.pa.array, other.firstIndex-firstIndex, combiner));
        }

        /**
         * Replaces elements with results of applying
         * <tt>combine(thisElement, otherElement)</tt>
         * @param other the other array
         * @param combiner the combiner
         * @throws ArrayIndexOutOfBoundsException if other array has
         * fewer than <tt>upperBound</tt> elements.
         */
        public void replaceWithCombination
            (T[] other, Reducer<T> combiner) {
            if (other.length < size())
                throw new ArrayIndexOutOfBoundsException();
            ex.invoke(new PAS.FJRCombineInPlace
                      (this, firstIndex, upperBound, null, other,
                       -firstIndex, combiner));
        }

        /**
         * Removes from the array all elements matching bound and/or
         * filter constraints.
         */
        public abstract void removeAll();

        /**
         * Returns a new ParallelArray containing only non-null unique
         * elements (that is, without any duplicates). This method
         * uses each element's <tt>equals</tt> method to test for
         * duplication.
         * @return the new ParallelArray
         */
        public abstract ParallelArray<T> allUniqueElements();

        /**
         * Returns a new ParallelArray containing only non-null unique
         * elements (that is, without any duplicates). This method
         * uses reference identity to test for duplication.
         * @return the new ParallelArray
         */
        public abstract ParallelArray<T> allNonidenticalElements();

        /**
         * Returns an operation prefix that causes a method to operate
         * only on elements for which the current selector (if
         * present) and the given selector returns true
         * @param selector the selector
         * @return operation prefix
         */
        public abstract WithFilter<T> withFilter
            (Predicate<? super T> selector);

        /**
         * Returns an operation prefix that causes a method to operate
         * only on elements for which the current selector (if
         * present) or the given selector returns true
         * @param selector the selector
         * @return operation prefix
         */
        public abstract WithFilter<T> orFilter
            (Predicate<? super T> selector);

        final void leafTransfer(int lo, int hi, Object[] dest, int offset) {
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i)
                dest[offset++] = (array[i]);
        }

        final void leafTransferByIndex(int[] indices, int loIdx, int hiIdx,
                                       Object[] dest, int offset) {
            final Object[] array = pa.array;
            for (int i = loIdx; i < hiIdx; ++i)
                dest[offset++] = (array[indices[i]]);
        }
    }

    /**
     * A restriction of parallel array operations to apply only within
     * a given range of indices.
     */
    public static final class WithBounds<T> extends WithFilter<T> {
        WithBounds(ParallelArray<T> pa, int firstIndex, int upperBound) {
            super(pa, firstIndex, upperBound);
        }

        /** Version for implementing main ParallelArray methods */
        WithBounds(ParallelArray<T> pa) {
            super(pa, 0, pa.limit);
        }

        /**
         * Returns an operation prefix that causes a method to operate
         * only on the elements of the array between firstIndex
         * (inclusive) and upperBound (exclusive).  The bound
         * arguments are relative to the current bounds.  For example
         * <tt>pa.withBounds(2, 8).withBounds(3, 5)</tt> indexes the
         * 5th (= 2+3) and 6th elements of pa. However, indices
         * returned by methods such as <tt>indexOf</tt> are
         * with respect to the underlying ParallelArray.
         * @param firstIndex the lower bound (inclusive)
         * @param upperBound the upper bound (exclusive)
         * @return operation prefix
         */
        public WithBounds<T> withBounds(int firstIndex, int upperBound) {
            if (firstIndex > upperBound)
                throw new IllegalArgumentException
                    ("firstIndex(" + firstIndex +
                     ") > upperBound(" + upperBound+")");
            if (firstIndex < 0)
                throw new ArrayIndexOutOfBoundsException(firstIndex);
            if (upperBound - firstIndex > this.upperBound - this.firstIndex)
                throw new ArrayIndexOutOfBoundsException(upperBound);
            return new WithBounds<T>(pa,
                                     this.firstIndex + firstIndex,
                                     this.firstIndex + upperBound);
        }

        public WithFilter<T> withFilter(Predicate<? super T> selector) {
            return new WithBoundedFilter<T>
                (pa, firstIndex, upperBound, selector);
        }

        public <U> WithMapping<T, U> withMapping
            (Mapper<? super T, ? extends U> mapper) {
            return new WithBoundedMapping<T,U>
                (pa, firstIndex, upperBound, mapper);
        }

        public WithDoubleMapping<T> withMapping
            (MapperToDouble<? super T> mapper) {
            return new WithBoundedDoubleMapping<T>
                (pa, firstIndex, upperBound, mapper);
        }

        public WithLongMapping<T> withMapping
            (MapperToLong<? super T> mapper) {
            return new WithBoundedLongMapping<T>
                (pa, firstIndex, upperBound, mapper);
        }

        public WithFilter<T> orFilter(Predicate<? super T> selector) {
            return new WithBoundedFilter<T>
                (pa, firstIndex, upperBound, selector);
        }

        public int anyIndex() {
            return (firstIndex < upperBound)? firstIndex : -1;
        }

        public T any() {
            return (firstIndex < upperBound)? (T)(pa.array[firstIndex]) : null;
        }

        /**
         * Returns a ParallelArray containing results of
         * applying <tt>combine(thisElement, otherElement)</tt>
         * for each element.
         * @param other the other array
         * @param combiner the combiner
         * @return the array of mappings
         * @throws ArrayIndexOutOfBoundsException if other array is
         * shorter than this array.
         */
        public <U,V> ParallelArray<V> combine
            (U[] other,
             Combiner<? super T, ? super U, ? extends V> combiner) {
            int size = upperBound - firstIndex;
            if (other.length < size)
                throw new ArrayIndexOutOfBoundsException();
            V[] dest = (V[])new Object[size];
            ex.invoke(new PAS.FJRCombine
                      (this, firstIndex, upperBound, null, other,
                       -firstIndex, dest, combiner));
            return new ParallelArray<V>(ex, dest);
        }

        /**
         * Returns a ParallelArray containing results of
         * applying <tt>combine(thisElement, otherElement)</tt>
         * for each element.
         * @param other the other array
         * @param combiner the combiner
         * @param elementType the type of elements of returned array
         * @return the array of mappings
         * @throws ArrayIndexOutOfBoundsException if other array is
         * shorter than this array.
         */
        public <U,V> ParallelArray<V> combine
            (U[] other,
             Combiner<? super T, ? super U, ? extends V> combiner,
             Class<? super V> elementType) {
            int size = upperBound - firstIndex;
            if (other.length < size)
                throw new ArrayIndexOutOfBoundsException();
            V[] dest = (V[])Array.newInstance(elementType, size);
            ex.invoke(new PAS.FJRCombine
                      (this, firstIndex, upperBound, null,
                       other, -firstIndex, dest, combiner));
            return new ParallelArray<V>(ex, dest);
        }

        /**
         * Returns a ParallelArray containing results of
         * applying <tt>combine(thisElement, otherElement)</tt>
         * for each element.
         * @param other the other array
         * @param combiner the combiner
         * @return the array of mappings
         * @throws ArrayIndexOutOfBoundsException if other array is
         * shorter than this array.
         */
        public <U,V> ParallelArray<V> combine
            (ParallelArray<? extends U> other,
             Combiner<? super T, ? super U, ? extends V> combiner) {
            int size = upperBound - firstIndex;
            if (other.size() < size)
                throw new ArrayIndexOutOfBoundsException();
            V[] dest = (V[])new Object[size];
            ex.invoke(new PAS.FJRCombine
                      (this, firstIndex, upperBound, null,
                       other.array, -firstIndex, dest, combiner));
            return new ParallelArray<V>(ex, dest);
        }

        /**
         * Returns a ParallelArray containing results of
         * applying <tt>combine(thisElement, otherElement)</tt>
         * for each element.
         * @param other the other array
         * @param combiner the combiner
         * @param elementType the type of elements of returned array
         * @return the array of mappings
         * @throws ArrayIndexOutOfBoundsException if other array is
         * shorter than this array.
         */
        public <U,V> ParallelArray<V> combine
            (ParallelArray<? extends U> other,
             Combiner<? super T, ? super U, ? extends V> combiner,
             Class<? super V> elementType) {
            int size = upperBound - firstIndex;
            if (other.size() < size)
                throw new ArrayIndexOutOfBoundsException();
            V[] dest = (V[])Array.newInstance(elementType, size);
            ex.invoke(new PAS.FJRCombine(this, firstIndex, upperBound,
                                         null, other.array,
                                         -firstIndex,
                                         dest, combiner));
            return new ParallelArray<V>(ex, dest);
        }

        /**
         * Returns a ParallelArray containing results of
         * applying <tt>combine(thisElement, otherElement)</tt>
         * for each element.
         * @param other the other array segment
         * @param combiner the combiner
         * @return the array of mappings
         * @throws ArrayIndexOutOfBoundsException if other segment is
         * shorter than this array.
         */
        public <U,V> ParallelArray<V> combine
            (ParallelArray.WithBounds<? extends U> other,
             Combiner<? super T, ? super U, ? extends V> combiner) {
            int size = upperBound - firstIndex;
            if (other.size() < size)
                throw new ArrayIndexOutOfBoundsException();
            V[] dest = (V[])new Object[size];
            ex.invoke(new PAS.FJRCombine(this, firstIndex, upperBound,
                                         null, other.pa.array,
                                         other.firstIndex - firstIndex,
                                         dest, combiner));
            return new ParallelArray<V>(ex, dest);
        }

        /**
         * Returns a ParallelArray containing results of
         * applying <tt>combine(thisElement, otherElement)</tt>
         * for each element.
         * @param other the other array segment
         * @param combiner the combiner
         * @param elementType the type of elements of returned array
         * @return the array of mappings
         * @throws ArrayIndexOutOfBoundsException if other array is
         * shorter than this array.
         */
        public <U,V> ParallelArray<V> combine
            (ParallelArray.WithBounds<? extends U> other,
             Combiner<? super T, ? super U, ? extends V> combiner,
             Class<? super V> elementType) {
            int size = upperBound - firstIndex;
            if (other.size() < size)
                throw new ArrayIndexOutOfBoundsException();
            V[] dest = (V[])Array.newInstance(elementType, size);
            ex.invoke(new PAS.FJRCombine(this, firstIndex, upperBound,
                                         null, other.pa.array,
                                         other.firstIndex - firstIndex,
                                         dest, combiner));
            return new ParallelArray<V>(ex, dest);
        }

        public ParallelArray<T> all() {
            final Object[] array = pa.array;
            // For now, avoid copyOf so people can compile with Java5
            int size = upperBound - firstIndex;
            T[] dest = (T[])Array.newInstance
                (array.getClass().getComponentType(), size);
            System.arraycopy(array, firstIndex, dest, 0, size);
            return new ParallelArray<T>(ex, dest);
        }

        public ParallelArray<T> all(Class<? super T> elementType) {
            final Object[] array = pa.array;
            int size = upperBound - firstIndex;
            T[] dest = (T[])Array.newInstance(elementType, size);
            System.arraycopy(array, firstIndex, dest, 0, size);
            return new ParallelArray<T>(ex, dest);
        }

        public ParallelArray<T> allUniqueElements() {
            PAS.RUniquifierTable tab = new PAS.RUniquifierTable
                (upperBound - firstIndex, pa.array, null, false);
            PAS.FJUniquifier f = new PAS.FJUniquifier
                (this, firstIndex, upperBound, null, tab);
            ex.invoke(f);
            T[] res = (T[])(tab.uniqueElements(f.count));
            return new ParallelArray<T>(ex, res);
        }

        public ParallelArray<T> allNonidenticalElements() {
            PAS.RUniquifierTable tab = new PAS.RUniquifierTable
                (upperBound - firstIndex, pa.array, null, true);
            PAS.FJUniquifier f = new PAS.FJUniquifier
                (this, firstIndex, upperBound, null, tab);
            ex.invoke(f);
            T[] res = (T[])(tab.uniqueElements(f.count));
            return new ParallelArray<T>(ex, res);
        }

        /**
         * Returns the index of some element equal to given target, or
         * -1 if not present
         * @param target the element to search for
         * @return the index or -1 if not present
         */
        public int indexOf(T target) {
            AtomicInteger result = new AtomicInteger(-1);
            PAS.FJRIndexOf f = new PAS.FJRIndexOf
                (this, firstIndex, upperBound, null, result, target);
            ex.invoke(f);
            return result.get();
        }

        /**
         * Assuming this array is sorted, returns the index of an
         * element equal to given target, or -1 if not present. If the
         * array is not sorted, the results are undefined.
         * @param target the element to search for
         * @return the index or -1 if not present
         */
        public int binarySearch(T target) {
            final Object[] array = pa.array;
            int lo = firstIndex;
            int hi = upperBound - 1;
            while (lo <= hi) {
                int mid = (lo + hi) >>> 1;
                int c = ((Comparable)target).compareTo((Comparable)array[mid]);
                if (c == 0)
                    return mid;
                else if (c < 0)
                    hi = mid - 1;
                else
                    lo = mid + 1;
            }
            return -1;
        }

        /**
         * Assuming this array is sorted with respect to the given
         * comparator, returns the index of an element equal to given
         * target, or -1 if not present. If the array is not sorted,
         * the results are undefined.
         * @param target the element to search for
         * @param comparator the comparator
         * @return the index or -1 if not present
         */
        public int binarySearch(T target, Comparator<? super T> comparator) {
            Comparator cmp = comparator;
            final Object[] array = pa.array;
            int lo = firstIndex;
            int hi = upperBound - 1;
            while (lo <= hi) {
                int mid = (lo + hi) >>> 1;
                int c = cmp.compare(target, array[mid]);
                if (c == 0)
                    return mid;
                else if (c < 0)
                    hi = mid - 1;
                else
                    lo = mid + 1;
            }
            return -1;
        }

        public int size() {
            return upperBound - firstIndex;
        }

        /**
         * Replaces each element with the running cumulation of applying
         * the given reducer.
         * @param reducer the reducer
         * @param base the result for an empty array
         */
        public void cumulate(Reducer<T> reducer, T base) {
            PAS.FJRCumulateOp op = new PAS.FJRCumulateOp(this, reducer, base);
            PAS.FJRScan r = new PAS.FJRScan(null, op, firstIndex, upperBound);
            ex.invoke(r);
        }

        /**
         * Replaces each element with the cumulation of applying the given
         * reducer to all previous values, and returns the total
         * reduction.
         * @param reducer the reducer
         * @param base the result for an empty array
         * @return the total reduction
         */
        public T precumulate(Reducer<T> reducer, T base) {
            PAS.FJRPrecumulateOp op = new PAS.FJRPrecumulateOp
                (this, reducer, base);
            PAS.FJRScan r = new PAS.FJRScan(null, op, firstIndex, upperBound);
            ex.invoke(r);
            return (T)(r.out);
        }

        /**
         * Sorts the elements.
         * Unlike Arrays.sort, this sort does
         * not guarantee that elements with equal keys maintain their
         * relative position in the array.
         * @param cmp the comparator to use
         */
        public void sort(Comparator<? super T> cmp) {
            final Object[] array = pa.array;
            Class tc = array.getClass().getComponentType();
            T[] ws = (T[])Array.newInstance(tc, upperBound);
            ex.invoke(new PAS.FJRSorter
                      (cmp, array, ws, firstIndex,
                       upperBound - firstIndex, threshold));
        }

        /**
         * Sorts the elements, assuming all elements are
         * Comparable. Unlike Arrays.sort, this sort does not
         * guarantee that elements with equal keys maintain their relative
         * position in the array.
         * @throws ClassCastException if any element is not Comparable.
         */
        public void sort() {
            final Object[] array = pa.array;
            Class tc = array.getClass().getComponentType();
            if (!Comparable.class.isAssignableFrom(tc)) {
                sort(Ops.castedComparator());
                return;
            }
            Comparable[] ca = (Comparable[])array;
            Comparable[] ws = (Comparable[])Array.newInstance(tc, upperBound);
            pa.ex.invoke(new PAS.FJRCSorter
                         (ca, ws, firstIndex,
                          upperBound - firstIndex, threshold));
        }

        public void removeAll() {
            pa.removeSlotsAt(firstIndex, upperBound);
        }

        /**
         * Removes consecutive elements that are equal (or null),
         * shifting others leftward, and possibly decreasing size.  This
         * method may be used after sorting to ensure that this
         * ParallelArray contains a set of unique elements.
         */
        public void removeConsecutiveDuplicates() {
            // Sequential implementation for now
            int k = firstIndex;
            int n = upperBound;
            Object[] arr = pa.array;
            Object last = null;
            for (int i = k; i < n; ++i) {
                Object x = arr[i];
                if (x != null && (last == null || !last.equals(x)))
                    arr[k++] = last = x;
            }
            pa.removeSlotsAt(k, n);
        }

        /**
         * Removes null elements, shifting others leftward, and possibly
         * decreasing size.
         */
        public void removeNulls() {
            // Sequential implementation for now
            int k = firstIndex;
            int n = upperBound;
            Object[] arr = pa.array;
            for (int i = k; i < n; ++i) {
                Object x = arr[i];
                if (x != null)
                    arr[k++] = x;
            }
            pa.removeSlotsAt(k, n);
        }

        void leafApply(int lo, int hi, Procedure procedure) {
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i)
                procedure.apply(array[i]);
        }

        void leafTransform(int lo, int hi, Mapper mapper) {
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i)
                array[i] = mapper.map(array[i]);
        }

        void leafIndexMap(int lo, int hi, MapperFromInt mapper) {
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i)
                array[i] = mapper.map(i);
        }

        void leafGenerate(int lo, int hi, Generator generator) {
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i)
                array[i] = generator.generate();
        }
        void leafFillValue(int lo, int hi, Object value) {
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i)
                array[i] = value;
        }
        void leafCombineInPlace(int lo, int hi, Object[] other,
                                int otherOffset, Reducer combiner) {
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i)
                array[i] = combiner.combine(array[i], other[i+otherOffset]);
        }

        void leafCombine(int lo, int hi, Object[] other, int otherOffset,
                         Object[] dest, Combiner combiner) {
            final Object[] array = pa.array;
            int k = lo - firstIndex;
            for (int i = lo; i < hi; ++i) {
                dest[k] = combiner.combine(array[i], other[i + otherOffset]);
                ++k;
            }
        }

        Object leafReduce(int lo, int hi, Reducer reducer, Object base) {
            if (lo >= hi)
                return base;
            final Object[] array = pa.array;
            Object r = array[lo];
            for (int i = lo+1; i < hi; ++i)
                r = reducer.combine(r, array[i]);
            return r;
        }

        void leafStats(int lo, int hi, PAS.FJRStats task) {
            final Object[] array = pa.array;
            task.size = hi - lo;
            for (int i = lo; i < hi; ++i) {
                Object x = array[i];
                task.updateMin(i, x);
                task.updateMax(i, x);
            }
        }
    }

    static final class WithBoundedFilter<T> extends WithFilter<T> {
        final Predicate<? super T> selector;
        WithBoundedFilter(ParallelArray<T> pa,
                          int firstIndex, int upperBound,
                          Predicate<? super T> selector) {
            super(pa, firstIndex, upperBound);
            this.selector = selector;
        }

        public WithFilter<T> withFilter(Predicate<? super T> selector) {
            return new WithBoundedFilter<T>
                (pa, firstIndex, upperBound,
                 Ops.andPredicate((Predicate)this.selector, selector));
        }

        public WithFilter<T> orFilter(Predicate<? super T> selector) {
            return new WithBoundedFilter<T>
                (pa, firstIndex, upperBound,
                 Ops.orPredicate((Predicate)this.selector, selector));
        }

        public <U> WithMapping<T, U> withMapping
            (Mapper<? super T, ? extends U> mapper) {
            return new WithBoundedFilteredMapping<T,U>
                (pa, firstIndex, upperBound, selector, mapper);
        }

        public WithDoubleMapping<T> withMapping
            (MapperToDouble<? super T> mapper) {
            return new WithBoundedFilteredDoubleMapping<T>
                (pa, firstIndex, upperBound, selector, mapper);
        }

        public WithLongMapping<T> withMapping
            (MapperToLong<? super T> mapper) {
            return new WithBoundedFilteredLongMapping<T>
                (pa, firstIndex, upperBound, selector, mapper);
        }

        public int anyIndex() {
            AtomicInteger result = new AtomicInteger(-1);
            PAS.FJRSelectAny f = new PAS.FJRSelectAny
                (this, firstIndex, upperBound, null, result, selector);
            ex.invoke(f);
            return result.get();
        }

        public T any() {
            int idx = anyIndex();
            final Object[] array = pa.array;
            return (idx < 0)?  null : (T)(array[idx]);
        }

        public ParallelArray<T> all() {
            final Object[] array = pa.array;
            Class<? super T> elementType =
                (Class<? super T>)array.getClass().getComponentType();
            PAS.FJRSelectAllDriver r = new PAS.FJRSelectAllDriver
                (this, elementType);
            ex.invoke(r);
            return new ParallelArray<T>(ex, (T[])(r.results));
        }

        public ParallelArray<T> all(Class<? super T> elementType) {
            PAS.FJRSelectAllDriver r = new PAS.FJRSelectAllDriver
                (this, elementType);
            ex.invoke(r);
            return new ParallelArray<T>(ex, (T[])(r.results));
        }

        public int size() {
            PAS.FJRCountSelected f = new PAS.FJRCountSelected
                (this, firstIndex, upperBound, null, selector);
            ex.invoke(f);
            return f.count;
        }

        public ParallelArray<T> allUniqueElements() {
            PAS.RUniquifierTable tab = new PAS.RUniquifierTable
                (upperBound - firstIndex, pa.array, selector, false);
            PAS.FJUniquifier f = new PAS.FJUniquifier
                (this, firstIndex, upperBound, null, tab);
            ex.invoke(f);
            T[] res = (T[])(tab.uniqueElements(f.count));
            return new ParallelArray<T>(ex, res);
        }

        public ParallelArray<T> allNonidenticalElements() {
            PAS.RUniquifierTable tab = new PAS.RUniquifierTable
                (upperBound - firstIndex, pa.array, selector, true);
            PAS.FJUniquifier f = new PAS.FJUniquifier
                (this, firstIndex, upperBound, null, tab);
            ex.invoke(f);
            T[] res = (T[])(tab.uniqueElements(f.count));
            return new ParallelArray<T>(ex, res);
        }

        public void removeAll() {
            PAS.FJRemoveAllDriver f = new PAS.FJRemoveAllDriver
                (this, firstIndex, upperBound);
            ex.invoke(f);
            pa.removeSlotsAt(f.offset, upperBound);
        }

        void leafApply(int lo, int hi, Procedure  procedure) {
            final Predicate sel = selector;
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i) {
                Object x = array[i];
                if (sel.evaluate(x))
                    procedure.apply(x);
            }
        }

        void leafTransform(int lo, int hi, Mapper mapper) {
            final Predicate sel = selector;
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i) {
                Object x = array[i];
                if (sel.evaluate(x))
                    array[i] = mapper.map(x);
            }
        }
        void leafIndexMap(int lo, int hi, MapperFromInt mapper) {
            final Predicate sel = selector;
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i) {
                Object x = array[i];
                if (sel.evaluate(x))
                    array[i] = mapper.map(i);
            }
        }

        void leafGenerate(int lo, int hi, Generator generator) {
            final Predicate sel = selector;
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i) {
                Object x = array[i];
                if (sel.evaluate(x))
                    array[i] = generator.generate();
            }
        }
        void leafFillValue(int lo, int hi, Object value) {
            final Predicate sel = selector;
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i) {
                Object x = array[i];
                if (sel.evaluate(x))
                    array[i] = value;
            }
        }
        void leafCombineInPlace(int lo, int hi, Object[] other,
                                int otherOffset, Reducer combiner) {
            final Predicate sel = selector;
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i) {
                Object x = array[i];
                if (sel.evaluate(x))
                    array[i] = combiner.combine(x, other[i+otherOffset]);
            }
        }

        Object leafReduce(int lo, int hi, Reducer reducer, Object base) {
            final Predicate sel = selector;
            boolean gotFirst = false;
            Object r = base;
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i) {
                Object x = array[i];
                if (sel.evaluate(x)) {
                    if (!gotFirst) {
                        gotFirst = true;
                        r = x;
                    }
                    else
                        r = reducer.combine(r, x);
                }
            }
            return r;
        }

        void leafStats(int lo, int hi, PAS.FJRStats task) {
            final Predicate sel = selector;
            final Object[] array = pa.array;
            int count = 0;
            for (int i = lo; i < hi; ++i) {
                Object x = array[i];
                if (sel.evaluate(x)) {
                    ++count;
                    task.updateMin(i, x);
                    task.updateMax(i, x);
                }
            }
            task.size = count;
        }

        int leafIndexSelected(int lo, int hi, boolean positive, int[] indices){
            final Predicate sel = selector;
            final Object[] array = pa.array;
            int k = 0;
            for (int i = lo; i < hi; ++i) {
                if (sel.evaluate(array[i]) == positive)
                    indices[lo + k++] = i;
            }
            return k;
        }

        int leafMoveSelected(int lo, int hi, int offset, boolean positive) {
            final Predicate sel = selector;
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i) {
                Object t = array[i];
                if (sel.evaluate(t) == positive)
                    array[offset++] = t;
            }
            return offset;
        }
    }

    static final class WithBoundedMapping<T,U> extends WithMapping<T,U> {
        final Mapper<? super T, ? extends U> mapper;
        WithBoundedMapping(ParallelArray<T> pa,
                           int firstIndex, int upperBound,
                           Mapper<? super T, ? extends U> mapper) {
            super(pa, firstIndex, upperBound);
            this.mapper = mapper;
        }

        public ParallelArray<U> all() {
            int n = upperBound - firstIndex;
            U[] dest = (U[])new Object[n];
            PAS.FJRMap f = new PAS.FJRMap
                (this, firstIndex, upperBound, null, dest, firstIndex);
            ex.invoke(f);
            return new ParallelArray<U>(ex, dest);
        }

        public ParallelArray<U> all(Class<? super U> elementType) {
            int n = upperBound - firstIndex;
            U[] dest = (U[])Array.newInstance(elementType, n);
            PAS.FJRMap f = new PAS.FJRMap
                (this, firstIndex, upperBound, null, dest, 0);
            ex.invoke(f);
            return new ParallelArray<U>(ex, dest);
        }

        public int size() {
            return upperBound - firstIndex;
        }

        public int anyIndex() {
            return (firstIndex < upperBound)? firstIndex : -1;
        }

        public U any() {
            final Mapper mpr = mapper;
            final Object[] array = pa.array;
            return (firstIndex < upperBound)?
                (U)(mpr.map(array[firstIndex])) : null;
        }

        public <V> WithMapping<T, V> withMapping
            (Mapper<? super U, ? extends V> mapper) {
            return new WithBoundedMapping<T,V>
                (pa, firstIndex, upperBound,
                 Ops.compoundMapper(this.mapper, mapper));
        }

        public WithDoubleMapping<T> withMapping
            (MapperToDouble<? super U> mapper) {
            return new WithBoundedDoubleMapping
                (pa, firstIndex, upperBound,
                 Ops.compoundMapper(this.mapper, mapper));
        }

        public WithLongMapping<T> withMapping
            (MapperToLong<? super U> mapper) {
            return new WithBoundedLongMapping
                (pa, firstIndex, upperBound,
                 Ops.compoundMapper(this.mapper, mapper));
        }

        void leafApply(int lo, int hi, Procedure  procedure) {
            final Mapper mpr = mapper;
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i)
                procedure.apply(mpr.map(array[i]));
        }

        Object leafReduce(int lo, int hi, Reducer reducer, Object base) {
            if (lo >= hi)
                return base;
            final Object[] array = pa.array;
            final Mapper mpr = mapper;
            Object r = mpr.map(array[lo]);
            for (int i = lo+1; i < hi; ++i)
                r = reducer.combine(r, mpr.map(array[i]));
            return r;
        }

        void leafStats(int lo, int hi, PAS.FJRStats task) {
            final Object[] array = pa.array;
            final Mapper mpr = mapper;
            task.size = hi - lo;
            for (int i = lo; i < hi; ++i) {
                Object x = mpr.map(array[i]);
                task.updateMin(i, x);
                task.updateMax(i, x);
            }
        }

        void leafTransfer(int lo, int hi, Object[] dest, int offset) {
            final Mapper mpr = mapper;
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i)
                dest[offset++] = mpr.map(array[i]);
        }

        void leafTransferByIndex(int[] indices, int loIdx, int hiIdx,
                                 Object[] dest, int offset) {
            final Object[] array = pa.array;
            final Mapper mpr = mapper;
            for (int i = loIdx; i < hiIdx; ++i)
                dest[offset++] = mpr.map(array[indices[i]]);
        }
    }

    static final class WithBoundedFilteredMapping<T,U>
        extends WithMapping<T,U> {
        final Predicate<? super T> selector;
        final Mapper<? super T, ? extends U> mapper;
        WithBoundedFilteredMapping(ParallelArray<T> pa,
                                   int firstIndex, int upperBound,
                                   Predicate<? super T> selector,
                                   Mapper<? super T, ? extends U> mapper) {
            super(pa, firstIndex, upperBound);
            this.selector = selector;
            this.mapper = mapper;
        }

        public ParallelArray<U> all() {
            PAS.FJRSelectAllDriver r = new PAS.FJRSelectAllDriver
                (this, Object.class);
            ex.invoke(r);
            return new ParallelArray<U>(ex, (U[])(r.results));
        }

        public ParallelArray<U> all(Class<? super U> elementType) {
            PAS.FJRSelectAllDriver r = new PAS.FJRSelectAllDriver
                (this, elementType);
            ex.invoke(r);
            return new ParallelArray<U>(ex, (U[])(r.results));
        }

        public int size() {
            PAS.FJRCountSelected f = new PAS.FJRCountSelected
                (this, firstIndex, upperBound, null, selector);
            ex.invoke(f);
            return f.count;
        }

        public int anyIndex() {
            AtomicInteger result = new AtomicInteger(-1);
            PAS.FJRSelectAny f = new PAS.FJRSelectAny
                (this, firstIndex, upperBound, null, result, selector);
            ex.invoke(f);
            return result.get();
        }

        public U any() {
            int idx = anyIndex();
            final Object[] array = pa.array;
            final Mapper mpr = mapper;
            return (idx < 0)?  null : (U)(mpr.map(array[idx]));
        }

        public <V> WithMapping<T, V> withMapping
            (Mapper<? super U, ? extends V> mapper) {
            return new WithBoundedFilteredMapping<T,V>
                (pa, firstIndex, upperBound, selector,
                 Ops.compoundMapper(this.mapper, mapper));
        }

        public WithDoubleMapping<T> withMapping
            (MapperToDouble<? super U> mapper) {
            return new WithBoundedFilteredDoubleMapping<T>
                (pa, firstIndex, upperBound, selector,
                 Ops.compoundMapper(this.mapper, mapper));
        }

        public WithLongMapping<T> withMapping
            (MapperToLong<? super U> mapper) {
            return new WithBoundedFilteredLongMapping<T>
                (pa, firstIndex, upperBound, selector,
                 Ops.compoundMapper(this.mapper, mapper));
        }

        void leafApply(int lo, int hi, Procedure  procedure) {
            final Predicate sel = selector;
            final Object[] array = pa.array;
            final Mapper mpr = mapper;
            for (int i = lo; i < hi; ++i) {
                Object x = array[i];
                if (sel.evaluate(x))
                    procedure.apply(mpr.map(x));
            }
        }
        Object leafReduce(int lo, int hi, Reducer reducer, Object base) {
            final Predicate sel = selector;
            final Object[] array = pa.array;
            final Mapper mpr = mapper;
            boolean gotFirst = false;
            Object r = base;
            for (int i = lo; i < hi; ++i) {
                Object x = array[i];
                if (sel.evaluate(x)) {
                    Object y = mpr.map(x);
                    if (!gotFirst) {
                        gotFirst = true;
                        r = y;
                    }
                    else
                        r = reducer.combine(r, y);
                }
            }
            return r;
        }

        void leafStats(int lo, int hi, PAS.FJRStats task) {
            final Predicate sel = selector;
            final Object[] array = pa.array;
            final Mapper mpr = mapper;
            int count = 0;
            for (int i = lo; i < hi; ++i) {
                Object t = array[i];
                if (sel.evaluate(t)) {
                    ++count;
                    Object x = mpr.map(t);
                    task.updateMin(i, x);
                    task.updateMax(i, x);
                }
            }
            task.size = count;
        }

        void leafTransfer(int lo, int hi, Object[] dest, int offset) {
            final Object[] array = pa.array;
            final Mapper mpr = mapper;
            for (int i = lo; i < hi; ++i)
                dest[offset++] = mpr.map(array[i]);
        }

        void leafTransferByIndex(int[] indices, int loIdx, int hiIdx,
                                 Object[] dest, int offset) {
            final Object[] array = pa.array;
            final Mapper mpr = mapper;
            for (int i = loIdx; i < hiIdx; ++i)
                dest[offset++] = mpr.map(array[indices[i]]);
        }

        int leafIndexSelected(int lo, int hi, boolean positive, int[] indices){
            final Predicate sel = selector;
            final Object[] array = pa.array;
            int k = 0;
            for (int i = lo; i < hi; ++i) {
                if (sel.evaluate(array[i]) == positive)
                    indices[lo + k++] = i;
            }
            return k;
        }

        int leafMoveSelected(int lo, int hi, int offset, boolean positive) {
            final Predicate sel = selector;
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i) {
                Object t = array[i];
                if (sel.evaluate(t) == positive)
                    array[offset++] = t;
            }
            return offset;
        }
    }

    /**
     * A modifier for parallel array operations to apply to mappings
     * of elements to doubles, not to the elements themselves
     */
    public static abstract class WithDoubleMapping<T> extends PAS.RPrefix {
        final MapperToDouble<? super T> mapper;
        WithDoubleMapping(ParallelArray<T> pa,
                          int firstIndex, int upperBound,
                          MapperToDouble<? super T> mapper) {
            super(pa, firstIndex, upperBound);
            this.mapper = mapper;
        }

        /**
         * Applies the given procedure
         * @param procedure the procedure
         */
        public void apply(DoubleProcedure procedure) {
            ex.invoke(new PAS.FJDApply
                      (this, firstIndex, upperBound, null, procedure));
        }

        /**
         * Returns reduction of mapped elements
         * @param reducer the reducer
         * @param base the result for an empty array
         * @return reduction
         */
        public double reduce(DoubleReducer reducer, double base) {
            PAS.FJDReduce f = new PAS.FJDReduce
                (this, firstIndex, upperBound, null, reducer, base);
            ex.invoke(f);
            return f.result;
        }

        /**
         * Returns the minimum element, or Double.MAX_VALUE if empty
         * @return minimum element, or Double.MAX_VALUE if empty
         */
        public double min() {
            return reduce(naturalDoubleMinReducer(), Double.MAX_VALUE);
        }

        /**
         * Returns the minimum element, or Double.MAX_VALUE if empty
         * @param comparator the comparator
         * @return minimum element, or Double.MAX_VALUE if empty
         */
        public double min(DoubleComparator comparator) {
            return reduce(doubleMinReducer(comparator),
                          Double.MAX_VALUE);
        }

        /**
         * Returns the maximum element, or -Double.MAX_VALUE if empty
         * @return maximum element, or -Double.MAX_VALUE if empty
         */
        public double max() {
            return reduce(naturalDoubleMaxReducer(), -Double.MAX_VALUE);
        }

        /**
         * Returns the maximum element, or -Double.MAX_VALUE if empty
         * @param comparator the comparator
         * @return maximum element, or -Double.MAX_VALUE if empty
         */
        public double max(DoubleComparator comparator) {
            return reduce(doubleMaxReducer(comparator),
                          -Double.MAX_VALUE);
        }

        /**
         * Returns the sum of elements
         * @return the sum of elements
         */
        public double sum() {
            return reduce(Ops.doubleAdder(), 0.0);
        }

        /**
         * Returns summary statistics
         * @param comparator the comparator to use for
         * locating minimum and maximum elements
         * @return the summary.
         */
        public ParallelDoubleArray.SummaryStatistics summary
            (DoubleComparator comparator) {
            PAS.FJDStats f = new PAS.FJDStats
                (this, firstIndex, upperBound, null, comparator);
            ex.invoke(f);
            return f;
        }

        /**
         * Returns summary statistics, using natural comparator
         * @return the summary.
         */
        public ParallelDoubleArray.SummaryStatistics summary() {
            PAS.FJDStats f = new PAS.FJDStats
                (this, firstIndex, upperBound, null,
                 naturalDoubleComparator());
            ex.invoke(f);
            return f;
        }

        /**
         * Returns a new ParallelDoubleArray holding mappings
         * @return a new ParallelDoubleArray holding mappings
         */
        public abstract ParallelDoubleArray all();

        /**
         * Return the number of elements selected using bound or
         * filter restrictions. Note that this method must evaluate
         * all selectors to return its result.
         * @return the number of elements
         */
        public abstract int size();

        /**
         * Returns the index of some element matching bound and filter
         * constraints, or -1 if none.
         * @return index of matching element, or -1 if none.
         */
        public abstract int anyIndex();

        /**
         * Returns an operation prefix that causes a method to operate
         * on mapped elements of the array using the given mapper.
         * @param mapper the mapper
         * @return operation prefix
         */
        public abstract WithDoubleMapping<T> withMapping
            (DoubleMapper mapper);

        /**
         * Returns an operation prefix that causes a method to operate
         * on mapped elements of the array using the given mapper.
         * @param mapper the mapper
         * @return operation prefix
         */
        public abstract WithLongMapping<T> withMapping
            (MapperFromDoubleToLong mapper);

        /**
         * Returns an operation prefix that causes a method to operate
         * on mapped elements of the array using the given mapper.
         * @param mapper the mapper
         * @return operation prefix
         */
        public abstract <U> WithMapping<T, U> withMapping
            (MapperFromDouble<? extends U> mapper);

        final void leafTransfer(int lo, int hi, double[] dest, int offset) {
            final MapperToDouble mpr = mapper;
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i)
                dest[offset++] = mpr.map(array[i]);
        }

        final void leafTransferByIndex(int[] indices, int loIdx, int hiIdx,
                                       double[] dest, int offset) {
            final Object[] array = pa.array;
            final MapperToDouble mpr = mapper;
            for (int i = loIdx; i < hiIdx; ++i)
                dest[offset++] = mpr.map(array[indices[i]]);
        }

    }

    static final class WithBoundedDoubleMapping<T>
        extends WithDoubleMapping<T> {
        WithBoundedDoubleMapping(ParallelArray<T> pa,
                                 int firstIndex, int upperBound,
                                 MapperToDouble<? super T> mapper) {
            super(pa, firstIndex, upperBound, mapper);
        }

        public ParallelDoubleArray all() {
            double[] dest = new double[upperBound - firstIndex];
            PAS.FJDMap f = new PAS.FJDMap
                (this, firstIndex, upperBound, null, dest, firstIndex);
            ex.invoke(f);
            return new ParallelDoubleArray(ex, dest);
        }

        public int size() {
            return upperBound - firstIndex;
        }

        public int anyIndex() {
            return (firstIndex < upperBound)? firstIndex : -1;
        }

        public WithDoubleMapping<T> withMapping
            (DoubleMapper mapper) {
            return new WithBoundedDoubleMapping<T>
                (pa, firstIndex, upperBound,
                 Ops.compoundMapper(this.mapper, mapper));
        }

        public WithLongMapping<T> withMapping
            (MapperFromDoubleToLong mapper) {
            return new WithBoundedLongMapping<T>
                (pa, firstIndex, upperBound,
                 Ops.compoundMapper(this.mapper, mapper));
        }

        public <U> WithMapping<T, U> withMapping
            (MapperFromDouble<? extends U> mapper) {
            return new WithBoundedMapping<T,U>
                (pa, firstIndex, upperBound,
                 Ops.compoundMapper(this.mapper, mapper));
        }

        void leafApply(int lo, int hi, DoubleProcedure procedure) {
            final MapperToDouble mpr = mapper;
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i)
                procedure.apply(mpr.map(array[i]));
        }

        double leafReduce(int lo, int hi, DoubleReducer reducer, double base) {
            if (lo >= hi)
                return base;
            final Object[] array = pa.array;
            final MapperToDouble mpr = mapper;
            double r = mpr.map(array[lo]);
            for (int i = lo+1; i < hi; ++i)
                r = reducer.combine(r, mpr.map(array[i]));
            return r;
        }

        void leafStats(int lo, int hi, PAS.FJDStats task) {
            final Object[] array = pa.array;
            final MapperToDouble mpr = mapper;
            task.size = hi - lo;
            for (int i = lo; i < hi; ++i) {
                double x = mpr.map(array[i]);
                task.sum += x;
                task.updateMin(i, x);
                task.updateMax(i, x);
            }
        }
    }

    static final class WithBoundedFilteredDoubleMapping<T>
        extends WithDoubleMapping<T> {
        final Predicate<? super T> selector;
        WithBoundedFilteredDoubleMapping
            (ParallelArray<T> pa, int firstIndex, int upperBound,
             Predicate<? super T> selector, MapperToDouble<? super T> mapper) {
            super(pa, firstIndex, upperBound, mapper);
            this.selector = selector;
        }

        public ParallelDoubleArray all() {
            PAS.FJDSelectAllDriver r = new PAS.FJDSelectAllDriver(this);
            ex.invoke(r);
            return new ParallelDoubleArray(ex, r.results);
        }

        public int size() {
            PAS.FJRCountSelected f = new PAS.FJRCountSelected
                (this, firstIndex, upperBound, null, selector);
            ex.invoke(f);
            return f.count;
        }

        public int anyIndex() {
            AtomicInteger result = new AtomicInteger(-1);
            PAS.FJRSelectAny f = new PAS.FJRSelectAny
                (this, firstIndex, upperBound, null, result, selector);
            ex.invoke(f);
            return result.get();
        }

        public WithDoubleMapping<T> withMapping
            (DoubleMapper mapper) {
            return new WithBoundedFilteredDoubleMapping<T>
                (pa, firstIndex, upperBound, selector,
                 Ops.compoundMapper(this.mapper, mapper));
        }

        public WithLongMapping<T> withMapping
            (MapperFromDoubleToLong mapper) {
            return new WithBoundedFilteredLongMapping<T>
                (pa, firstIndex, upperBound, selector,
                 Ops.compoundMapper(this.mapper, mapper));
        }

        public <U> WithMapping<T, U> withMapping
            (MapperFromDouble<? extends U> mapper) {
            return new WithBoundedFilteredMapping<T,U>
                (pa, firstIndex, upperBound, selector,
                 Ops.compoundMapper(this.mapper, mapper));
        }

        void leafApply(int lo, int hi, DoubleProcedure procedure) {
            final Predicate sel = selector;
            final Object[] array = pa.array;
            final MapperToDouble mpr = mapper;
            for (int i = lo; i < hi; ++i) {
                Object x = array[i];
                if (sel.evaluate(x))
                    procedure.apply(mpr.map(x));
            }
        }

        double leafReduce(int lo, int hi, DoubleReducer reducer, double base) {
            final Predicate sel = selector;
            final MapperToDouble mpr = mapper;
            boolean gotFirst = false;
            double r = base;
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i) {
                Object t = array[i];
                if (sel.evaluate(t)) {
                    double y = mpr.map(t);
                    if (!gotFirst) {
                        gotFirst = true;
                        r = y;
                    }
                    else
                        r = reducer.combine(r, y);
                }
            }
            return r;
        }

        void leafStats(int lo, int hi, PAS.FJDStats task) {
            final Predicate sel = selector;
            final Object[] array = pa.array;
            final MapperToDouble mpr = mapper;
            int count = 0;
            for (int i = lo; i < hi; ++i) {
                Object t = array[i];
                if (sel.evaluate(t)) {
                    ++count;
                    double x = mpr.map(t);
                    task.sum += x;
                    task.updateMin(i, x);
                    task.updateMax(i, x);
                }
            }
            task.size = count;
        }

        int leafIndexSelected(int lo, int hi, boolean positive, int[] indices){
            final Predicate sel = selector;
            final Object[] array = pa.array;
            int k = 0;
            for (int i = lo; i < hi; ++i) {
                if (sel.evaluate(array[i]) == positive)
                    indices[lo + k++] = i;
            }
            return k;
        }

        int leafMoveSelected(int lo, int hi, int offset, boolean positive) {
            final Predicate sel = selector;
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i) {
                Object t = array[i];
                if (sel.evaluate(t) == positive)
                    array[offset++] = t;
            }
            return offset;
        }
    }

    /**
     * A modifier for parallel array operations to apply to mappings
     * of elements to longs, not to the elements themselves
     */
    public static abstract class WithLongMapping<T> extends PAS.RPrefix {
        final MapperToLong<? super T> mapper;
        WithLongMapping(ParallelArray<T> pa,
                        int firstIndex, int upperBound,
                        final MapperToLong<? super T> mapper) {
            super(pa, firstIndex, upperBound);
            this.mapper = mapper;
        }

        /**
         * Applies the given procedure
         * @param procedure the procedure
         */
        public void apply(LongProcedure procedure) {
            ex.invoke(new PAS.FJLApply
                      (this, firstIndex, upperBound, null, procedure));
        }

        /**
         * Returns reduction of mapped elements
         * @param reducer the reducer
         * @param base the result for an empty array
         * @return reduction
         */
        public long reduce(LongReducer reducer, long base) {
            PAS.FJLReduce f = new PAS.FJLReduce
                (this, firstIndex, upperBound, null, reducer, base);
            ex.invoke(f);
            return f.result;
        }

        /**
         * Returns the minimum element, or Long.MAX_VALUE if empty
         * @return minimum element, or Long.MAX_VALUE if empty
         */
        public long min() {
            return reduce(naturalLongMinReducer(), Long.MAX_VALUE);
        }

        /**
         * Returns the minimum element, or Long.MAX_VALUE if empty
         * @param comparator the comparator
         * @return minimum element, or Long.MAX_VALUE if empty
         */
        public long min(LongComparator comparator) {
            return reduce(longMinReducer(comparator),
                          Long.MAX_VALUE);
        }

        /**
         * Returns the maximum element, or Long.MIN_VALUE if empty
         * @return maximum element, or Long.MIN_VALUE if empty
         */
        public long max() {
            return reduce(naturalLongMaxReducer(), Long.MIN_VALUE);
        }

        /**
         * Returns the maximum element, or Long.MIN_VALUE if empty
         * @param comparator the comparator
         * @return maximum element, or Long.MIN_VALUE if empty
         */
        public long max(LongComparator comparator) {
            return reduce(longMaxReducer(comparator),
                          Long.MIN_VALUE);
        }

        /**
         * Returns the sum of elements
         * @return the sum of elements
         */
        public long sum() {
            return reduce(Ops.longAdder(), 0L);
        }

        /**
         * Returns summary statistics
         * @param comparator the comparator to use for
         * locating minimum and maximum elements
         * @return the summary.
         */
        public ParallelLongArray.SummaryStatistics summary
            (LongComparator comparator) {
            PAS.FJLStats f = new PAS.FJLStats
                (this, firstIndex, upperBound, null, comparator);
            ex.invoke(f);
            return f;
        }

        /**
         * Returns summary statistics, using natural comparator
         * @return the summary.
         */
        public ParallelLongArray.SummaryStatistics summary() {
            PAS.FJLStats f = new PAS.FJLStats
                (this, firstIndex, upperBound, null,
                 naturalLongComparator());
            ex.invoke(f);
            return f;
        }

        /**
         * Returns a new ParallelLongArray holding mappings
         * @return a new ParallelLongArray holding mappings
         */
        public abstract ParallelLongArray all();

        /**
         * Return the number of elements selected using bound or
         * filter restrictions. Note that this method must evaluate
         * all selectors to return its result.
         * @return the number of elements
         */
        public abstract int size();

        /**
         * Returns the index of some element matching bound and filter
         * constraints, or -1 if none.
         * @return index of matching element, or -1 if none.
         */
        public abstract int anyIndex();

        /**
         * Returns an operation prefix that causes a method to operate
         * on mapped elements of the array using the given mapper.
         * @param mapper the mapper
         * @return operation prefix
         */
        public abstract WithDoubleMapping<T> withMapping
            (MapperFromLongToDouble mapper);

        /**
         * Returns an operation prefix that causes a method to operate
         * on mapped elements of the array using the given mapper.
         * @param mapper the mapper
         * @return operation prefix
         */
        public abstract WithLongMapping<T> withMapping
            (LongMapper mapper);

        /**
         * Returns an operation prefix that causes a method to operate
         * on mapped elements of the array using the given mapper.
         * @param mapper the mapper
         * @return operation prefix
         */
        public abstract <U> WithMapping<T, U> withMapping
            (MapperFromLong<? extends U> mapper);

        final void leafTransfer(int lo, int hi, long[] dest, int offset) {
            final MapperToLong mpr = mapper;
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i)
                dest[offset++] = mpr.map(array[i]);
        }

        final void leafTransferByIndex(int[] indices, int loIdx, int hiIdx,
                                       long[] dest, int offset) {
            final Object[] array = pa.array;
            final MapperToLong mpr = mapper;
            for (int i = loIdx; i < hiIdx; ++i)
                dest[offset++] = mpr.map(array[indices[i]]);
        }
    }

    static final class WithBoundedLongMapping<T>
        extends WithLongMapping<T> {
        WithBoundedLongMapping(ParallelArray<T> pa,
                               int firstIndex, int upperBound,
                               MapperToLong<? super T> mapper) {
            super(pa, firstIndex, upperBound, mapper);
        }

        public ParallelLongArray all() {
            long[] dest = new long[upperBound - firstIndex];
            PAS.FJLMap f = new PAS.FJLMap
                (this, firstIndex, upperBound, null, dest, firstIndex);
            ex.invoke(f);
            return new ParallelLongArray(ex, dest);
        }

        public int size() {
            return upperBound - firstIndex;
        }

        public int anyIndex() {
            return (firstIndex < upperBound)? firstIndex : -1;
        }

        public WithDoubleMapping<T> withMapping
            (MapperFromLongToDouble mapper) {
            return new WithBoundedDoubleMapping<T>
                (pa, firstIndex, upperBound,
                 Ops.compoundMapper(this.mapper, mapper));
        }

        public WithLongMapping<T> withMapping
            (LongMapper mapper) {
            return new WithBoundedLongMapping<T>
                (pa, firstIndex, upperBound,
                 Ops.compoundMapper(this.mapper, mapper));
        }

        public <U> WithMapping<T, U> withMapping
            (MapperFromLong<? extends U> mapper) {
            return new WithBoundedMapping<T,U>
                (pa, firstIndex, upperBound,
                 Ops.compoundMapper(this.mapper, mapper));
        }

        void leafApply(int lo, int hi, LongProcedure procedure) {
            final Object[] array = pa.array;
            final MapperToLong mpr = mapper;
            for (int i = lo; i < hi; ++i)
                procedure.apply(mpr.map(array[i]));
        }

        long leafReduce(int lo, int hi, LongReducer reducer, long base) {
            if (lo >= hi)
                return base;
            final Object[] array = pa.array;
            final MapperToLong mpr = mapper;
            long r = mpr.map(array[lo]);
            for (int i = lo+1; i < hi; ++i)
                r = reducer.combine(r, mpr.map(array[i]));
            return r;
        }

        void leafStats(int lo, int hi, PAS.FJLStats task) {
            final Object[] array = pa.array;
            final MapperToLong mpr = mapper;
            task.size = hi - lo;
            for (int i = lo; i < hi; ++i) {
                long x = mpr.map(array[i]);
                task.sum += x;
                task.updateMin(i, x);
                task.updateMax(i, x);
            }
        }

    }

    static final class WithBoundedFilteredLongMapping<T>
        extends WithLongMapping<T> {
        final Predicate<? super T> selector;
        WithBoundedFilteredLongMapping
            (ParallelArray<T> pa, int firstIndex, int upperBound,
             Predicate<? super T> selector, MapperToLong<? super T> mapper) {
            super(pa, firstIndex, upperBound, mapper);
            this.selector = selector;
        }
        public ParallelLongArray all() {
            PAS.FJLSelectAllDriver r = new PAS.FJLSelectAllDriver(this);
            ex.invoke(r);
            return new ParallelLongArray(ex, r.results);
        }

        public int size() {
            PAS.FJRCountSelected f = new PAS.FJRCountSelected
                (this, firstIndex, upperBound, null, selector);
            ex.invoke(f);
            return f.count;
        }

        public int anyIndex() {
            AtomicInteger result = new AtomicInteger(-1);
            PAS.FJRSelectAny f = new PAS.FJRSelectAny
                (this, firstIndex, upperBound, null, result, selector);
            ex.invoke(f);
            return result.get();
        }

        public WithDoubleMapping<T> withMapping
            (MapperFromLongToDouble mapper) {
            return new WithBoundedFilteredDoubleMapping<T>
                (pa, firstIndex, upperBound, selector,
                 Ops.compoundMapper(this.mapper, mapper));
        }

        public WithLongMapping<T> withMapping
            (LongMapper mapper) {
            return new WithBoundedFilteredLongMapping<T>
                (pa, firstIndex, upperBound, selector,
                 Ops.compoundMapper(this.mapper, mapper));
        }

        public <U> WithMapping<T, U> withMapping
            (MapperFromLong<? extends U> mapper) {
            return new WithBoundedFilteredMapping<T,U>
                (pa, firstIndex, upperBound, selector,
                 Ops.compoundMapper(this.mapper, mapper));
        }

        void leafApply(int lo, int hi, LongProcedure procedure) {
            final Predicate sel = selector;
            final Object[] array = pa.array;
            final MapperToLong mpr = mapper;
            for (int i = lo; i < hi; ++i) {
                Object x = array[i];
                if (sel.evaluate(x))
                    procedure.apply(mpr.map(x));
            }
        }

        long leafReduce(int lo, int hi, LongReducer reducer, long base) {
            final Predicate sel = selector;
            final MapperToLong mpr = mapper;
            boolean gotFirst = false;
            long r = base;
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i) {
                Object t = array[i];
                if (sel.evaluate(t)) {
                    long y = mpr.map(t);
                    if (!gotFirst) {
                        gotFirst = true;
                        r = y;
                    }
                    else
                        r = reducer.combine(r, y);
                }
            }
            return r;
        }

        void leafStats(int lo, int hi, PAS.FJLStats task) {
            final Predicate sel = selector;
            final Object[] array = pa.array;
            final MapperToLong mpr = mapper;
            int count = 0;
            for (int i = lo; i < hi; ++i) {
                Object t = array[i];
                if (sel.evaluate(t)) {
                    ++count;
                    long x = mpr.map(t);
                    task.sum += x;
                    task.updateMin(i, x);
                    task.updateMax(i, x);
                }
            }
            task.size = count;
        }

        int leafIndexSelected(int lo, int hi, boolean positive, int[] indices){
            final Predicate sel = selector;
            final Object[] array = pa.array;
            int k = 0;
            for (int i = lo; i < hi; ++i) {
                if (sel.evaluate(array[i]) == positive)
                    indices[lo + k++] = i;
            }
            return k;
        }

        int leafMoveSelected(int lo, int hi, int offset, boolean positive) {
            final Predicate sel = selector;
            final Object[] array = pa.array;
            for (int i = lo; i < hi; ++i) {
                Object t = array[i];
                if (sel.evaluate(t) == positive)
                    array[offset++] = t;
            }
            return offset;
        }
    }

    /**
     * Returns an iterator stepping through each element of the array
     * up to the current limit. This iterator does <em>not</em>
     * support the remove operation. However, a full
     * <tt>ListIterator</tt> supporting add, remove, and set
     * operations is available via {@link #asList}.
     * @return an iterator stepping through each element.
     */
    public Iterator<T> iterator() {
        return new ParallelArrayIterator<T>(array, limit);
    }

    static final class ParallelArrayIterator<T> implements Iterator<T> {
        int cursor;
        final T[] arr;
        final int hi;
        ParallelArrayIterator(T[] a, int limit) { arr = a; hi = limit; }
        public boolean hasNext() { return cursor < hi; }
        public T next() {
            if (cursor >= hi)
                throw new NoSuchElementException();
            return arr[cursor++];
        }
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }

    // List support

    /**
     * Returns a view of this ParallelArray as a List. This List has
     * the same structural and performance characteristics as {@link
     * ArrayList}, and may be used to modify, replace or extend the
     * bounds of the array underlying this ParallelArray.  The methods
     * supported by this list view are <em>not</em> in general
     * implemented as parallel operations. This list is also not
     * itself thread-safe.  In particular, performing list updates
     * while other parallel operations are in progress has undefined
     * (and surely undesired) effects.
     * @return a list view
     */
    public List<T> asList() {
        AsList lv = listView;
        if (lv == null)
            listView = lv = new AsList();
        return lv;
    }

    /**
     * Returns the effective size of the underlying array. The
     * effective size is the current limit, if used (see {@link
     * #setLimit}), or the length of the array otherwise.
     * @return the effective size of array
     */
    public int size() { return limit; }

    /**
     * Returns the element of the array at the given index
     * @param i the index
     * @return the element of the array at the given index
     */
    public T get(int i) { return array[i]; }

    /**
     * Sets the element of the array at the given index to the given value
     * @param i the index
     * @param x the value
     */
    public void set(int i, T x) { array[i] = x; }

    /**
     * Returns the underlying array used for computations
     * @return the array
     */
    public T[] getArray() { return array; }

    /**
     * Equivalent to <tt>asList().toString()</tt>
     * @return a string representation
     */
    public String toString() {
        return asList().toString();
    }

    /**
     * Equivalent to <tt>AsList.addAll</tt> but specialized for array
     * arguments and likely to be more efficient.
     * @param other the elements to add
     */
    public void addAll(T[] other) {
        int csize = other.length;
        int end = limit;
        insertSlotsAt(end, csize);
        System.arraycopy(other, 0, array, end, csize);
    }

    /**
     * Equivalent to <tt>AsList.addAll</tt> but specialized for
     * ParallelArray arguments and likely to be more efficient.
     * @param other the elements to add
     */
    public void addAll(ParallelArray<T> other) {
        int csize = other.size();
        int end = limit;
        insertSlotsAt(end, csize);
        System.arraycopy(other.array, 0, array, end, csize);
    }

    /**
     * Equivalent to <tt>AsList.addAll</tt> but specialized for
     * ParallelArray arguments and likely to be more efficient.
     * @param other the elements to add
     */
    public void addAll(ParallelArray.WithBounds<T> other) {
        int csize = other.size();
        int end = limit;
        insertSlotsAt(end, csize);
        System.arraycopy(other.pa.array, other.firstIndex, array, end, csize);
    }

    /**
     * Ensures that the underlying array can be accessed up to the
     * given upper bound, reallocating and copying the underlying
     * array to expand if necessary. Or, if the given limit is less
     * than the length of the underlying array, causes computations to
     * ignore elements past the given limit.
     * @param newLimit the new upper bound
     * @throws IllegalArgumentException if newLimit less than zero.
     */
    public final void setLimit(int newLimit) {
        if (newLimit < 0)
            throw new IllegalArgumentException();
        int cap = array.length;
        if (newLimit > cap)
            resizeArray(newLimit);
        limit = newLimit;
    }

    final void replaceElementsWith(T[] a) {
        System.arraycopy(a, 0, array, 0, a.length);
        limit = a.length;
    }

    final void resizeArray(int newCap) {
        int cap = array.length;
        if (newCap > cap) {
            Class elementType = array.getClass().getComponentType();
            T[] a =(T[])Array.newInstance(elementType, newCap);
            System.arraycopy(array, 0, a, 0, cap);
            array = a;
        }
    }

    final void insertElementAt(int index, T e) {
        int hi = limit++;
        if (hi >= array.length)
            resizeArray((hi * 3)/2 + 1);
        if (hi > index)
            System.arraycopy(array, index, array, index+1, hi - index);
        array[index] = e;
    }

    final void appendElement(T e) {
        int hi = limit++;
        if (hi >= array.length)
            resizeArray((hi * 3)/2 + 1);
        array[hi] = e;
    }

    /**
     * Make len slots available at index
     */
    final void insertSlotsAt(int index, int len) {
        if (len <= 0)
            return;
        int cap = array.length;
        int newSize = limit + len;
        if (cap < newSize) {
            cap = (cap * 3)/2 + 1;
            if (cap < newSize)
                cap = newSize;
            resizeArray(cap);
        }
        if (index < limit)
            System.arraycopy(array, index, array, index + len, limit - index);
        limit = newSize;
    }

    final void removeSlotAt(int index) {
        System.arraycopy(array, index + 1, array, index, limit - index - 1);
        array[--limit] = null;
    }

    final void removeSlotsAt(int fromIndex, int toIndex) {
        if (fromIndex < toIndex) {
            int size = limit;
            System.arraycopy(array, toIndex, array, fromIndex, size - toIndex);
            int newSize = size - (toIndex - fromIndex);
            limit = newSize;
            while (size > newSize)
                array[--size] = null;
        }
    }

    final int seqIndexOf(Object target) {
        T[] arr = array;
        int fence = limit;
        if (target == null) {
            for (int i = 0; i < fence; i++)
                if (arr[i] == null)
                    return i;
        } else {
            for (int i = 0; i < fence; i++)
                if (target.equals(arr[i]))
                    return i;
        }
        return -1;
    }

    final int seqLastIndexOf(Object target) {
        T[] arr = array;
        int last = limit - 1;
        if (target == null) {
            for (int i = last; i >= 0; i--)
                if (arr[i] == null)
                    return i;
        } else {
            for (int i = last; i >= 0; i--)
                if (target.equals(arr[i]))
                    return i;
        }
        return -1;
    }

    final class ListIter implements ListIterator<T> {
        int cursor;
        int lastRet;
        T[] arr; // cache array and bound
        int hi;
        ListIter(int lo) {
            this.cursor = lo;
            this.lastRet = -1;
            this.arr = ParallelArray.this.array;
            this.hi = ParallelArray.this.limit;
        }

        public boolean hasNext() {
            return cursor < hi;
        }

        public T next() {
            int i = cursor;
            if (i < 0 || i >= hi)
                throw new NoSuchElementException();
            T next = arr[i];
            lastRet = i;
            cursor = i + 1;
            return next;
        }

        public void remove() {
            int k = lastRet;
            if (k < 0)
                throw new IllegalStateException();
            ParallelArray.this.removeSlotAt(k);
            hi = ParallelArray.this.limit;
            if (lastRet < cursor)
                cursor--;
            lastRet = -1;
        }

        public boolean hasPrevious() {
            return cursor > 0;
        }

        public T previous() {
            int i = cursor - 1;
            if (i < 0 || i >= hi)
                throw new NoSuchElementException();
            T previous = arr[i];
            lastRet = cursor = i;
            return previous;
        }

        public int nextIndex() {
            return cursor;
        }

        public int previousIndex() {
            return cursor - 1;
        }

        public void set(T e) {
            int i = lastRet;
            if (i < 0 || i >= hi)
                throw new NoSuchElementException();
            arr[i] = e;
        }

        public void add(T e) {
            int i = cursor;
            ParallelArray.this.insertElementAt(i, e);
            arr = ParallelArray.this.array;
            hi = ParallelArray.this.limit;
            lastRet = -1;
            cursor = i + 1;
        }
    }

    final class AsList extends AbstractList<T> implements RandomAccess {
        public T get(int i) {
            if (i >= limit)
                throw new IndexOutOfBoundsException();
            return array[i];
        }

        public T set(int i, T x) {
            if (i >= limit)
                throw new IndexOutOfBoundsException();
            T[] arr = array;
            T t = arr[i];
            arr[i] = x;
            return t;
        }

        public boolean isEmpty() {
            return limit == 0;
        }

        public int size() {
            return limit;
        }

        public Iterator<T> iterator() {
            return new ListIter(0);
        }

        public ListIterator<T> listIterator() {
            return new ListIter(0);
        }

        public ListIterator<T> listIterator(int index) {
            if (index < 0 || index > limit)
                throw new IndexOutOfBoundsException();
            return new ListIter(index);
        }

        public boolean add(T e) {
            appendElement(e);
            return true;
        }

        public void add(int index, T e) {
            if (index < 0 || index > limit)
                throw new IndexOutOfBoundsException();
            insertElementAt(index, e);
        }

        public boolean addAll(Collection<? extends T> c) {
            int csize = c.size();
            if (csize == 0)
                return false;
            int hi = limit;
            setLimit(hi + csize);
            T[] arr = array;
            for (T e : c)
                arr[hi++] = e;
            return true;
        }

        public boolean addAll(int index, Collection<? extends T> c) {
            if (index < 0 || index > limit)
                throw new IndexOutOfBoundsException();
            int csize = c.size();
            if (csize == 0)
                return false;
            insertSlotsAt(index, csize);
            T[] arr = array;
            for (T e : c)
                arr[index++] = e;
            return true;
        }

        public void clear() {
            T[] arr = array;
            for (int i = 0; i < limit; ++i)
                arr[i] = null;
            limit = 0;
        }

        public boolean remove(Object o) {
            int idx = seqIndexOf(o);
            if (idx < 0)
                return false;
            removeSlotAt(idx);
            return true;
        }

        public T remove(int index) {
            T oldValue = get(index);
            removeSlotAt(index);
            return oldValue;
        }

        protected void removeRange(int fromIndex, int toIndex) {
            removeSlotsAt(fromIndex, toIndex);
        }

        public boolean contains(Object o) {
            return seqIndexOf(o) >= 0;
        }

        public int indexOf(Object o) {
            return seqIndexOf(o);
        }

        public int lastIndexOf(Object o) {
            return seqLastIndexOf(o);
        }

        public Object[] toArray() {
            int len = limit;
            Object[] a = new Object[len];
            System.arraycopy(array, 0, a, 0, len);
            return a;
        }

        public <V> V[] toArray(V a[]) {
            int len = limit;
            if (a.length < len) {
                Class elementType = a.getClass().getComponentType();
                a =(V[])Array.newInstance(elementType, len);
            }
            System.arraycopy(array, 0, a, 0, len);
            if (a.length > len)
                a[len] = null;
            return a;
        }
    }
}