File: SynchronizationTimer.java

package info (click to toggle)
concurrent-dfsg 1.3.4-6
  • links: PTS
  • area: main
  • in suites: bookworm
  • size: 976 kB
  • sloc: java: 10,704; xml: 49; makefile: 12
file content (2302 lines) | stat: -rw-r--r-- 65,258 bytes parent folder | download | duplicates (4)
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
/*
  File: SynchronizationTimer.java

  Originally written by Doug Lea and released into the public domain.
  This may be used for any purposes whatsoever without acknowledgment.
  Thanks for the assistance and support of Sun Microsystems Labs,
  and everyone contributing, testing, and using this code.

  History:
  Date       Who                What
  7Jul1998   dl               Create public version
  16Jul1998  dl               fix intialization error for compute loops
                              combined into one frame
                              misc layout and defaults changes
                              increase printed precision
                              overlap get/set in Executor tests
                              Swap defaults for swing import
                              Active thread counts reflect executors
  30Aug1998 dl                Misc revisions to mesh with 1.1.0
  27jan1999 dl                Eliminate GC calls    
  24Nov2001 dl                Increase some default values
*/

package EDU.oswego.cs.dl.util.concurrent.misc;

// Swap the following sets of imports if necessary.

import javax.swing.*;
import javax.swing.border.*;

//import com.sun.java.swing.*;
//import com.sun.java.swing.border.*;

import  EDU.oswego.cs.dl.util.concurrent.*;
import  java.awt.*;
import  java.awt.event.*;
import  java.io.*;
import  java.net.*;
import  java.lang.reflect.*;

/**
 *
 *  This program records times for various fine-grained synchronization
 *  schemes, and provides some ways of measuring them over different
 *  context parameters.
 *
 *  <p>
 *   Quick start: 
 *  <ol>
 *   <li>javac -d <em>base of some CLASSPATH</em> *.java <br>
 *      You'll need Swing (JFC). (This
 *      program currently imports the javax.swing versions.
 *      You can edit imports to instead use other versions.)
 *   <li>java EDU.oswego.cs.dl.util.concurrent.misc.SynchronizationTimer <br>
 *   <li> Click<em> start</em>.
 *    Clicking <em>stop</em> cancels the run. Cancellation can take
 *    a while when there are a lot of threads.
 *   <li>For more explanation about tested classes, see
 *    <a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html">Documentation for util.concurrent</a>
 *  </ol>
 *
 *  <p>
 *   Synchronization schemes are tested around implementations and
 *   subclasses of <code>RNG</code>, which is just a hacked random
 *   number generator class.  Objects of this class have just enough
 *   state and require just enough computation to be reasonable minimal
 *   targets.  (Additionally, random numbers are needed a lot in these
 *   kinds of time tests, so basing them on objects that produce random
 *   numbers is convenient.)  Computation of each random number is
 *   padded a bit with an adjustable compute loop running a random
 *   number of times to avoid getting schedulers locked into
 *   uninteresting patterns.
 *
 *  <p>
 *   Each iteration of each test ultimately somehow calls 
 *   the random number generation
 *   method of an RNG. The time listed is the average time it took to do
 *   one iteration, in microseconds. These are just based on wallclock
 *   time (System.currentTimeMillis()). Thread
 *   construction time is <em>NOT</em> included in these times. 
 *   In tests with many threads, construction and other bookkeeping
 *   can take longer than the tests themselves.
 *  <p>
 *   Results are listed in a table, and optionally printed on standard output.
 *   You can redirect standard output to save to a file. 
 *  <p>
 *   The total amount of ``real'' computation reported in each cell is
 *   the same. Thus, the unobtainably ideal pattern of results would be
 *   for every cell of the table to be the same (and very small).
 *  <p>
 *  A thread pool (PooledExecutor) is used to manage the threads used in
 *  test runs. The current number of active threads is indicated in
 *  the panel. It should normally be at most three plus the number of threads used in the
 *  indicated test column (there are at most three overhead threads per run), although
 *  it may transiently climb, and is larger in those tests that
 *  generate their own internal threads (for example ThreadedExceutor). If the
 *  indicated size fails to return to zero within about 10 seconds of 
 *  either hitting stop
 *  or the end of a run, you may have a
 *  problem with interruption handling on your Java VM. 
 *
 *  <p>
 *  This program cannot
 *  tell you how busy your computer is while running tests. 
 *  You can run a utility program (for
 *  example <code>perfmeter</code> or <code>top</code> on unix) 
 *  alongside this program
 *  to find out.
 *  <p>
 *   A number of control parameters can be changed at any time.
 *   Most combinations of parameter settings create contexts
 *   that are completely unrepresentative of those seen in practical
 *   applications. However, they can be set to provide rough analogs of
 *   real applications, and the results used as rough guesses about
 *   performance impact. Also, do not be too upset about slow
 *   performance on tests representing situations
 *   that would never occur in practice.
 *   <p>
 *
 *   You can control parameters by clicking any of the following,
 *   at any time. (You can even change parameters
 *   while tests are running, in which case they will take
 *   effect as soon as possible. Most controls momentarily stall
 *   while test objects and threads are being constructed, to avoid
 *   inconsistencies during test runs.)
 *  <dl>
 *
 *   <dt> Number of threads
 *
 *   <dd> Controls concurrency.  The indicated number of threads are
 *   started simultaneously and then waited out.
 *
 *   <dt>Contention. 
 *
 *   <dd>Percent sharing among threads. Zero percent means that each
 *   thread has its own RNG object, so there is no
 *   interference among threads.  The zero
 *   percent case thus shows the cost of synchronization mechanics that
 *   happen to never be needed.
 *   100 percent sharing means that all
 *   threads call methods on the same object, so each thread will have to
 *   wait until the RNG objects are not being used by others. 
 *   In between is in between: Only the given percentage of calls are
 *   made to shared RNG objects; others are to unshared. 
 *   Contention in classes that use Channels works slightly differently:
 *   The Channels are shared, not the base RNG objects. (Another way
 *   of looking at it is that tests demonstrate effects of multiple
 *   producers and consumers on the same channel.)
 *
 *   <dt>Classes
 *   <dd>You can choose to only test the indicated classes. You can 
 *    probably figure out how to add more classes to run yourself.
 *
 *   <dt>Calls per thread per test
 *
 *   <dd>Specifies number of iterations per thread per test.  The listed
 *   times are averages over these iterations. The default seems to
 *   provide precise enough values for informal testing purposes.
 *   You should expect to see a fair amount of variation across
 *   repeated runs.
 *   If you get zeroes printed in any cell, this means that the
 *   test ran too fast to measure in milleconds, so you should increase the 
 *   iterations value.
 *
 *   <dt> Computations per call
 *
 *   <dd>Specifies length of each call by setting an internal looping
 *   parameter inside each RNG object. Shorter calls lead to shorter
 *   times between synchronization measures. Longer calls, along with
 *   high contention can be used to force timeouts to occur.
 *
 *   <dt> Iterations per barrier.
 *
 *   <dd> Specifies the number of iterations performed by each thread until
 *    a synchronization barrier is forced with other threads, forcing
 *    it to wait for other threads to reach the same number of iterations. This
 *    controls the amount of interaction (versus contention) among threads.
 *    Setting to a value greater than the number of iterations per test
 *    effectively disables barriers.
 *
 *   <dt> Threads per barrier
 *
 *   <dd> Specifies how many threads are forced to synchronize at each
 *   barrier point. Greater numbers cause more threads to wait for each
 *   other at barriers. Setting to 1 means that a thread only has to
 *   wait for itself, which means not to wait at all.
 *
 *   <dt>Lock mode
 *
 *   <dd>For classes that support it, this controls whether mutual
 *   exclusion waits are done via standard blocking synchronization, or
 *   a loop repeatedly calling a timed wait.
 *
 *   <dt>Producer mode
 *
 *   <dd>For classes that support it, this controls whether producers
 *   perform blocking puts versus loops repeatedly calling offer.
 *
 *   <dt>Consumer mode
 *
 *   <dd>For classes that support it, this controls whether consumers
 *   perform blocking takes versus loops repeatedly calling poll.
 *
 *   <dt> Timeouts
 *
 *   <dd> Specifies the duration of timeouts used in timeout mode.  A
 *   value of zero results in pure spin-loops.
 *
 *   <dt>Producer/consumer rates.
 *
 *   <dd>For tests involving producer/consumer pairs, this controls
 *   whether the producer is much faster, about the same speed, or much
 *   slower than the consumer. This is implemented by having the
 *   producer do all, half, or none of the actual calls to update, in
 *   addition to adding elements to channel.
 *
 *   <dt>Buffer capacity 
 *
 *   <dd>For tests involving finite capacity
 *   buffers, this controls maximum buffer size.
 *
 *  </dl>
 *
 *  <p>
 *   To scaffold all this, the RNG class is defined in
 *   layers. Each RNG has internal non-public methods that do the actual
 *   computation, and public methods that call the internal ones.  The
 *   particular classes run in tests might change over time, but
 *   currently includes the following general kinds:
 *
 *  <dl>
 *
 *
 *   <dt> Using built-in synchronization
 *   <dd> Versions of RNG classes that use (or don't use)
 *    synchronized methods and/or blocks. Also some tests of
 *    simple SynchronizedVariables. Tests that would not
 *    be thread-safe are not run when there is more than one
 *    thread and non-zero contention.
 *
 *
 *   <dt> Using <code>Sync</code> classes as locks
 *   <dd> Classes protecting public methods via Semaphores, mutexes, etc.
 *    In each case, the outer public methods delegate actions to
 *    another RNG object, surrounded by acquire/release/etc. The
 *    class called SDelegated does this using builtin
 *    synchronization rather than Sync locks
 *    so might be a useful comparison.
 *
 *   <dt> Using Channels
 *   <dd> These classes work a little bit differently than the others.
 *    Each test arranges that half of the threads behave as producers,
 *    and half as consumers. Each test iteration puts/takes an RNG object
 *    through a channel before or after executing its update
 *    method. When the number of threads is one, each producer
 *    simply consumers its own object. Some Channels (notably
 *    SynchronousChannels) cannot be used with only one thread,
 *    in which case the test is skipped.
 *
 *   <dt> Using Executors
 *   <dd> These classes arrange for each RNG update to occur
 *    as an executable command. Each test iteration passes a
 *    command to an Executor, which eventually executes it.
 *    Execution is overlapped: Each iteration starts a new 
 *    command, and then waits for the previous command to complete.
 *
 *  </dl>
 *
 *  <p>
 *
 *   The test code is ugly; it has just evolved over the years.  Sorry.
**/

public class SynchronizationTimer {

  /** Start up this application **/
  public static void main(String[] args) {

    JFrame frame = new JFrame("Times per call in microseconds"); 

    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {System.exit(0);}
    });
  
    frame.getContentPane().add(new SynchronizationTimer().mainPanel());
    frame.pack();
    frame.setVisible(true);
  }

  /**
   * Information about classes to be tested
   **/
  static class TestedClass { 
    final String name; 
    final Class cls; 
    final boolean multipleOK; 
    final boolean singleOK;
    final Class buffCls;
    Boolean enabled_ = new Boolean(true);

    synchronized void setEnabled(Boolean b) { enabled_ = b; }
    synchronized Boolean getEnabled() { return enabled_; }

    synchronized void toggleEnabled() {
      boolean enabled = enabled_.booleanValue();
      enabled_ = new Boolean(!enabled);
    }
    
    synchronized boolean isEnabled(int nthreads, Fraction shared) { 
      boolean enabled = enabled_.booleanValue();
      if (!enabled) return false;
      if (!singleOK && nthreads <= 1) return false;
      if (!multipleOK && nthreads > 1 && shared.compareTo(0) > 0) return false;
      return true;
    }
    
    
    TestedClass(String n, Class c, boolean m, boolean sok) {
      name = n; cls = c; multipleOK = m; singleOK = sok; 
      buffCls = null;
    }
    
    TestedClass(String n, Class c, boolean m, boolean sok, Class bc) {
      name = n; cls = c; multipleOK = m; singleOK = sok; 
      buffCls = bc;
    }
    
    static final TestedClass dummy = 
      new TestedClass("", null, false, false);

    static final TestedClass[]  classes = {
      
      new TestedClass("NoSynchronization", NoSynchRNG.class, false, true),
      new TestedClass("PublicSynchronization", PublicSynchRNG.class, true, true),
      new TestedClass("NestedSynchronization", AllSynchRNG.class, true, true),
      
      new TestedClass("SDelegated", SDelegatedRNG.class, true, true),
      
      new TestedClass("SynchLongUsingSet", SynchLongRNG.class, true, true),
      new TestedClass("SynchLongUsingCommit", AClongRNG.class, true, true),
      
      new TestedClass("Semaphore", SemRNG.class, true, true),
      new TestedClass("WaiterPrefSemaphore", WpSemRNG.class, true, true),
      new TestedClass("FIFOSemaphore", FifoRNG.class, true, true),
      new TestedClass("PrioritySemaphore", PrioritySemRNG.class, true, true),
      new TestedClass("Mutex", MutexRNG.class, true, true),
      new TestedClass("ReentrantLock", RlockRNG.class, true, true),
      
      new TestedClass("WriterPrefRWLock", WpRWlockRNG.class, true, true),
      new TestedClass("ReaderPrefRWLock", ReaderPrefRWlockRNG.class, true, true),
      new TestedClass("FIFORWLock", FIFORWlockRNG.class, true, true),
      new TestedClass("ReentrantRWL", ReentrantRWlockRNG.class, true, true),
      
      
      
      new TestedClass("LinkedQueue", ChanRNG.class, true, true, 
                      LinkedQueue.class),

      new TestedClass("WaitFreeQueue", ChanRNG.class, true, true, 
                      WaitFreeQueue.class),

      new TestedClass("BoundedLinkedQueue", ChanRNG.class, true, true,
                      BoundedLinkedQueue.class),
      new TestedClass("BoundedBuffer", ChanRNG.class, true, true,
                      BoundedBuffer.class),
      new TestedClass("CondVarBoundedBuffer", ChanRNG.class, true, true,
                      CVBuffer.class),
      new TestedClass("BoundedPriorityQueue", ChanRNG.class, true, true,
                      BoundedPriorityQueue.class),
      new TestedClass("Slot", ChanRNG.class, true, true,
                      Slot.class),
      //    new TestedClass("FIFOSlot", ChanRNG.class, true, true, FIFOSlot.class),
      new TestedClass("SynchronousChannel", ChanRNG.class, true, false,
                      SynchronousChannel.class),

      
      new TestedClass("DirectExecutor", DirectExecutorRNG.class, true, true),
      new TestedClass("SemaphoreLckExecutor", LockedSemRNG.class, true, true),
      new TestedClass("QueuedExecutor", QueuedExecutorRNG.class, true, true),
      new TestedClass("ThreadedExecutor", ThreadedExecutorRNG.class, true, true),
      new TestedClass("PooledExecutor", PooledExecutorRNG.class, true, true),
      
      //      new TestedClass("Pipe", ChanRNG.class, true, true, PipedChannel.class),
    };
  }



  // test parameters

  static final int[] nthreadsChoices = { 
    1, 
    2, 
    4, 
    8, 
    16, 
    32, 
    64, 
    128, 
    256, 
    512, 
    1024 
  };

  static final int BLOCK_MODE = 0;
  static final int TIMEOUT_MODE = 1;

  static final int[] syncModes = { BLOCK_MODE, TIMEOUT_MODE, };

  // misc formatting utilities

  static String modeToString(int m) {
    String sms;
    if (m == BLOCK_MODE) sms = "block";
    else if (m == TIMEOUT_MODE) sms = "timeout";
    else sms = "No such mode";
    return sms;
  }

  static String biasToString(int b) {
    String sms;
    if (b < 0) sms =       "slower producer";
    else if (b == 0) sms = "balanced prod/cons rate";
    else if (b > 0) sms =  "slower consumer";
    else sms = "No such bias";
    return sms;
  }


  static String p2ToString(int n) { // print power of two
    String suf = "";
    if (n >= 1024) {
      n = n / 1024;
      suf = "K";
      if (n >= 1024) {
        n = n / 1024;
        suf = "M";
      }
    }
    return n + suf;
  }

  static final int PRECISION = 10; // microseconds
    
  static String formatTime(long ns, boolean showDecimal) {
    long intpart = ns / PRECISION;
    long decpart = ns % PRECISION;
    if (!showDecimal) {
      if (decpart >= PRECISION/2)
        ++intpart;
      return Long.toString(intpart);
    }
    else {
      String sint = Long.toString(intpart);
      String sdec = Long.toString(decpart);
      if (decpart == 0) {
        int z = PRECISION;
        while (z > 10) {
          sdec = "0" + sdec;
          z /= 10;
        }
      }
      String ts = sint + "." + sdec;
      return ts;
    }
  }
    
  static class ThreadInfo {
    final String name;
    final int number;
    Boolean enabled;
    ThreadInfo(int nthr) {
      number = nthr;
      name = p2ToString(nthr);
      enabled = new Boolean(true);
    }

    synchronized Boolean getEnabled() { return enabled; }
    synchronized void setEnabled(Boolean v) { enabled = v; }
    synchronized void toggleEnabled() {
      enabled = new Boolean(!enabled.booleanValue());
    }
  }

  final ThreadInfo[] threadInfo = new ThreadInfo[nthreadsChoices.length];

  boolean threadEnabled(int nthreads) {
    return threadInfo[nthreads].getEnabled().booleanValue();
  }

  // This used to be a JTable datamodel, but now just part of this class ...

  final static int headerRows = 1;
  final static int classColumn = 0;
  final static int headerColumns = 1;
  final int tableRows = TestedClass.classes.length + headerRows;
  final int tableColumns = nthreadsChoices.length + headerColumns;
  
  final JComponent[][] resultTable_ = new JComponent[tableRows][tableColumns];
  
  JPanel resultPanel() {

    JPanel[] colPanel = new JPanel[tableColumns];
    for (int col = 0; col < tableColumns; ++col) {
      colPanel[col] = new JPanel();
      colPanel[col].setLayout(new GridLayout(tableRows, 1));
      if (col != 0)
        colPanel[col].setBackground(Color.white);
    }

    Color hdrbg = colPanel[0].getBackground();
    Border border = new LineBorder(hdrbg);

    Font font = new Font("Dialog", Font.PLAIN, 12);
    Dimension labDim = new Dimension(40, 16);
    Dimension cbDim = new Dimension(154, 16);

    JLabel cornerLab = new JLabel(" Classes      \\      Threads");
    cornerLab.setMinimumSize(cbDim);
    cornerLab.setPreferredSize(cbDim);
    cornerLab.setFont(font);
    resultTable_[0][0] = cornerLab;
    colPanel[0].add(cornerLab);
    
    for (int col = 1; col < tableColumns; ++col) {
      final int nthreads = col - headerColumns;
      JCheckBox tcb = new JCheckBox(threadInfo[nthreads].name, true);
      tcb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
          threadInfo[nthreads].toggleEnabled();
        }});
      
      
      tcb.setMinimumSize(labDim);
      tcb.setPreferredSize(labDim);
      tcb.setFont(font);
      tcb.setBackground(hdrbg);
      resultTable_[0][col] = tcb;
      colPanel[col].add(tcb);
    }
    
    
    for (int row = 1; row < tableRows; ++row) {
      final int cls = row - headerRows;
      
      JCheckBox cb = new JCheckBox(TestedClass.classes[cls].name, true); 
      cb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
          TestedClass.classes[cls].toggleEnabled();
        }});
      
      resultTable_[row][0] = cb;
      cb.setMinimumSize(cbDim);
      cb.setPreferredSize(cbDim);
      cb.setFont(font);
      colPanel[0].add(cb);
      
      for (int col = 1; col < tableColumns; ++col) {
        int nthreads = col - headerColumns;
        JLabel lab = new JLabel("");
        resultTable_[row][col] = lab;
        
        lab.setMinimumSize(labDim);
        lab.setPreferredSize(labDim);
        lab.setBorder(border); 
        lab.setFont(font);
        lab.setBackground(Color.white);
        lab.setForeground(Color.black);
        lab.setHorizontalAlignment(JLabel.RIGHT);
        
        colPanel[col].add(lab);
      }
    }
    
    JPanel tblPanel = new JPanel();
    tblPanel.setLayout(new BoxLayout(tblPanel, BoxLayout.X_AXIS));
    for (int col = 0; col < tableColumns; ++col) {
      tblPanel.add(colPanel[col]);
    }
    
    return tblPanel;
    
  }

  void setTime(final long ns, int clsIdx, int nthrIdx) {
    int row = clsIdx+headerRows;
    int col = nthrIdx+headerColumns;
    final JLabel cell = (JLabel)(resultTable_[row][col]);

    SwingUtilities.invokeLater(new Runnable() {
      public void run() { 
        cell.setText(formatTime(ns, true)); 
      } 
    });
  }
  
     

  void clearTable() {
    for (int i = 1; i < tableRows; ++i) {
      for (int j = 1; j < tableColumns; ++j) {
        ((JLabel)(resultTable_[i][j])).setText("");
      }
    }
  }

  void setChecks(final boolean setting) {
    for (int i = 0; i < TestedClass.classes.length; ++i) {
      TestedClass.classes[i].setEnabled(new Boolean(setting));
      ((JCheckBox)resultTable_[i+1][0]).setSelected(setting);
    }
  }


  public SynchronizationTimer() { 
    for (int i = 0; i < threadInfo.length; ++i) 
      threadInfo[i] = new ThreadInfo(nthreadsChoices[i]);

  }
  
  final SynchronizedInt nextClassIdx_ = new SynchronizedInt(0);
  final SynchronizedInt nextThreadIdx_ = new SynchronizedInt(0);


  JPanel mainPanel() {
    new PrintStart(); // classloader bug workaround
    JPanel paramPanel = new JPanel();
    paramPanel.setLayout(new GridLayout(5, 3));

    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridLayout(1, 3));
    
    startstop_.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        if (running_.get()) 
          cancel();
        else {
          try { 
            startTestSeries(new TestSeries());  
          }
          catch (InterruptedException ex) { 
            endTestSeries(); 
          }
        }
      }});
    
    paramPanel.add(startstop_);
    
    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(1, 2));
    
    JButton continueButton = new JButton("Continue");

    continueButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        if (!running_.get()) {
          try { 
            startTestSeries(new TestSeries(nextClassIdx_.get(),
                                           nextThreadIdx_.get()));  
          }
          catch (InterruptedException ex) { 
            endTestSeries(); 
          }
        }
      }});

    p1.add(continueButton);

    JButton clearButton = new JButton("Clear cells");
    
    clearButton.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent evt) {
        clearTable();
      }
    });

    p1.add(clearButton);

    paramPanel.add(p1);

    JPanel p3 = new JPanel();
    p3.setLayout(new GridLayout(1, 2));
    
    JButton setButton = new JButton("All classes");
    
    setButton.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent evt) {
        setChecks(true);
      }
    });

    p3.add(setButton);


    JButton unsetButton = new JButton("No classes");
    
    unsetButton.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent evt) {
        setChecks(false);
      }
    });

    p3.add(unsetButton);
    paramPanel.add(p3);

    JPanel p2 = new JPanel();
    //    p2.setLayout(new GridLayout(1, 2));
    p2.setLayout(new BoxLayout(p2, BoxLayout.X_AXIS));


    JCheckBox consoleBox = new JCheckBox("Console echo");
    consoleBox.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent evt) {
        echoToSystemOut.complement();
      }
    });

    

    JLabel poolinfo  = new JLabel("Active threads:      0");

    p2.add(poolinfo);
    p2.add(consoleBox);

    paramPanel.add(p2);

    paramPanel.add(contentionBox());
    paramPanel.add(itersBox());
    paramPanel.add(cloopBox());
    paramPanel.add(barrierBox());
    paramPanel.add(exchangeBox());
    paramPanel.add(biasBox());
    paramPanel.add(capacityBox());
    paramPanel.add(timeoutBox());
    paramPanel.add(syncModePanel());
    paramPanel.add(producerSyncModePanel());
    paramPanel.add(consumerSyncModePanel());

    startPoolStatus(poolinfo);

    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

    JPanel tblPanel = resultPanel();

    mainPanel.add(tblPanel);
    mainPanel.add(paramPanel);
    return mainPanel;
  }

  
  
  
  JComboBox syncModePanel() {
    JComboBox syncModeComboBox = new JComboBox();
    
    for (int j = 0; j < syncModes.length; ++j) {
      String lab = "Locks: " + modeToString(syncModes[j]);
      syncModeComboBox.addItem(lab);
    }
    syncModeComboBox.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent evt) {
        JComboBox src = (JComboBox)(evt.getItemSelectable());
        int idx = src.getSelectedIndex();
        RNG.syncMode.set(syncModes[idx]);
      }
    });
    
    RNG.syncMode.set(syncModes[0]);
    syncModeComboBox.setSelectedIndex(0);
    return syncModeComboBox;
  }

  JComboBox producerSyncModePanel() {
    JComboBox producerSyncModeComboBox = new JComboBox();
    
    for (int j = 0; j < syncModes.length; ++j) {
      String lab = "Producers: " + modeToString(syncModes[j]);
      producerSyncModeComboBox.addItem(lab);
    }
    producerSyncModeComboBox.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent evt) {
        JComboBox src = (JComboBox)(evt.getItemSelectable());
        int idx = src.getSelectedIndex();
        RNG.producerMode.set(syncModes[idx]);
      }
    });
    
    RNG.producerMode.set(syncModes[0]);
    producerSyncModeComboBox.setSelectedIndex(0);
    return producerSyncModeComboBox;
  }

  JComboBox consumerSyncModePanel() {
    JComboBox consumerSyncModeComboBox = new JComboBox();
    
    for (int j = 0; j < syncModes.length; ++j) {
      String lab = "Consumers: " + modeToString(syncModes[j]);
      consumerSyncModeComboBox.addItem(lab);
    }
    consumerSyncModeComboBox.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent evt) {
        JComboBox src = (JComboBox)(evt.getItemSelectable());
        int idx = src.getSelectedIndex();
        RNG.consumerMode.set(syncModes[idx]);
      }
    });
    
    RNG.consumerMode.set(syncModes[0]);
    consumerSyncModeComboBox.setSelectedIndex(0);
    return consumerSyncModeComboBox;
  }


  
  JComboBox contentionBox() {
    final  Fraction[] contentionChoices = { 
      new Fraction(0, 1),
      new Fraction(1, 16),
      new Fraction(1, 8),
      new Fraction(1, 4),
      new Fraction(1, 2),
      new Fraction(1, 1)
    };
    
    JComboBox contentionComboBox = new JComboBox();
    
    for (int j = 0; j < contentionChoices.length; ++j) {
      String lab = contentionChoices[j].asDouble() * 100.0 + 
        "% contention/sharing";
      contentionComboBox.addItem(lab);
    }
    contentionComboBox.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent evt) {
        JComboBox src = (JComboBox)(evt.getItemSelectable());
        int idx = src.getSelectedIndex();
        contention_.set(contentionChoices[idx]);
      }
    });
    
    contention_.set(contentionChoices[3]);
    contentionComboBox.setSelectedIndex(3);
    return contentionComboBox;
  }
  
  JComboBox itersBox() {
    final int[] loopsPerTestChoices = { 
      1,
      16,
      256,
      1024,
      2 * 1024, 
      4 * 1024, 
      8 * 1024, 
      16 * 1024,
      32 * 1024,
      64 * 1024, 
      128 * 1024, 
      256 * 1024, 
      512 * 1024, 
      1024 * 1024, 
    };
    
    JComboBox precComboBox = new JComboBox();
    
    for (int j = 0; j < loopsPerTestChoices.length; ++j) {
      String lab = p2ToString(loopsPerTestChoices[j]) + 
        " calls per thread per test";
      precComboBox.addItem(lab);
    }
    precComboBox.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent evt) {
        JComboBox src = (JComboBox)(evt.getItemSelectable());
        int idx = src.getSelectedIndex();
        loopsPerTest_.set(loopsPerTestChoices[idx]);
      }
    });
    
    loopsPerTest_.set(loopsPerTestChoices[8]);
    precComboBox.setSelectedIndex(8);

    return precComboBox;
  }
  
  JComboBox cloopBox() {
    final int[] computationsPerCallChoices = { 
      1,
      2,
      4,
      8,
      16,
      32,
      64,
      128,
      256,
      512,
      1024,
      2 * 1024,
      4 * 1024,
      8 * 1024,
      16 * 1024,
      32 * 1024,
      64 * 1024,
    };
    
    JComboBox cloopComboBox = new JComboBox();
    
    for (int j = 0; j < computationsPerCallChoices.length; ++j) {
      String lab = p2ToString(computationsPerCallChoices[j]) + 
        " computations per call";
      cloopComboBox.addItem(lab);
    }
    cloopComboBox.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent evt) {
        JComboBox src = (JComboBox)(evt.getItemSelectable());
        int idx = src.getSelectedIndex();
        RNG.computeLoops.set(computationsPerCallChoices[idx]);
      }
    });
    
    RNG.computeLoops.set(computationsPerCallChoices[3]);
    cloopComboBox.setSelectedIndex(3);
    return cloopComboBox;
  }
  
  JComboBox barrierBox() {
    final int[] itersPerBarrierChoices = { 
      1,
      2,
      4,
      8,
      16,
      32,
      64,
      128,
      256,
      512,
      1024,
      2 * 1024,
      4 * 1024,
      8 * 1024,
      16 * 1024,
      32 * 1024,
      64 * 1024, 
      128 * 1024, 
      256 * 1024, 
      512 * 1024, 
      1024 * 1024,
    };
    
    JComboBox barrierComboBox = new JComboBox();
    
    for (int j = 0; j < itersPerBarrierChoices.length; ++j) {
      String lab = p2ToString(itersPerBarrierChoices[j]) + 
        " iterations per barrier";
      barrierComboBox.addItem(lab);
    }
    barrierComboBox.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent evt) {
        JComboBox src = (JComboBox)(evt.getItemSelectable());
        int idx = src.getSelectedIndex();
        RNG.itersPerBarrier.set(itersPerBarrierChoices[idx]);
      }
    });
    
    RNG.itersPerBarrier.set(itersPerBarrierChoices[13]);
    barrierComboBox.setSelectedIndex(13);

    //    RNG.itersPerBarrier.set(itersPerBarrierChoices[15]);
    //    barrierComboBox.setSelectedIndex(15);

    return barrierComboBox;
  }
  
  JComboBox exchangeBox() {
    final int[] exchangerChoices = { 
      1,
      2,
      4,
      8,
      16,
      32,
      64,
      128,
      256,
      512,
      1024,
    };
    
    JComboBox exchComboBox = new JComboBox();
    
    for (int j = 0; j < exchangerChoices.length; ++j) {
      String lab = p2ToString(exchangerChoices[j]) + 
        " max threads per barrier";
      exchComboBox.addItem(lab);
    }
    exchComboBox.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent evt) {
        JComboBox src = (JComboBox)(evt.getItemSelectable());
        int idx = src.getSelectedIndex();
        RNG.exchangeParties.set(exchangerChoices[idx]);
      }
    });
    
    RNG.exchangeParties.set(exchangerChoices[1]);
    exchComboBox.setSelectedIndex(1);
    return exchComboBox;
  }
  
  JComboBox biasBox() {
    final int[] biasChoices = { 
      -1, 
      0, 
      1 
    };
    
    
    JComboBox biasComboBox = new JComboBox();
    
    for (int j = 0; j < biasChoices.length; ++j) {
      String lab = biasToString(biasChoices[j]);
      biasComboBox.addItem(lab);
    }
    biasComboBox.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent evt) {
        JComboBox src = (JComboBox)(evt.getItemSelectable());
        int idx = src.getSelectedIndex();
        RNG.bias.set(biasChoices[idx]);
      }
    });
    
    RNG.bias.set(biasChoices[1]);
    biasComboBox.setSelectedIndex(1);
    return biasComboBox;
  }
  
  JComboBox capacityBox() {
    
    final int[] bufferCapacityChoices = {
      1,
      4,
      64,
      256,
      1024,
      4096,
      16 * 1024,
      64 * 1024,
      256 * 1024,
      1024 * 1024,
    };
    
    JComboBox bcapComboBox = new JComboBox();
    
    for (int j = 0; j < bufferCapacityChoices.length; ++j) {
      String lab = p2ToString(bufferCapacityChoices[j]) + 
        " element bounded buffers";
      bcapComboBox.addItem(lab);
    }
    bcapComboBox.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent evt) {
        JComboBox src = (JComboBox)(evt.getItemSelectable());
        int idx = src.getSelectedIndex();
        DefaultChannelCapacity.set(bufferCapacityChoices[idx]);
      }
    });
    
    
    DefaultChannelCapacity.set(bufferCapacityChoices[3]);
    bcapComboBox.setSelectedIndex(3);
    return bcapComboBox;
  }
  
  JComboBox timeoutBox() {
    
    
    final long[] timeoutChoices = {
      0,
      1,
      10,
      100,
      1000,
      10000,
      100000,
    };
    
    
    JComboBox timeoutComboBox = new JComboBox();
    
    for (int j = 0; j < timeoutChoices.length; ++j) {
      String lab = timeoutChoices[j] + " msec timeouts";
      timeoutComboBox.addItem(lab);
    }
    timeoutComboBox.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent evt) {
        JComboBox src = (JComboBox)(evt.getItemSelectable());
        int idx = src.getSelectedIndex();
        RNG.timeout.set(timeoutChoices[idx]);
      }
    });
    
    RNG.timeout.set(timeoutChoices[3]);
    timeoutComboBox.setSelectedIndex(3);
    return timeoutComboBox;
  }

  ClockDaemon timeDaemon = new ClockDaemon();
  
  void startPoolStatus(final JLabel status) {
    Runnable updater = new Runnable() {
      int lastps = 0;
      public void run() {
        final int ps = Threads.activeThreads.get();
        if (lastps != ps) {
          lastps = ps;
          SwingUtilities.invokeLater(new Runnable() {
            public void run() {
              status.setText("Active threads: " + ps);
            } } );
        }
      }
    };
    timeDaemon.executePeriodically(250, updater, false);
  }

  private final SynchronizedRef contention_ = new SynchronizedRef(null);
  private final SynchronizedInt loopsPerTest_ = new SynchronizedInt(0);

  private final SynchronizedBoolean echoToSystemOut = 
      new SynchronizedBoolean(false);


  private final JButton startstop_ = new JButton("Start");
  
  private WaitableInt testNumber_ = new WaitableInt(1);

  private void runOneTest(Runnable tst) throws InterruptedException { 
    int nt = testNumber_.get(); 
    Threads.pool.execute(tst);
    testNumber_.whenNotEqual(nt, null);
  }

  private void endOneTest() {
    testNumber_.increment();
  }

  private SynchronizedBoolean running_ = new SynchronizedBoolean(false);

  void cancel() { 
    //  not stable enough to cancel during construction
    synchronized (RNG.constructionLock) {
      try {
        Threads.pool.interruptAll();
      }
      catch(Exception ex) {
        System.out.println("\nException during cancel:\n" + ex);
        return;
      }
    }
  }


  void startTestSeries(Runnable tst) throws InterruptedException {
    running_.set(true);
    startstop_.setText("Stop");
    Threads.pool.execute(tst);
  }

  // prevent odd class-gc problems on some VMs?
  class PrintStart implements Runnable {
    public void run() {
      startstop_.setText("Start");
    } 
  } 


  void endTestSeries() {
    running_.set(false);
    SwingUtilities.invokeLater(new PrintStart());
  }

  /*
  void old_endTestSeries() {
    running_.set(false);
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        startstop_.setText("Start");
      } } );
  }
  */

  class TestSeries implements Runnable {
    final int firstclass;
    final int firstnthreads;

    TestSeries() { 
      firstclass = 0;
      firstnthreads = 0;
    }

    TestSeries(final int firstc, final int firstnt) { 
      firstclass = firstc;
      firstnthreads = firstnt;
    }

    public void run() {
      Thread.currentThread().setPriority(Thread.NORM_PRIORITY);

      try {
        int t = firstnthreads; 
        int c = firstclass;

        if (t < nthreadsChoices.length &&
            c < TestedClass.classes.length) {

          for (;;) {

            
            // these checks are duplicated in OneTest, but added here
            // to minimize unecessary thread construction, 
            // which can skew results

            if (threadEnabled(t)) {

              TestedClass entry = TestedClass.classes[c];
        
              int nthreads = nthreadsChoices[t];
              int iters = loopsPerTest_.get();
              Fraction pshr = (Fraction)(contention_.get());
        
              if (entry.isEnabled(nthreads, pshr)) {

                runOneTest(new OneTest(c, t));
              }
            }

            if (++c >= TestedClass.classes.length) {
              c = 0;
              if (++t >= nthreadsChoices.length) 
                break;
            }

            nextClassIdx_.set(c);
            nextThreadIdx_.set(t);
            
          }
        }

      }
      catch (InterruptedException ex) { 
        Thread.currentThread().interrupt();
      }
      finally {
        endTestSeries();
      }
    }
  }

  static class BarrierTimer implements Runnable {
    private long startTime_ = 0;
    private long endTime_ = 0;

    public synchronized long getTime() {
      return endTime_ - startTime_;
    }

    public synchronized void run() {
      long now = System.currentTimeMillis();
      if (startTime_ == 0) 
        startTime_ = now;
      else
        endTime_ = now;
    }
  }
      
  class OneTest implements Runnable {
    final int clsIdx; 
    final int nthreadsIdx; 

    OneTest(int idx, int t) {
      clsIdx = idx; 
      nthreadsIdx = t; 
    }

    public void run() {
      Thread.currentThread().setPriority(Thread.NORM_PRIORITY-3);

      boolean wasInterrupted = false;

      final TestedClass entry = TestedClass.classes[clsIdx];

      final JLabel cell = (JLabel)(resultTable_[clsIdx+1][nthreadsIdx+1]);
      final Color oldfg =  cell.getForeground();

      try {


        if (Thread.interrupted()) return;
        if (!threadEnabled(nthreadsIdx)) return;
        
        int nthreads = nthreadsChoices[nthreadsIdx];
        int iters = loopsPerTest_.get();
        Fraction pshr = (Fraction)(contention_.get());
        
        if (!entry.isEnabled(nthreads, pshr))  return;

        BarrierTimer timer = new BarrierTimer();
        CyclicBarrier barrier = new CyclicBarrier(nthreads+1, timer);

        Class cls = entry.cls;
        Class chanCls = entry.buffCls;

        try {
          SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
              cell.setForeground(Color.blue);
              cell.setText("RUN");
              cell.repaint();
            }
          });
        }
        catch (InvocationTargetException ex) {
          ex.printStackTrace();
          System.exit(-1);
        }
        synchronized (RNG.constructionLock) {
          RNG.reset(nthreads);

          if (chanCls == null) {
            RNG shared = (RNG)(cls.newInstance());
            for (int k = 0; k < nthreads; ++k) {
              RNG pri = (RNG)(cls.newInstance());
              TestLoop l = new TestLoop(shared, pri, pshr, iters, barrier);
              Threads.pool.execute(l.testLoop());
            }
          }
          else {
            Channel shared = (Channel)(chanCls.newInstance());
            if (nthreads == 1) {
              ChanRNG single = (ChanRNG)(cls.newInstance());
              single.setSingle(true);
              PCTestLoop l = new PCTestLoop(single.getDelegate(), single, pshr,
                                            iters, barrier,
                                            shared, shared);
              Threads.pool.execute(l.testLoop(true));
            }
            else if (nthreads % 2 != 0) 
              throw new Error("Must have even number of threads!");
            else {
              int npairs = nthreads / 2;
              
              for (int k = 0; k < npairs; ++k) {
                ChanRNG t = (ChanRNG)(cls.newInstance());
                t.setSingle(false);
                Channel chan = (Channel)(chanCls.newInstance());
                
                PCTestLoop l = new PCTestLoop(t.getDelegate(), t, pshr, 
                                              iters, barrier,
                                              shared, chan);
                
                Threads.pool.execute(l.testLoop(false));
                Threads.pool.execute(l.testLoop(true));
                
              }
            }
          }

          if (echoToSystemOut.get()) {
            System.out.print(
                             entry.name + " " +
                             nthreads + "T " +
                             pshr + "S " +
                             RNG.computeLoops.get() + "I " +
                             RNG.syncMode.get() + "Lm " +
                             RNG.timeout.get() + "TO " +
                             RNG.producerMode.get() + "Pm " +
                             RNG.consumerMode.get() + "Cm " +
                             RNG.bias.get() + "B " +
                             DefaultChannelCapacity.get() + "C " +
                             RNG.exchangeParties.get() + "Xp " +
                             RNG.itersPerBarrier.get() + "Ib : "
                             );
          }

        }
        
        // Uncomment if AWT doesn't update right
        //        Thread.sleep(100);

        barrier.barrier(); // start

        barrier.barrier(); // stop

        long tm = timer.getTime();
        long totalIters = nthreads * iters;
        double dns = tm * 1000.0 * PRECISION / totalIters;
        long ns = Math.round(dns);

        setTime(ns, clsIdx, nthreadsIdx);

        if (echoToSystemOut.get()) {
          System.out.println(formatTime(ns, true));
        }

      }
      catch (BrokenBarrierException ex) { 
        wasInterrupted = true;
      }
      catch (InterruptedException ex) {
        wasInterrupted = true;
        Thread.currentThread().interrupt();
      }
      catch (Exception ex) { 
        ex.printStackTrace();
        System.out.println("Construction Exception?");
        System.exit(-1);
      }
      finally {
        final boolean clear = wasInterrupted;
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            if (clear) cell.setText("");
            cell.setForeground(oldfg);
            cell.repaint();
          }
        });

        Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
        endOneTest();
      }
    }
  }

}

class Threads implements ThreadFactory {

  static final SynchronizedInt activeThreads = new SynchronizedInt(0);

  static final Threads factory = new Threads();

  static final PooledExecutor pool = new PooledExecutor();

  static { 
    pool.setKeepAliveTime(10000); 
    pool.setThreadFactory(factory);
  }

  static class MyThread extends Thread {
    public MyThread(Runnable cmd) { 
      super(cmd); 
    }

    public void run() {
      activeThreads.increment();

      try {
        super.run();
      }
      finally {
        activeThreads.decrement();
      }
    }
  }

  public Thread newThread(Runnable cmd) {
    return new MyThread(cmd);
  }
}



class TestLoop {

  final RNG shared;
  final RNG primary;
  final int iters;
  final Fraction pshared;
  final CyclicBarrier barrier;
  final boolean[] useShared;
  final int firstidx;

  public TestLoop(RNG sh, RNG pri, Fraction pshr, int it, CyclicBarrier br) {
    shared = sh; 
    primary = pri; 
    pshared = pshr; 
    iters = it; 
    barrier = br; 

    firstidx = (int)(primary.get());

    int num = (int)(pshared.numerator());
    int denom = (int)(pshared.denominator());

    if (num == 0 || primary == shared) {
      useShared = new boolean[1];
      useShared[0] = false;
    }
    else if (num >= denom) {
      useShared = new boolean[1];
      useShared[0] = true;
    }
    else {
      // create bool array and randomize it.
      // This ensures that always same number of shared calls.

      // denom slots is too few. iters is too many. an arbitrary compromise is:
      int xfactor = 1024 / denom;
      if (xfactor < 1) xfactor = 1;
      useShared = new boolean[denom * xfactor];
      for (int i = 0; i < num * xfactor; ++i) 
        useShared[i] = true;
      for (int i = num * xfactor; i < denom  * xfactor; ++i) 
        useShared[i] = false;

      for (int i = 1; i < useShared.length; ++i) {
        int j = ((int) (shared.next() & 0x7FFFFFFF)) % (i + 1);
        boolean tmp = useShared[i];
        useShared[i] = useShared[j];
        useShared[j] = tmp;
      }
    }
  }

  public Runnable testLoop() {
    return new Runnable() {
      public void run() {
        int itersPerBarrier = RNG.itersPerBarrier.get();
        try {
          int delta = -1;
          if (primary.getClass().equals(PrioritySemRNG.class)) {
            delta = 2 - (int)((primary.get() % 5));
          }
          Thread.currentThread().setPriority(Thread.NORM_PRIORITY+delta);
          
          int nshared = (int)(iters * pshared.asDouble());
          int nprimary = iters - nshared;
          int idx = firstidx;
          
          barrier.barrier();
          
          for (int i = iters; i > 0; --i) {
            ++idx;
            if (i % itersPerBarrier == 0)
              primary.exchange();
            else {
              
              RNG r;
              
              if (nshared > 0 && useShared[idx % useShared.length]) {
                --nshared;
                r = shared;
              }
              else {
                --nprimary;
                r = primary;
              }
              long rnd = r.next();
              if (rnd % 2 == 0 && Thread.currentThread().isInterrupted()) 
                break;
            }
          }
        }
        catch (BrokenBarrierException ex) {
        }
        catch (InterruptedException ex) {
          Thread.currentThread().interrupt();
        }
        finally {
          try {
            barrier.barrier();
          }
          catch (BrokenBarrierException ex) { 
          }
          catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
          }
          finally {
            Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
          }

        }
      }
    };
  }
}

class PCTestLoop extends TestLoop {
  final Channel primaryChannel;
  final Channel sharedChannel;

  public PCTestLoop(RNG sh, RNG pri, Fraction pshr, int it, 
    CyclicBarrier br, Channel shChan, Channel priChan) {
    super(sh, pri, pshr, it, br);
    sharedChannel = shChan;
    primaryChannel = priChan;
  }

  public Runnable testLoop(final boolean isProducer) {
    return new Runnable() {
      public void run() {
        int delta = -1;
        Thread.currentThread().setPriority(Thread.NORM_PRIORITY+delta);
        int itersPerBarrier = RNG.itersPerBarrier.get();
        try { 
          
          int nshared = (int)(iters * pshared.asDouble());
          int nprimary = iters - nshared;
          int idx = firstidx;
          
          barrier.barrier(); 
          
          ChanRNG target = (ChanRNG)(primary);
          
          for (int i = iters; i > 0; --i) {
            ++idx;
            if (i % itersPerBarrier == 0)
              primary.exchange();
            else {
              Channel c;
            
              if (nshared > 0 && useShared[idx % useShared.length]) {
                --nshared;
                c = sharedChannel;
              }
              else {
                --nprimary;
                c = primaryChannel;
              }
              
              long rnd;
              if (isProducer) 
                rnd = target.producerNext(c);
              else 
                rnd = target.consumerNext(c);
              
              if (rnd % 2 == 0 && Thread.currentThread().isInterrupted()) 
                break;
            }
          }
        }
        catch (BrokenBarrierException ex) {
        }
        catch (InterruptedException ex) {
          Thread.currentThread().interrupt();
        }
        finally {
          try {
            barrier.barrier();
          }
          catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
          }
          catch (BrokenBarrierException ex) { 
          }
          finally {
            Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
          }
        }
      }
    };
  }
}

// -------------------------------------------------------------


abstract class RNG implements Serializable, Comparable {
  static final int firstSeed = 4321;
  static final int rmod = 2147483647;
  static final int rmul = 16807;

  static int lastSeed = firstSeed;
  static final int smod = 32749;
  static final int smul = 3125;

  static final Object constructionLock = RNG.class;

  // Use construction lock for all params to disable
  // changes in midst of construction of test objects.

  static final SynchronizedInt computeLoops = 
    new SynchronizedInt(16, constructionLock);
  static final SynchronizedInt syncMode = 
    new SynchronizedInt(0, constructionLock);
  static final SynchronizedInt producerMode = 
    new SynchronizedInt(0, constructionLock);
  static final SynchronizedInt consumerMode = 
    new SynchronizedInt(0, constructionLock);
  static final SynchronizedInt bias = 
    new SynchronizedInt(0, constructionLock);
  static final SynchronizedLong timeout = 
    new SynchronizedLong(100, constructionLock);
  static final SynchronizedInt exchangeParties = 
    new SynchronizedInt(1, constructionLock);
  static final SynchronizedInt sequenceNumber = 
    new SynchronizedInt(0, constructionLock);
  static final SynchronizedInt itersPerBarrier = 
    new SynchronizedInt(0, constructionLock);

  static Rendezvous[] exchangers_;

  static void reset(int nthreads) {
    synchronized(constructionLock) {
      sequenceNumber.set(-1);
      int parties = exchangeParties.get();
      if (nthreads < parties) parties = nthreads;
      if (nthreads % parties != 0) 
        throw new Error("need even multiple of parties");
      exchangers_ = new Rendezvous[nthreads / parties];
      for (int i = 0; i < exchangers_.length; ++i) {
        exchangers_[i] = new Rendezvous(parties);
      }
    }
  }

  static long nextSeed() {
    synchronized(constructionLock) {
      long s = lastSeed;
      lastSeed = (lastSeed * smul) % smod;
      if (lastSeed == 0) 
        lastSeed = (int)(System.currentTimeMillis());
      return s;
    }
  }

  final int cloops = computeLoops.get();
  final int pcBias = bias.get();
  final int smode = syncMode.get();
  final int pmode = producerMode.get();
  final int cmode = consumerMode.get();
  final long waitTime = timeout.get();
  Rendezvous exchanger_ = null;

  synchronized Rendezvous getExchanger() {
    if (exchanger_ == null) {
      synchronized (constructionLock) {
        int idx = sequenceNumber.increment();
        exchanger_ = exchangers_[idx % exchangers_.length];
      }
    }
    return exchanger_;
  }

  public void exchange() throws InterruptedException {
    Rendezvous ex = getExchanger(); 
    Runnable r = (Runnable)(ex.rendezvous(new UpdateCommand(this)));
    if (r != null) r.run();
  }

  public int compareTo(Object other) {
    int h1 = hashCode();
    int h2 = other.hashCode();
    if (h1 < h2) return -1;
    else if (h1 > h2) return 1;
    else return 0;
  }

  protected final long compute(long l) { 
    int loops = (int)((l & 0x7FFFFFFF) % (cloops * 2)) + 1;
    for (int i = 0; i < loops; ++i) l = (l * rmul) % rmod;
    return (l == 0)? firstSeed : l; 
  }

  abstract protected void set(long l);
  abstract protected long internalGet();
  abstract protected void internalUpdate();

  public long get()    { return internalGet(); }
  public void update() { internalUpdate();  }
  public long next()   { internalUpdate(); return internalGet(); }
}


class UpdateCommand implements Runnable, Serializable, Comparable {
  private final RNG obj_;
  final long cmpVal;
  public UpdateCommand(RNG o) { 
    obj_ = o; 
    cmpVal = o.get();
  }

  public void run() { obj_.update(); } 

  public int compareTo(Object x) {
    UpdateCommand u = (UpdateCommand)x;
    if (cmpVal < u.cmpVal) return -1;
    else if (cmpVal > u.cmpVal) return 1;
    else return 0;
  }
}


class GetFunction implements Callable {
  private final RNG obj_;
  public GetFunction(RNG o) { obj_ = o;  }
  public Object call() { return new Long(obj_.get()); } 
}

class NextFunction implements Callable {
  private final RNG obj_;
  public NextFunction(RNG o) { obj_ = o;  }
  public Object call() { return new Long(obj_.next()); } 
}


class NoSynchRNG extends RNG {
  protected long current_ = nextSeed();

  protected void set(long l) { current_ = l; }
  protected long internalGet() { return current_; }  
  protected void internalUpdate() { set(compute(internalGet())); }
}

class PublicSynchRNG extends NoSynchRNG {
  public synchronized long get() { return internalGet(); }  
  public synchronized void update() { internalUpdate();  }
  public synchronized long next() { internalUpdate(); return internalGet(); }
}

class AllSynchRNG extends PublicSynchRNG {
  protected synchronized void set(long l) { current_ = l; }
  protected synchronized long internalGet() { return current_; }
  protected synchronized void internalUpdate() { set(compute(internalGet())); }
}


class AClongRNG extends RNG {
  protected final SynchronizedLong acurrent_ = 
    new SynchronizedLong(nextSeed());

  protected void set(long l) { throw new Error("No set allowed"); }
  protected long internalGet() { return acurrent_.get(); }

  protected void internalUpdate() { 
    int retriesBeforeSleep = 100;
    int maxSleepTime = 100;
    int retries = 0;
    for (;;) {
      long v = internalGet();
      long n = compute(v);
      if (acurrent_.commit(v, n))
        return;
      else if (++retries >= retriesBeforeSleep) {
        try {
          Thread.sleep(n % maxSleepTime);
        }
        catch (InterruptedException ex) {
          Thread.currentThread().interrupt();
        }
        retries = 0;
      }
    }        
  }
  
}

class SynchLongRNG extends RNG {
  protected final SynchronizedLong acurrent_ = 
    new SynchronizedLong(nextSeed());

  protected void set(long l) { acurrent_.set(l); }
  protected long internalGet() { return acurrent_.get(); }
  protected void internalUpdate() { set(compute(internalGet())); }
  
}

abstract class DelegatedRNG extends RNG  {
  protected RNG delegate_ = null;
  public synchronized void setDelegate(RNG d) { delegate_ = d; }
  protected synchronized RNG getDelegate() { return delegate_; }

  public long get() { return getDelegate().get(); }
  public void update() { getDelegate().update(); }
  public long next() { return getDelegate().next(); }

  protected void set(long l) { throw new Error(); }
  protected long internalGet() { throw new Error(); }
  protected void internalUpdate() { throw new Error(); }

}

class SDelegatedRNG extends DelegatedRNG {
  public SDelegatedRNG() { setDelegate(new NoSynchRNG()); }
  public synchronized long get() { return getDelegate().get(); }
  public synchronized void update() { getDelegate().update(); }
  public synchronized long next() { return getDelegate().next(); }
}


class SyncDelegatedRNG extends DelegatedRNG {
  protected final Sync cond_;
  public SyncDelegatedRNG(Sync c) { 
    cond_ = c; 
    setDelegate(new NoSynchRNG());
  }


  protected final void acquire() throws InterruptedException {
    if (smode == 0) {
      cond_.acquire();
    }
    else {
      while (!cond_.attempt(waitTime)) {}
    }
  }
      
  public long next() { 
    try {
      acquire();

      getDelegate().update();
      long l = getDelegate().get();
      cond_.release(); 
      return l;
    }
    catch(InterruptedException x) { 
      Thread.currentThread().interrupt(); 
      return 0;
    }
  }

  public long get()  { 
    try {
      acquire();
      long l = getDelegate().get();
      cond_.release(); 
      return l;
    }
    catch(InterruptedException x) { 
      Thread.currentThread().interrupt(); 
      return 0;
    }
  }

  public void update()  { 
    try {
      acquire();
      getDelegate().update();
      cond_.release(); 
    }
    catch(InterruptedException x) { 
      Thread.currentThread().interrupt(); 
    }
  }


}

class MutexRNG extends SyncDelegatedRNG {
  public MutexRNG() { super(new Mutex()); }
}


class SemRNG extends SyncDelegatedRNG {
  public SemRNG() { super(new Semaphore(1)); }
}

class WpSemRNG extends SyncDelegatedRNG {
  public WpSemRNG() { super(new WaiterPreferenceSemaphore(1)); }
}

class FifoRNG extends SyncDelegatedRNG {
  public FifoRNG() { super(new FIFOSemaphore(1)); }
}

class PrioritySemRNG extends SyncDelegatedRNG {
  public PrioritySemRNG() { super(new PrioritySemaphore(1)); }
}

class RlockRNG extends SyncDelegatedRNG {
  public RlockRNG() { super(new ReentrantLock()); }
}


class RWLockRNG extends NoSynchRNG {
  protected final ReadWriteLock lock_;
  public RWLockRNG(ReadWriteLock l) { 
    lock_ = l; 
  }
      
  protected final void acquireR() throws InterruptedException {
    if (smode == 0) {
      lock_.readLock().acquire();
    }
    else {
      while (!lock_.readLock().attempt(waitTime)) {}
    }
  }

  protected final void acquireW() throws InterruptedException {
    if (smode == 0) {
      lock_.writeLock().acquire();
    }
    else {
      while (!lock_.writeLock().attempt(waitTime)) {}
    }
  }


  public long next() { 
    long l = 0;
    try {
      acquireR();
      l = current_;
      lock_.readLock().release(); 
    }
    catch(InterruptedException x) { 
      Thread.currentThread().interrupt(); 
      return 0;
    }

    l = compute(l);

    try {
      acquireW();
      set(l);
      lock_.writeLock().release(); 
      return l;
    }
    catch(InterruptedException x) { 
      Thread.currentThread().interrupt(); 
      return 0;
    }
  }


  public long get()  { 
    try {
      acquireR();
      long l = current_;
      lock_.readLock().release(); 
      return l;
    }
    catch(InterruptedException x) { 
      Thread.currentThread().interrupt(); 
      return 0;
    }
  }

  public void update()  { 
    long l = 0;

    try {
      acquireR();
      l = current_;
      lock_.readLock().release(); 
    }
    catch(InterruptedException x) { 
      Thread.currentThread().interrupt(); 
      return;
    }

    l = compute(l);

    try {
      acquireW();
      set(l);
      lock_.writeLock().release(); 
    }
    catch(InterruptedException x) { 
      Thread.currentThread().interrupt(); 
    }
  }

}

class WpRWlockRNG extends RWLockRNG {
  public WpRWlockRNG() { super(new WriterPreferenceReadWriteLock()); }
}

class ReaderPrefRWlockRNG extends RWLockRNG {
  public ReaderPrefRWlockRNG() { 
    super(new ReaderPreferenceReadWriteLock()); 
  }


}

class FIFORWlockRNG extends RWLockRNG {
  public FIFORWlockRNG() { super(new FIFOReadWriteLock()); }
}


class ReentrantRWlockRNG extends RWLockRNG {
  public ReentrantRWlockRNG() { 
    super(new ReentrantWriterPreferenceReadWriteLock()); 
  }

  public void update()  {  // use embedded acquires
    long l = 0;

    try {
      acquireW();

      try {
        acquireR();
        l = current_;
        lock_.readLock().release(); 
      }
      catch(InterruptedException x) { 
        Thread.currentThread().interrupt(); 
        return;
      }

      l = compute(l);

      set(l);
      lock_.writeLock().release(); 
    }
    catch(InterruptedException x) { 
      Thread.currentThread().interrupt(); 
    }
  }

}


abstract class ExecutorRNG extends DelegatedRNG {
  Executor executor_;


  synchronized void setExecutor(Executor e) { executor_ = e; }
  synchronized Executor getExecutor() { return executor_; }

  Runnable delegatedUpdate_ = null;
  Callable delegatedNext_ = null;

  synchronized Runnable delegatedUpdateCommand() {
    if (delegatedUpdate_ == null)
      delegatedUpdate_ = new UpdateCommand(getDelegate());
    return delegatedUpdate_;
  }

  synchronized Callable delegatedNextFunction() {
    if (delegatedNext_ == null)
      delegatedNext_ = new NextFunction(getDelegate());
    return delegatedNext_;
  }

  public void update() { 
    try {
      getExecutor().execute(delegatedUpdateCommand()); 
    }
    catch (InterruptedException ex) {
      Thread.currentThread().interrupt();
    }
  }

  // Each call to next gets result of previous future 
  FutureResult nextResult_ = null;

  public synchronized long next() { 
    long res = 0;
    try {
      if (nextResult_ == null) { // direct call first time through
        nextResult_ = new FutureResult();
        nextResult_.set(new Long(getDelegate().next()));
      }
      FutureResult currentResult = nextResult_;

      nextResult_ = new FutureResult();
      Runnable r = nextResult_.setter(delegatedNextFunction());
      getExecutor().execute(r); 

      res =  ((Long)(currentResult.get())).longValue();

    }
    catch (InterruptedException ex) {
      Thread.currentThread().interrupt();
    }
    catch (InvocationTargetException ex) {
      ex.printStackTrace();
      throw new Error("Bad Callable?");
    }
    return res;
  }
}

class DirectExecutorRNG extends ExecutorRNG {
  public DirectExecutorRNG() { 
    setDelegate(new PublicSynchRNG()); 
    setExecutor(new DirectExecutor()); 
  }
}

class LockedSemRNG extends ExecutorRNG {
  public LockedSemRNG() { 
    setDelegate(new NoSynchRNG()); 
    setExecutor(new LockedExecutor(new Semaphore(1))); 
  }
}

class QueuedExecutorRNG extends ExecutorRNG {
  static final QueuedExecutor exec = new QueuedExecutor();
  static { exec.setThreadFactory(Threads.factory); }
  public QueuedExecutorRNG() { 
    setDelegate(new PublicSynchRNG()); 
    setExecutor(exec); 
  }
}

class ForcedStartRunnable implements Runnable {
  protected final Latch latch_ = new Latch();
  protected final Runnable command_;

  ForcedStartRunnable(Runnable command) { command_ = command; }

  public Latch started() { return latch_; }

  public void run() {
    latch_.release();
    command_.run();
  }
}


class ForcedStartThreadedExecutor extends ThreadedExecutor {
  public void execute(Runnable command) throws InterruptedException {
    ForcedStartRunnable wrapped = new ForcedStartRunnable(command);
    super.execute(wrapped);
    wrapped.started().acquire();
  }
}

class ThreadedExecutorRNG extends ExecutorRNG {
  static final ThreadedExecutor exec = new ThreadedExecutor();
  static { exec.setThreadFactory(Threads.factory); }

  public ThreadedExecutorRNG() { 
    setDelegate(new PublicSynchRNG()); 
    setExecutor(exec); 
  }
}


class PooledExecutorRNG extends ExecutorRNG {
  static final PooledExecutor exec = Threads.pool;

  public PooledExecutorRNG() { 
    setDelegate(new PublicSynchRNG()); 
    setExecutor(exec); 
  }
}


class ChanRNG extends DelegatedRNG {

  boolean single_;

  ChanRNG() {
    setDelegate(new PublicSynchRNG());
  }

  public synchronized void setSingle(boolean s) { single_ = s; }
  public synchronized boolean isSingle() { return single_; }

  public long producerNext(Channel c) throws InterruptedException {
    RNG r = getDelegate();
    if (isSingle()) {
      c.put(r);
      r = (RNG)(c.take());
      r.update();
    }
    else {
      if (pcBias < 0) {
        r.update();
        r.update(); // update consumer side too
      }
      else if (pcBias == 0) {
        r.update();
      }
      
      if (pmode == 0) {
        c.put(r);
      }
      else {
        while (!(c.offer(r, waitTime))) {}
      }
    }
    return r.get();
  }

  public long consumerNext(Channel c) throws InterruptedException {
    RNG r = null;
    if (cmode == 0) {
      r =  (RNG)(c.take());
    }
    else {
      while (r == null) r = (RNG)(c.poll(waitTime));
    }
    
    if (pcBias == 0) {
      r.update();
    }
    else if (pcBias > 0) {
      r.update();
      r.update();
    }
    return r.get();
  }
}