Java 8 Lambdas and concurrent interpretation

I'm reading Lambdas in Richard Warburton's Book Java 8 Lambdas He began to discuss the use of concurrency in modern CPUs and eventually associated it with Lambdas I don't know what I missed, but I certainly didn't get the concept Consider the following courses

class A {

private int state;

A(){
    state = 0;
}

A(int state){
    this.state = state;
}

public int getState() {
    return state;
}

public void setState(int state) {
    this.state = state;
}

@Override
public String toString() {
    return Integer.toString(state);
}
} // end A

public class Main {

public static void main(String[] args) {

    List<A> ls = new ArrayList<>();

    ls.add(new A(2));
    ls.add(new A(3));

    ls.forEach( a -> a.setState(a.getState() + 1) );
    System.out.println(ls); // [3,4]

} // end main

} // end class Main

How to construct ls forEach(a – > a.setState(a.getState()1)); More suitable for concurrent programming than

ls.forEach(new Consumer<A>() {

        @Override
        public void accept(A t) {
            t.setState(t.getState() + 1);
        }
    });

Solution

From a developer's point of view, the first lambda example is just the second code example provided to you by the java compiler extension Lambdas basically creates an anonymous inner class when and only when the parameter of a function needs an interface with an unknown method

The actual Java 8 implementations are slightly different because they do not want to generate a large number of class files, so the implementation classes are created at runtime by binding private methods (lambda code) with the help of invokedynamic Some comments from Goetz also mention that there may be some cache optimization opportunities at runtime

Theoretically, an optimization compiler with knowledge of library implementation can do some smart things, but it has never worked like a java compiler, mainly because the Java source compiler is usually separated from the runtime (the invokedynamic section does give some opportunities, but not at the library level)

However, using lambda syntax in style is more concise and can also be considered a cleaner option, because you don't want to insert variables into the state containing internal classes

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>