Parallel and serial streams
A parallel stream is to divide a content into multiple data blocks and process the stream of each data block separately with different threads.
Parallel optimization is performed in Java 8, so we can easily operate the data in parallel. The Stream API can declaratively switch between parallel and sequential streams through parallel() and sequential().
Understand the Fork/Join framework
Fork/Join framework: When necessary, a large task is split into several small tasks (when it cannot be disassembled), and then the results of the running of each small task are added together.
The difference between Fork/Join framework and traditional thread pool:
Use "work-stealing" mode:
When a new task is executed, it can split it into smaller task executions and add small tasks to the thread queue, then steal one from a queue of random threads and put it in its own queue.
Compared with the general thread pool implementation, the advantages of the fork/join framework are reflected in the way of handling the tasks contained therein. In the general thread pool, if a thread is executing a task that cannot continue to run for some reason, the thread will be in a waiting state. However, in the fork/join framework implementation, if a sub-problem cannot continue to run because it is waiting for the completion of another sub-problem. Then the thread that handles the sub-problem will actively look for other sub-problems that have not yet been run for execution. This method reduces the waiting time of the thread and improves performance.
import java.time.Duration;import java.time.Instant;import java.util.concurrent.ForkJoinPool;import java.util.concurrent.ForkJoinTask;import java.util.concurrent.RecursiveTask;import java.util.stream.LongStream;public class TestForkJoin { public static void main(String[] xx){ } private static void test1(){ Instant start=Instant.now(); ForkJoinPool pool=new ForkJoinPool(); ForkJoinTask<Long> task = new ForkJoinCalculate(0L, 1000000000L); long sum = pool.invoke(task); System.out.println(sum); Instant end=Instant.now(); System.out.println("consum time"+Duration.between(start, end).toMillis()+"ms");//consum time 3409ms } private static void test2(){ Instant start=Instant.now(); Long sum = LongStream.rangeClosed(0L, 10000L) .parallel() .reduce(0,Long::sum); System.out.println(sum); Instant end=Instant.now(); System.out.println("consumption time" + Duration.between(start, end).toMillis()+"ms");//consumption time 2418ms } }class ForkJoinCalculate extends RecursiveTask<Long>{ private static final long serialVersionUID = 1234567890L;//serial number private long start; private long end; private static final long THRESHOLD=2500000000L;//critical value public ForkJoinCalculate(long start,long end) { this.start=start; this.end=end; } @Override protected Long compute() { long length = end - start; if(length <= THRESHOLD){ long sum=0; for(long i = start; i <= end; i++){ sum += i; } return sum; }else{ long middle = (start+end)/2; ForkJoinCalculate left = new ForkJoinCalculate(start, middle); left.fork(); ForkJoinCalculate right=new ForkJoinCalculate(middle+1, end); right.fork(); return left.join() + right.join(); } }}Optional class
Optional<T> class (java.util.Optional) is a container class that represents whether a value exists or does not exist.
It turns out that null means that a value does not exist, and now Optional can better express this concept. And it can avoid null pointer exceptions.
Common methods:
Optional.of(T t): Create an Optional instance
Optional.empty(): Create an empty Optional instance
Optional.ofNullable(T t): If t is not null, create an Optional instance, otherwise create an empty instance.
isPresent(): determines whether the value is included
orElse(T t) : If the call object contains a value, return the value, otherwise return t
orElseGet(Supplier s): If the call object contains a value, return the value obtained by s.
map(Function f): If there is a value to process it and returns the processed Optional, otherwise, it returns Optional.empty()
flatMap(Function mapper): Similar to map, the return value must be Optional
public class OptionalTest1 { public static void main(String[] args){ String s = new String("Ha");// Optional<String> op = Optional.of(null);// // String s1 = op.get();// System.out.println(s1); // Optional<String> op1 = Optional.empty();// String s1 = op1.get();// System.out.println(s1); Optional<String> op1 = Optional.ofNullable(null);// System.out.println(op1.isPresent());// System.out.println(op1.orElse(new String("Google"))); //System.out.println(op1.orElseGet(() -> new String("Ali"))); Optional<String> op2 = op1.map((x) -> x.toLowerCase()); String s2 = op2.get(); System.out.println(s2); }} @Test public void test5(){ Man man=new Man(); String name=getGodnessName(man); System.out.println(name); } //Requirements: Get the name of the goddess in a man's heart public String getGodnessName(Man man){ if(man!=null){ Godness g=man.getGod(); if(g!=null){ return g.getName(); } } return "Teacher Cang"; } //Use Optional entity class @Test public void test6(){ Optional<Godness> godness=Optional.ofNullable(new Godness("Lin Chiling")); Optional<NewMan> op=Optional.ofNullable(new NewMan(godness)); String name=getGodnessName2(op); System.out.println(name); } public String getGodnessName2(Optional<NewMan> man){ return man.orElse(new NewMan()) .getGodness() .orElse(new Godness("Teacher Cang")) .getName(); }//Note: Optional cannot be serialized public class NewMan { private Optional<Godness> godness = Optional.empty(); private Godness god; public Optional<Godness> getGod(){ return Optional.of(god); } public NewMan() { } public NewMan(Optional<Godness> godness) { this.godness = godness; } public Optional<Godness> getGodness() { return godness; } public void setGodness(Optional<Godness> godness) { this.godness = godness; } @Override public String toString() { return "NewMan [godness=" + godness + "]"; }}The above is all the experience of using the forkjoin and optional frameworks in Java 8 that we have compiled for you. If you still don’t understand anything you don’t understand when you are learning, you can discuss it in the message area below.