35
loading...
This website collects cookies to deliver better user experience
class Service{
public void doWork(String s){
System.out.printf("Do work on %s%n", s);
}
}
class Job implements Runnable{
private final List<String> data;
private final Service service;
public Job(List<String> data) {
this.data = data;
this.service = new Service();
}
@Override
public void run() {
for (String s : data)
service.doWork(s);
}
}
// get the data chunks and run a separate worker thread for each chunk
public void oldWay(){
List<String> data = getData();
for(List<String> batch : getDataChunks(data, 1000))
new Job(batch).run();
}
// get the numbers from 0 to 10,000 as Strings
private List<String> getData(){
return IntStream.
range(0, 10_000).
mapToObj(Integer::toString).
collect(Collectors.toList());
}
private List<List<String>> getDataChunks(List<String> data, int chunkSize){
List<List<String>> result= new ArrayList<>();
final AtomicInteger counter = new AtomicInteger();
for (String s : data) {
if (counter.getAndIncrement() % chunkSize == 0)
result.add(new ArrayList<>());
result.get(result.size() - 1).add(s);
}
return result;
}
- According to Oracle:
When a stream executes in parallel, the Java runtime partitions the
stream into multiple substreams. Aggregate operations iterate over and
process these substreams in parallel and then combine the results
parallelStream
on a collection we get a number of sub streams each working in a separate thread. Djava.util.concurrent.ForkJoinPool.common.parallelism=8
public void newWay(){
Service service = new Service();
// note that we used the getData method and Service class from previous example
getData().parallelStream().forEach(service::doWork);
}