-
Notifications
You must be signed in to change notification settings - Fork 1
/
chapter27.java
834 lines (639 loc) · 18.8 KB
/
chapter27.java
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
// A simple semaphore example.
import java.util.concurrent.*;
class SemDemo {
public static void main(String[] args) {
Semaphore sem = new Semaphore(1);
new IncThread(sem, "A");
new DecThread(sem, "B");
}
}
// A shared resource.
class Shared {
static int count = 0;
}
// A thread of execution that increments count.
class IncThread implements Runnable {
String name;
Semaphore sem;
IncThread(Semaphore s, String n) {
sem = s;
name = n;
new Thread(this).start();
}
public void run() {
System.out.println("Starting " + name);
try {
// First, get a permit.
System.out.println(name + " is waiting for a permit.");
sem.acquire();
System.out.println(name + " gets a permit.");
// Now, access shared resource.
for(int i=0; i < 5; i++) {
Shared.count++;
System.out.println(name + ": " + Shared.count);
// Now, allow a context switch -- if possible.
Thread.sleep(10);
}
} catch (InterruptedException exc) {
System.out.println(exc);
}
// Release the permit.
System.out.println(name + " releases the permit.");
sem.release();
}
}
// A thread of execution that decrements count.
class DecThread implements Runnable {
String name;
Semaphore sem;
DecThread(Semaphore s, String n) {
sem = s;
name = n;
new Thread(this).start();
}
public void run() {
System.out.println("Starting " + name);
try {
// First, get a permit.
System.out.println(name + " is waiting for a permit.");
sem.acquire();
System.out.println(name + " gets a permit.");
// Now, access shared resource.
for(int i=0; i < 5; i++) {
Shared.count--;
System.out.println(name + ": " + Shared.count);
// Now, allow a context switch -- if possible.
Thread.sleep(10);
}
} catch (InterruptedException exc) {
System.out.println(exc);
}
// Release the permit.
System.out.println(name + " releases the permit.");
sem.release();
}
}
// -----------------------------------------
// An example of CountDownLatch.
import java.util.concurrent.CountDownLatch;
class CDLDemo {
public static void main(String[] args) {
CountDownLatch cdl = new CountDownLatch(5);
System.out.println("Starting");
new MyThread(cdl);
try {
cdl.await();
} catch (InterruptedException exc) {
System.out.println(exc);
}
System.out.println("Done");
}
}
class MyThread implements Runnable {
CountDownLatch latch;
MyThread(CountDownLatch c) {
latch = c;
new Thread(this).start();
}
public void run() {
for(int i = 0; i<5; i++) {
System.out.println(i);
latch.countDown(); // decrement count
}
}
}
// -----------------------------------------
// An example of CyclicBarrier.
import java.util.concurrent.*;
class BarDemo {
public static void main(String[] args) {
CyclicBarrier cb = new CyclicBarrier(3, new BarAction() );
System.out.println("Starting");
new MyThread(cb, "A");
new MyThread(cb, "B");
new MyThread(cb, "C");
}
}
// A thread of execution that uses a CyclicBarrier.
class MyThread implements Runnable {
CyclicBarrier cbar;
String name;
MyThread(CyclicBarrier c, String n) {
cbar = c;
name = n;
new Thread(this).start();
}
public void run() {
System.out.println(name);
try {
cbar.await();
} catch (BrokenBarrierException exc) {
System.out.println(exc);
} catch (InterruptedException exc) {
System.out.println(exc);
}
}
}
// An object of this class is called when the
// CyclicBarrier ends.
class BarAction implements Runnable {
public void run() {
System.out.println("Barrier Reached!");
}
}
// -----------------------------------------
// An example of Exchanger.
import java.util.concurrent.Exchanger;
class ExgrDemo {
public static void main(String[] args) {
Exchanger<String> exgr = new Exchanger<String>();
new UseString(exgr);
new MakeString(exgr);
}
}
// A Thread that constructs an initialized string.
class MakeString implements Runnable {
Exchanger<String> ex;
String str;
MakeString(Exchanger<String> c) {
ex = c;
str = new String();
new Thread(this).start();
}
public void run() {
char ch = 'A';
for(int i = 0; i < 3; i++) {
// Make a string.
for(int j = 0; j < 5; j++)
str += ch++;
try {
// Exchange an initialized string for an empty one.
str = ex.exchange(str);
} catch(InterruptedException exc) {
System.out.println(exc);
}
}
}
}
// A Thread that uses a string.
class UseString implements Runnable {
Exchanger<String> ex;
String str;
UseString(Exchanger<String> c) {
ex = c;
new Thread(this).start();
}
public void run() {
for(int i=0; i < 3; i++) {
try {
// Exchange an empty string for an initialized one.
str = ex.exchange(new String());
System.out.println("Got: " + str);
} catch(InterruptedException exc) {
System.out.println(exc);
}
}
}
}
// -----------------------------------------
// An example of Phaser.
import java.util.concurrent.*;
class PhaserDemo {
public static void main(String[] args) {
Phaser phsr = new Phaser(1);
int curPhase;
System.out.println("Starting");
new MyThread(phsr, "A");
new MyThread(phsr, "B");
new MyThread(phsr, "C");
// Wait for all threads to complete phase one.
curPhase = phsr.getPhase();
phsr.arriveAndAwaitAdvance();
System.out.println("Phase " + curPhase + " Complete");
// Wait for all threads to complete phase two.
curPhase = phsr.getPhase();
phsr.arriveAndAwaitAdvance();
System.out.println("Phase " + curPhase + " Complete");
curPhase = phsr.getPhase();
phsr.arriveAndAwaitAdvance();
System.out.println("Phase " + curPhase + " Complete");
// Deregister the main thread.
phsr.arriveAndDeregister();
if(phsr.isTerminated())
System.out.println("The Phaser is terminated");
}
}
// A thread of execution that uses a Phaser.
class MyThread implements Runnable {
Phaser phsr;
String name;
MyThread(Phaser p, String n) {
phsr = p;
name = n;
phsr.register();
new Thread(this).start();
}
public void run() {
System.out.println("Thread " + name + " Beginning Phase One");
phsr.arriveAndAwaitAdvance(); // Signal arrival.
// Pause a bit to prevent jumbled output. This is for illustration
// only. It is not required for the proper operation of the phaser.
try {
Thread.sleep(10);
} catch(InterruptedException e) {
System.out.println(e);
}
System.out.println("Thread " + name + " Beginning Phase Two");
phsr.arriveAndAwaitAdvance(); // Signal arrival.
// Pause a bit to prevent jumbled output. This is for illustration
// only. It is not required for the proper operation of the phaser.
try {
Thread.sleep(10);
} catch(InterruptedException e) {
System.out.println(e);
}
System.out.println("Thread " + name + " Beginning Phase Three");
phsr.arriveAndDeregister(); // Signal arrival and deregister.
}
}
// -----------------------------------------
import java.util.concurrent.Phaser;
public class StarPhaserDemo {
public static void main(String args[]) {
Phaser phsr = new NewlinePhaser(4,3);
new StarThread(phsr);
new StarThread(phsr);
new StarThread(phsr);
new StarThread(phsr);
}
}
class NewlinePhaser extends Phaser {
int numPhases;
public NewlinePhaser(int numParties, int phases) {
super(numParties);
numPhases = phases;
}
public boolean onAdvance(int phase, int numParties) {
System.out.println(); // print a newline
return phase == numPhases-1; // stop after numPhases
}
}
class StarThread implements Runnable {
Phaser phsr;
StarThread(Phaser p) {
phsr = p;
new Thread(this).start();
}
public void run() {
while (!phsr.isTerminated()) {
System.out.print('*');
phsr.arriveAndAwaitAdvance();
}
}
}
// -----------------------------------------
// A simple example that uses an Executor.
import java.util.concurrent.*;
class SimpExec {
public static void main(String[] args) {
CountDownLatch cdl = new CountDownLatch(5);
CountDownLatch cdl2 = new CountDownLatch(5);
CountDownLatch cdl3 = new CountDownLatch(5);
CountDownLatch cdl4 = new CountDownLatch(5);
ExecutorService es = Executors.newFixedThreadPool(2);
System.out.println("Starting");
// Start the threads.
es.execute(new MyThread(cdl, "A"));
es.execute(new MyThread(cdl2, "B"));
es.execute(new MyThread(cdl3, "C"));
es.execute(new MyThread(cdl4, "D"));
try {
cdl.await();
cdl2.await();
cdl3.await();
cdl4.await();
} catch (InterruptedException exc) {
System.out.println(exc);
}
es.shutdown();
System.out.println("Done");
}
}
class MyThread implements Runnable {
String name;
CountDownLatch latch;
MyThread(CountDownLatch c, String n) {
latch = c;
name = n;
}
public void run() {
for(int i = 0; i < 5; i++) {
System.out.println(name + ": " + i);
latch.countDown();
}
}
}
// -----------------------------------------
// An example that uses a Callable.
import java.util.concurrent.*;
class CallableDemo {
public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(3);
Future<Integer> f;
Future<Double> f2;
Future<Integer> f3;
System.out.println("Starting");
f = es.submit(new Sum(10));
f2 = es.submit(new Hypot(3, 4));
f3 = es.submit(new Factorial(5));
try {
System.out.println(f.get());
System.out.println(f2.get());
System.out.println(f3.get());
} catch (InterruptedException exc) {
System.out.println(exc);
}
catch (ExecutionException exc) {
System.out.println(exc);
}
es.shutdown();
System.out.println("Done");
}
}
// Following are three computational threads.
class Sum implements Callable<Integer> {
int stop;
Sum(int v) { stop = v; }
public Integer call() {
int sum = 0;
for(int i = 1; i <= stop; i++) {
sum += i;
}
return sum;
}
}
class Hypot implements Callable<Double> {
double side1, side2;
Hypot(double s1, double s2) {
side1 = s1;
side2 = s2;
}
public Double call() {
return Math.sqrt((side1*side1) + (side2*side2));
}
}
class Factorial implements Callable<Integer> {
int stop;
Factorial(int v) { stop = v; }
public Integer call() {
int fact = 1;
for(int i = 2; i <= stop; i++) {
fact *= i;
}
return fact;
}
}
// -----------------------------------------
// A simple lock example.
import java.util.concurrent.locks.*;
class LockDemo {
public static void main(String[] args) {
ReentrantLock lock = new ReentrantLock();
new LockThread(lock, "A");
new LockThread(lock, "B");
}
}
// A shared resource.
class Shared {
static int count = 0;
}
// A thread of execution that increments count.
class LockThread implements Runnable {
String name;
ReentrantLock lock;
LockThread(ReentrantLock lk, String n) {
lock = lk;
name = n;
new Thread(this).start();
}
public void run() {
System.out.println("Starting " + name);
try {
// First, lock count.
System.out.println(name + " is waiting to lock count.");
lock.lock();
System.out.println(name + " is locking count.");
Shared.count++;
System.out.println(name + ": " + Shared.count);
// Now, allow a context switch -- if possible.
System.out.println(name + " is sleeping.");
Thread.sleep(1000);
} catch (InterruptedException exc) {
System.out.println(exc);
} finally {
// Unlock
System.out.println(name + " is unlocking count.");
lock.unlock();
}
}
}
// -----------------------------------------
// A simple example of the basic divide-and-conquer strategy.
// In this case, RecursiveAction is used.
import java.util.concurrent.*;
import java.util.*;
// A ForkJoinTask (via RecursiveAction) that transforms
// the elements in an array of doubles into their square roots.
class SqrtTransform extends RecursiveAction {
// The threshold value is arbitrarily set at 1,000 in this example.
// In real-world code, its optimal value can be determined by
// profiling and experimentation.
final int seqThreshold = 1000;
// Array to be accessed.
double[] data;
// Determines what part of data to process.
int start, end;
SqrtTransform(double[] vals, int s, int e ) {
data = vals;
start = s;
end = e;
}
// This is the method in which parallel computation will occur.
protected void compute() {
// If number of elements is below the sequential threshold,
// then process sequentially.
if((end - start) < seqThreshold) {
// Transform each element into its square root.
for(int i = start; i < end; i++) {
data[i] = Math.sqrt(data[i]);
}
}
else {
// Otherwise, continue to break the data into smaller pieces.
// Find the midpoint.
int middle = (start + end) / 2;
// Invoke new tasks, using the subdivided data.
invokeAll(new SqrtTransform(data, start, middle),
new SqrtTransform(data, middle, end));
}
}
}
// Demonstrate parallel execution.
class ForkJoinDemo {
public static void main(String[] args) {
// Create a task pool.
ForkJoinPool fjp = new ForkJoinPool();
double[] nums = new double[100000];
// Give nums some values.
for(int i = 0; i < nums.length; i++)
nums[i] = (double) i;
System.out.println("A portion of the original sequence:");
for(int i=0; i < 10; i++)
System.out.print(nums[i] + " ");
System.out.println("\n");
SqrtTransform task = new SqrtTransform(nums, 0, nums.length);
// Start the main ForkJoinTask.
fjp.invoke(task);
System.out.println("A portion of the transformed sequence" +
" (to four decimal places):");
for(int i=0; i < 10; i++)
System.out.format("%.4f ", nums[i]);
System.out.println();
}
}
// -----------------------------------------
// A simple program that lets you experiment with the effects of
// changing the threshold and parallelism of a ForkJoinTask.
import java.util.concurrent.*;
// A ForkJoinTask (via RecursiveAction) that performs a
// a transform on the elements of an array of doubles.
class Transform extends RecursiveAction {
// Sequential threshold, which is set by the constructor.
int seqThreshold;
// Array to be accessed.
double[] data;
// Determines what part of data to process.
int start, end;
Transform(double[] vals, int s, int e, int t ) {
data = vals;
start = s;
end = e;
seqThreshold = t;
}
// This is the method in which parallel computation will occur.
protected void compute() {
// If number of elements is below the sequential threshold,
// then process sequentially.
if((end - start) < seqThreshold) {
// The following code assigns an element at an even index the
// square root of its original value. An element at an odd
// index is assigned its cube root. This code is designed
// to simply consume CPU time so that the effects of concurrent
// execution are more readily observable.
for(int i = start; i < end; i++) {
if((data[i] % 2) == 0)
data[i] = Math.sqrt(data[i]);
else
data[i] = Math.cbrt(data[i]);
}
}
else {
// Otherwise, continue to break the data into smaller pieces.
// Find the midpoint.
int middle = (start + end) / 2;
// Invoke new tasks, using the subdivided data.
invokeAll(new Transform(data, start, middle, seqThreshold),
new Transform(data, middle, end, seqThreshold));
}
}
}
// Demonstrate parallel execution.
class FJExperiment {
public static void main(String[] args) {
int pLevel;
int threshold;
if(args.length != 2) {
System.out.println("Usage: FJExperiment parallelism threshold ");
return;
}
pLevel = Integer.parseInt(args[0]);
threshold = Integer.parseInt(args[1]);
// These variables are used to time the task.
long beginT, endT;
// Create a task pool. Notice that the parallelism level is set.
ForkJoinPool fjp = new ForkJoinPool(pLevel);
double[] nums = new double[1000000];
for(int i = 0; i < nums.length; i++)
nums[i] = (double) i;
Transform task = new Transform(nums, 0, nums.length, threshold);
// Starting timing.
beginT = System.nanoTime();
// Start the main ForkJoinTask.
fjp.invoke(task);
// End timing.
endT = System.nanoTime();
System.out.println("Level of parallelism: " + pLevel);
System.out.println("Sequential threshold: " + threshold);
System.out.println("Elapsed time: " + (endT - beginT) + " ns");
System.out.println();
}
}
// -----------------------------------------
// A simple example that uses RecursiveTask<V>.
import java.util.concurrent.*;
// A RecursiveTask that computes the summation of an array of doubles.
class Sum extends RecursiveTask<Double> {
// The sequential threshold value.
final int seqThresHold = 500;
// Array to be accessed.
double[] data;
// Determines what part of data to process.
int start, end;
Sum(double[] vals, int s, int e ) {
data = vals;
start = s;
end = e;
}
// Find the summation of an array of doubles.
protected Double compute() {
double sum = 0;
// If number of elements is below the sequential threshold,
// then process sequentially.
if((end - start) < seqThresHold) {
// Sum the elements.
for(int i = start; i < end; i++) sum += data[i];
}
else {
// Otherwise, continue to break the data into smaller pieces.
// Find the midpoint.
int middle = (start + end) / 2;
// Invoke new tasks, using the subdivided data.
Sum subTaskA = new Sum(data, start, middle);
Sum subTaskB = new Sum(data, middle, end);
// Start each subtask by forking.
subTaskA.fork();
subTaskB.fork();
// Wait for the subtasks to return, and aggregate the results.
sum = subTaskA.join() + subTaskB.join();
}
// Return the final sum.
return sum;
}
}
// Demonstrate parallel execution.
class RecurTaskDemo {
public static void main(String[] args) {
// Create a task pool.
ForkJoinPool fjp = new ForkJoinPool();
double[] nums = new double[5000];
// Initialize nums with values that alternate between
// positive and negative.
for(int i=0; i < nums.length; i++)
nums[i] = (double) (((i%2) == 0) ? i : -i) ;
Sum task = new Sum(nums, 0, nums.length);
// Start the ForkJoinTasks. Notice that, in this case,
// invoke() returns a result.
double summation = fjp.invoke(task);
System.out.println("Summation " + summation);
}
}