Java Reference
In-Depth Information
private
private
Runnable
makeJob
() {
return
return
() -> {
ThreadLocalRandom random
=
ThreadLocalRandom
.
current
();
for
for
(
int
int
i
=
0
;
i
<
workPerThread
;
i
++) {
int
int
entry
=
twoDiceThrows
(
random
);
accumulateResult
(
entry
);
}
};
}
private
private
void
int
entry
) {
results
.
compute
(
entry
, (
key
,
previous
) ->
previous
==
null
void
accumulateResult
(
int
null
?
fraction
:
previous
+
fraction
);
}
private
private
int
int
twoDiceThrows
(
ThreadLocalRandom random
) {
int
int
firstThrow
=
random
.
nextInt
(
1
,
7
);
int
int
secondThrow
=
random
.
nextInt
(
1
,
7
);
return
return
firstThrow
+
secondThrow
;
}
private
private
void
void
awaitCompletion
(
List
<
Future
<?>>
futures
) {
futures
.
forEach
((
future
) -> {
try
try
{
future
.
get
();
}
catch
catch
(
InterruptedException
|
ExecutionException e
) {
e
.
printStackTrace
();
}
});
executor
.
shutdown
();
}
}
Caveats
I said earlier that using parallel streams “just works,” but that's being a little cheeky. You can
run existing code in parallel with little modification, but only if you've written idiomatic
code. There are a few rules and restrictions that need to be obeyed in order to make optimal
use of the parallel streams framework.