Top Banner
Java 8 Good & Bad Overview by Nicola Pedot - 26 giugno 2014 https:// creativecommons .org/licenses/by/3.0/it
42
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 2: Java 8 Overview

StatusOn 2014, Java is one of the most used programming language for client-server applications, with approximately 9 million developers.Oracle Java Versions:6 archived7 production ready (java.net)8 for developers (java.com)

Page 3: Java 8 Overview

Corporate SupportIBMOracleRed HatGoogle

Page 4: Java 8 Overview

Java 8 PartsProcessDevelopment Kit- JDKVirtual Machine VM LanguageRuntime Libraries - JREEditions - JEE, JSE, JME, JEmbedded

Page 5: Java 8 Overview

Java Community ProcessThe JCP remains the governing body for all standard Java SE APIs and related interfaces. If a proposal accepted into this process intends to revise existing standard interfaces, or to define new ones, then a parallel effort to design, review, and approve those changes must be undertaken in the JCP, either as part of a Maintenance Review of an existing JSR or in the context of a new JSR.

Page 6: Java 8 Overview

JDK Enhancement-ProposalJEP 1: JDK Enhancement-Proposal & Roadmap Process

Author Mark Reinhold

Organization Oracle

Created 2011/6/23

Updated 2012/12/4

The primary goal of this process is to produce a regularly-updated list of proposals to serve as the long-term Roadmap for JDK Release Projects and related efforts.

This process is open to every OpenJDK Committer.

This process does not in any way supplant the Java Community Process.

Page 7: Java 8 Overview

Java JDK - OpenJDKJDK 8 was the second part of "Plan B". The single driving feature of the release was Project Lambda. (Project Jigsaw was initially proposed for this release but later dropped). Additional features proposed via the JEP Process were included so long as they fit into the overall schedule required for Lambda. Detailed information on the features included in the release can be found on the features page.

The source is open and avaliable on Mercurial repository.

Page 8: Java 8 Overview

Java VM - HotSpotBelow you will find the source code for the Java HotSpot virtual machine, the best Java virtual machine on the planet.

The HotSpot code base has been worked on by dozens of people, over the course of 10 years, so far. (That's good and bad.) It's big. There are nearly 1500 C/C++ header and source files, comprising almost 250,000 lines of code. In addition to the expected class loader, bytecode interpreter, and supporting runtime routines, you get two runtime compilers from bytecode to native instructions, 3 (or so) garbage collectors, and a set of high-performance runtime libraries for synchronization, etc.

Page 9: Java 8 Overview

Java 8 Hot TopicsDefault MethodsFunction Iterfaces (Closure, Lambda) or AntiScalaStreamsParallelJavascript Nashorn Java TimeSNI IPV6Security

Page 10: Java 8 Overview

Default methodsDefault methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.

Note: interfaces do not have any state

Page 11: Java 8 Overview

Default method syntaxpublic interface oldInterface { public void existingMethod(); default public void newDefaultMethod() { System.out.println("New default method" " is added in interface"); }}

The following class will compile successfully in Java JDK 8,?

public class oldInterfaceImpl implements oldInterface { public void existingMethod() { // existing implementation is here… }}

If you create an instance of oldInterfaceImpl:?

oldInterfaceImpl obj = new oldInterfaceImpl ();// print “New default method add in interface”obj.newDefaultMethod();

Page 12: Java 8 Overview

Default method conflictjava: class Impl inherits unrelated defaults for defaultMethod() from types InterfaceA and InterfaceB

In order to fix this class, we need to provide default method implementation:

public class Impl implements InterfaceA, InterfaceB { public void defaultMethod(){ // existing code here.. InterfaceA.super.defaultMethod(); }}

Page 13: Java 8 Overview

Default method goodThe great thing about using interfaces instead of adapter classes is the ability to extend another class than the particular adapter.Simil multiple inheritance.Finally, library developers are able to evolve established APIs without introducing incompatibilities to their user's code.

Page 14: Java 8 Overview

Default method badIn a nutshell, make sure to never override a default method in another interface. Neither with another default method, nor with an abstract method.Before Java 7, you would only need to look for the actually invoked code by traversing down a linear class hierarchy. Only add this complexity when you really feel it is absolutely necessary.

Page 15: Java 8 Overview

Lambda: functional interface

A functional interface is any interface that contains only one abstract method. (A functional interface may contain one or more default methods or static methods.)

Page 16: Java 8 Overview

Lambda syntax//Prima:

List list1 = Arrays.asList(1,2,3,5);

for(Integer n: list1) {

System.out.println(n);

}

//Dopo:

List list2 = Arrays.asList(1,2,3,5);

list2.forEach(n -> System.out.println(n));// default method forEach

//Espressioni lambda e doppio due punti static method reference

list2.forEach(System.out::println);

Page 17: Java 8 Overview

Lambda syntax (2)// Anonymous class

new CheckPerson() {

public boolean test(Person p) {

return p.getGender() == Person.Sex.MALE

&& p.getAge() >= 18

&& p.getAge() <= 25;

}

}

// Lambda

(Person p) -> p.getGender() == Person.Sex.MALE

&& p.getAge() >= 18

&& p.getAge() <= 25

Page 18: Java 8 Overview

Good: Stream sampleMap<Person.Sex, List<Person>> byGender =

roster.stream().collect(

Collectors.groupingBy(Person::getGender));

Page 19: Java 8 Overview

Good: Parallel Stream sample

ConcurrentMap<Person.Sex, List<Person>> byGender =

roster.parallelStream().collect(

Collectors.groupingByConcurrent(Person::getGender))

Page 20: Java 8 Overview

Stream Bad Parts“Java 8 Streams API will be the single biggest source of new Stack Overflow questions.”With streams and functional thinking, we’ll run into a massive amount of new, subtle bugs. Few of these bugs can be prevented, except through practice and staying focused. You have to think about how to order your operations. You have to think about whether your streams may be infinite. [14]

Page 21: Java 8 Overview

Stream Bad Parts (2)“If evaluation of one parallel stream results in a very long running task, this may be split into as many long running sub-tasks that will be distributed to each thread in the pool. From there, no other parallel stream can be processed because all threads will be occupied.”If a program is to be run inside a container, one must be very careful when using parallel streams. Never use the default pool in such a situation unless you know for sure that the container can handle it. In a Java EE container, do not use parallel streams. [15]

Page 22: Java 8 Overview

Parallel Lang Tools: StampedLock

The ReentrantReadWriteLock had a lot of shortcomings: It suffered from starvation. You could not upgrade a read lock into a write lock. There was no support for optimistic reads. Programmers "in the know" mostly avoided using them.

StampedLock addresses all these shortcomings

Page 23: Java 8 Overview

Parallel Lang Tools:Concurrent Adders

Concurrent Adders: this is a new set of classes for managing counters written and read by multiple threads. The new API promises significant performance gains, while still keeping things simple and straightforward.

Page 24: Java 8 Overview

Bad PartWe’re paying the price for shorter, more concise code with more complex debugging, and longer synthetic call stacks.

Page 25: Java 8 Overview

The ReasonThe reason is that while javac has been extended to support Lambda functions, the JVM still remains oblivious to them.

Page 26: Java 8 Overview

JavascriptUn nome per tutti: node.jar from Oracle

Page 27: Java 8 Overview

JavaScript from Javapackage sample1;

import javax.script.ScriptEngine;import javax.script.ScriptEngineManager;

public class Hello {

public static void main(String... args) throws Throwable {

ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

engine.eval("function sum(a, b) { return a + b; }"); System.out.println(engine.eval("sum(1, 2);"));

engine.eval(new FileReader("src/sample1/greeter.js")); System.out.println(invocable.invokeFunction("greet", "Julien"));

}}

Page 28: Java 8 Overview

JavaScript DB Connectionvar someDatabaseFun = function() { var Properties = Java.type("java.util.Properties"); var Driver = Java.type("org.h2.Driver"); var driver = new Driver(); var properties = new Properties(); properties.setProperty("user", "sa"); properties.setProperty("password", ""); try { var conn = driver.connect( "jdbc:h2:~/test", properties); // Database code here } finally { try { if (conn) conn.close(); } catch (e) {} }}someDatabaseFun();

Page 29: Java 8 Overview

JavaScript with JOOQDSL.using(conn) .select( t.TABLE_SCHEMA, t.TABLE_NAME, count().as("CNT")) .from(t) .join(c) .on(row(t.TABLE_SCHEMA, t.TABLE_NAME) .eq(c.TABLE_SCHEMA, c.TABLE_NAME)) .groupBy(t.TABLE_SCHEMA, t.TABLE_NAME) .orderBy( t.TABLE_SCHEMA.asc(), t.TABLE_NAME.asc())

// continue in next slide

Page 30: Java 8 Overview

JavaScript with streamDSL.using(conn) .select(...) // this is folded code.

// This fetches a List<Map<String, Object>> as// your ResultSet representation .fetchMaps()

// This is Java 8's standard Collection.stream() .stream()

// And now, r is like any other JavaScript object// or record! .forEach(function (r) { print(r.TABLE_SCHEMA + '.' + r.TABLE_NAME + ' has ' + r.CNT + ' columns.'); });

Page 31: Java 8 Overview

Javascript ProblemIn this case the bytecode code is dynamically generated at runtime using a nested tree of Lambda expressions. There is very little correlation between our source code, and the resulting bytecode executed by the JVM. The call stack is now two orders of magnitude longer.

Page 32: Java 8 Overview

The Hard SideHaskell is good at preventing bugs.Java without lambda has readable stacktrace.In Groovy is harder reading exceptions,Java8 Lambda is also harder,Javascript is even harder.

Page 33: Java 8 Overview

JavaTime, JodaTime’s revenge

● The Calendar class was not type safe.● Because the classes were mutable, they could not be

used in multithreaded applications.● Bugs in application code were common due to the

unusual numbering of months and the lack of type safety.

Page 34: Java 8 Overview

JodaTime syntaximport java.time.Instant;Instant timestamp = Instant.now();

This class format follows the ISO-86012013-05-30T23:38:23.085Z

Come gestire le vecchie date?Date.toInstant()

public static Date from(Instant instant)

Calendar.toInstant()

Other classes Clock, Period,...

Page 35: Java 8 Overview

SNI IPV6Assigning a separate IP address for each site increases the cost of hosting since requests for IP addresses must be justified to the regional internet registry and IPv4 addresses are now in short supply.

An extension to TLS called Server Name Indication (SNI) addresses this issue by sending the name of the virtual domain as part of the TLS negotiation. <<Wikipedia>>

E’ possibile configurare in un webserver più virtual host con diversi certificati SSL utilizzando un solo indirizzo IP.provocazione...in vista dell’esaurimento di IP di InternetOfThings…. Java Everywhere?

Page 36: Java 8 Overview

Securityjava.security.SecureRandomThis class provides a cryptographically strong random number generator (RNG).

Page 37: Java 8 Overview

Others...1. Process termination

Process destroyForcibly(); isAlive(); waitFor(long timeout, TimeUnit unit);

2. Optional ValuesString name = computer.flatMap(Computer::getSoundcard)

.flatMap(Soundcard::getUSB) .map(USB::getVersion) .orElse("UNKNOWN");

3. Annotate AnythingType Annotations are annotations that can be placed anywhere you use a type. This includes the new operator, type casts, implements clauses and throws clauses

Page 39: Java 8 Overview

New DomainsJava started simple by design, now it has to gain complexity to model new domains.from Static Object Orienteed to->(functional) Parallel Event Orienteed->(dynamic) Syntax & Check relaxed== More fun & more dangerous times ahead!

Page 40: Java 8 Overview

from Java8 to Java9 from….Enterprise EditionStandard EditionEmbedded EditionMobile Edition…. to Java9 complete module system

Page 41: Java 8 Overview

Compact ProfilesJava Compact Profiles,

A reasonably configured Java SE-Embedded 8 for ARMv5/Linuxcompact1 profile comes in at less than 14MBcompact2 is about 18MB and compact3 is in the neighborhood of 21MB. For reference, the Java SE-Embedded 7u21 Linux environment requires 45MB.

Page 42: Java 8 Overview

Links1. http://www.dzone.com/links/r/the_bad_parts_of_lambdas_in_java_8.html2. http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html3. http://www.javacodegeeks.com/2014/04/15-must-read-java-8-tutorials.html4. http://www.oracle.com/events/us/en/java8/index.html?msgid=3-99115339445. http://typesafe.com/blog/reactive-programming-patterns-in-akka-using-java-86. http://java.dzone.com/articles/java-8-will-revolutionize7. http://openjdk.java.net/jeps/1178. http://hg.openjdk.java.net/jdk89. http://it.wikipedia.org/wiki/Java_%28linguaggio_di_programmazione%29

10. http://java.dzone.com/articles/5-features-java-8-will-change11. http://java.dzone.com/articles/10-features-java-8-you-havent12. http://java.dzone.com/articles/java-lambda-expressions-vs13. http://java.dzone.com/articles/java-8-default-methods-can14. http://blog.informatech.cr/2013/03/11/java-infinite-streams/15. http://java.dzone.com/articles/whats-wrong-java-8-part-iii