写在前面:
现在(2019-01-12)绝大多数的公司或者个人都在使用JDK8,这一点毋庸置疑,但是不排除那些需要自我反省一下的落后者还在使用JDK5~7。毕竟JDK12都出来了。参考​​​JDK12​​​,还有​​JDK13​​​。
本文是参考网络诸多资料的学习笔记。

Diamond Operator<>钻石操作符改进

在JDK7之前每次声明泛型变量的时必须左右两边都同时声明泛型:
​​​List<String> list = new ArrayList<String>();​​ 右边的泛型声明看起来有些多余?

JDK7对这一点进行改进,不必两边都声明泛型,这种只适用<>标记的操作,称之为钻石操作符Diamond Operator;IDEA的language level里面也可见一斑:

Java学习之JDK9新特性_java


因此可以简写为:​​List<String> list = new ArrayList<>();​​ 但是不允许在匿名类上使用:

Java学习之JDK9新特性_JDK9_02


报错:’<>’ cannot be used with anonymous classes。

JDK9对此加以改进:

Allow diamond with anonymous classes if the argument type of the inferred type is denotable. Because the inferred type using diamond with an anonymous class constructor could be outside of the set of types supported by the signature attribute, using diamond with anonymous classes was disallowed in Java SE 7. As noted in the JSR 334 proposed final draft, it would be possible to ease this restriction if the inferred type was denotable.

try-with-resources

在早起的JDK中,最早接触流处理时,无论是JDBC,还是文件读取等;一定会很蛋疼,因为需要记住关闭流;否则会有资源泄露问题,严重的情况下会有其他CPU占用等。所以,我们需要写很多重复的代码:打开文件流,关闭文件流,判断流的关闭与否等等。

在JDK7中,这一问题得到改善。使用try…with…resource,可以少写不少代码:

try(ResourceA some = new ResourceA();
ResourceB other = new ResourceB()) {
some.doSome();
other.doOther();
} catch(Exception ex) {
ex.printStackTrace();
}

其中,ResourceA和ResourceB都是实现AutoCloseable(实际上所有实现java.io.Closeable接口的类或者接口都行)的资源类。

但是,不能在 try-with-resources 语句中直接使用该变量,而必须像上面的代码片段一样声明新变量。

Java学习之JDK9新特性_java_03


通过IDEA快速切换language level(上面有示意图),切换到JDK9,发现这个写法在JDK9里面是支持的。

针对集合的工厂方法优化

JDK9之前,有限元素的不可变集合的初始化是这样的:

Set<String> set = new HashSet<>();
set.add("a");
set.add("b");
set.add("c");
set = Collections.unmodifiableSet(set);

如果切换到JDK9:

Java学习之JDK9新特性_ide_04


依照IDEA的智能提醒,一行代码搞定:

​Set<String> set = Set.of("a", "b", "c");​​ 注意:因为这种方式初始化的集合是不可变的,创建后,继续添加元素会导致 “UnsupportedOperationException” 。

Java学习之JDK9新特性_JDK9_05


问题:unmodifiable与immutable有什么区别?

参考:​​JEP-269​

模块化

JVM

新的编译工具:jaotc
示例:

  • compile:​​jaotc --output libHelloWorld.so HelloWorld.class​
  • run: ​​java -XX:AOTLibrary=./libHelloWorl.so HelloWorld​

ahead-of-time compilation,​​jep 295​​ 通过提供类库风格的机制(library-like mechanism)以降低启动开销

G1作为默认GC,​​jep 248​​​ 在通用场景下,通常认为gc延迟的重要性高于吞吐量
G1,健壮且经过充分测试的收集器:

  • 直接设定延迟目标,能够达到延迟SLAs
  • 最坏场景的延迟表现优于CMS(设计原理导致碎片化问题)

参考

​JEP-213​​​​Java9新特性系列(总结)​

​​​JDK 9 New Features​