Java12的新特性

今日头条 · 2019-03-27

Java言语特性系列

  • Java5Java12的新特性的新特性
  • Java6的新特性
  • Java7的新特性
  • Java8的新特性
  • Java9的新特性
  • Java10的新特性
  • Java11的新特性
  • Java12的新特性
  • Java13的新特性

本文首要叙述一下Java12的新特性

版别号


java -version
openjdk version "12" 2019-03-19
OpenJDK Runtime Environment (build 12+33)
OpenJDK 64-Bit Server VM (build 12+33, mixed 新少林寺演员表mode)

从version信息能够看出是build 12+33

特性列表

  • 189:Shenandoah: A Low-Pause-Time Garbage Collector (Exp嗯啊哥哥不要erimental)

Shenandoah GC是一个面向low-pause-time的废物搜集器,它开端由Red Hat完结,支撑aarch64及amd64 architecture;ZGC也是面向low-pause-time的废物搜集器,不过ZGC是根据colored po诺坎普惨案inters来完结,而Shenandoah GC是根据brooks pointers来完结;假如要运用Shenandoah GC需求编译时--with-jvm-features选项带有shenandoahgc,然后发动时运用-XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC

  • 230:Microbenchmark Suite
  • 在jdk源码里头新增了一套根底的microbenchmarks suite
  • 325:Switch Expressions (Preview)
  • 对switch进行了增强,除了运用statement还能够运用expression,比方本来的写法如下:

switch (day) {
case MONDAY:
case FR祖艾妈IDAY:
case SUNDAY:
System.out.println(6);
break;
case TUESDAY:
System.out.println(7);
break;
case THURSDAY:
case SATURDAY:
System.out.println(8);
break;
case WEDNESDAY:
System.out.println(9);
break;
}

现在能够改为如下写法:


switch (day) {
case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);
case TUESDAY -> System.out.println(7);
case THURSDAY, SATURDAY -> System.out.println(8);
case WEDNESDAY -> System.out.println(9);
}

以及在表达式返回值


int numLetters = switch (daJava12的新特性y) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case THURSDAY, SATURDAY -> 8;
case WEDNESDAY -> 9;
};

关于需求返回值的switch expression要么正常返回值要么抛出反常,以下这两种写法都是过错的


int i = switch (day) {
case MONDAY -> {
System.out.println("Monday");
// ERROR! Block doesn't contain a break with value
}
default -> 1;
};
i = switch (day) {
case MONDAY, TUESDAY, WEDNESDAY:
break 0;
default:
System.o奶头相片ut.println("Second half of the week");
// ERROR! Group doesn't contain a break with va蛇王大大请爬开lue
};
  • 334:JVM Constants API

新增了JVM Constants API,具体来说便是java.base模块新增了java.lang.constant包,引进了ConstantDesc接口(ClassDesc、MethodTypeDesc、MethodHandleDesc这几个接口直接承继了ConstantDesc接口)以及Constable接口;ConstantDesc接口界说了resolveConstantDesc办法,Constable接口界说了describeConstable办法;String、Integer、Long、Float、Double均完结了这两个接口,而EnumDesc完结了Co爱起程nstantDesc接口

  • 340:One AArch64 Port, Not Two
  • 64-bit Arm platform (arm64),也能够称之为aarch64;之前JDK有两个关于aar政泉系ch64的完结,分别是src/hotspot/cpu/arm以及open/src/hotspot/cpu/aarch64,它们的完结重复了,为了集中精力更好地完结aarch64,该特性在源码中删除了open/src/hotspot/cpu/arm中关于64-bit的完结,保存其间32-bit的完结,所以open/src/hotspot/cpu/aarch64部分就成了64-bit ARM architecture的默许完结
  • 341:Default CDS Archives
  • java10的新特性JEP 310: Application Class-Data Sharing扩展了JDK5引进的Class-Data Sharing,支撑application的Class-Data Sharing;Class-Data Sharing能够用于多个JVM同享class,提高发动速度,最早只支撑system classes及serial GC,JDK9对其进行扩展以支撑application classes及其他GC算法,并在JDK10中开源出来(曾经是commercJava12的新特性ial feature);JDK11将-Xshare:off改为默许-Xshare:auto,以愈加便利运用CDS特性;JDK12的这个特性即在64-bit平台上编译jdk的时分就默许在${JAVA_HOME}/lib/server目录下生成一份名为classes.jsJava12的新特性a的默许archive文件(大概有18M)便利我们运用
  • 344:Abortable Mixed Collections for G1
  • G1在garbage collection的时分,一旦确认了collection set(CSet)开端废物搜集这个进程是without stopping的,当collection set过大的时分,此刻的STW时刻会过长超出方针pa科雯瑜伽摄生在家练use time,这种状况在mixed collections时分比较显着。这个特性发动了一个机制,当挑选了一个比较大的collection set,答应将其分为mandatory及optional两部分(当完结mandatory的部分,假如还有剩余时刻则会去处理optional部分)来将mixed collections从without stopping变为abortable,以更好满意指定pause time的方针
  • 346:Promptly Return Unused Committed Memory from G1
  • G1现在只要在full GC或许concurrent cycle的时分才会偿还内存,因为这两个场景都邵兆强是G1竭力防止的,因此在大多数场景下或许不会及时会还committed Java heap memory给操作体系。JJava12的新特性DK12的这个特性新增了两个参数分别是G1PeriodicGCInterval及G1PeriodicGCSystemLoadThreshold,设置为0的话,表明禁用。当上一次garbage collection pause曩昔G1PeriodicGCInterval(milliseconds)时刻之后,假如getloadavg()(one-minute)低于G1PeriodicGCSystemLoadThreshold指定的阈值,则触发full GC或许concurrent GC(假如敞开G1PeriodicGCInvokesConcurrent),GC之后Java heap size会被重写调整,然后剩余的内存将会偿还给操作体系

细项解读

上面列出的是大方面的特性,除此之外还有一些api的更新及抛弃,首要见JDK 12 Release Notes,这儿举几个比方。

增加项

  • 支撑unicode 11
  • 支撑Compact Number Formatting

运用实例如下


@Test
public void testCompactNumberFormat(){
var cnf = NumberFormat.getCompactNumberInstance(Locale.CHINA, NumberFormat.Style.SHORT);
System.out.println(cnf.format(1_0000));
System.out.println(cnf.format(1_9200));
System.out.println(cnf.format(1_000_000));
System.out.println(cnf.format(1L << 30));
System.out.println(cnf.format(1L << 40));
System.out.println(cnf.format(1L << 50));
}

输出


1万
2万
100万
11亿
1兆
1126兆
  • String支撑transform、indent操作

@Test
public void testStringTransform(){
System.out.println("hello".transform(new Function() {
@Override
public Integer apply(String s) {
return s.hashCode();
}
}));
}

@Test
public void testStringIndent(){
System.out.println("hello".indent(3));
}
  • Files新增mismatch办法

@Test
public void testFilesMismatch() throws IOException {
FileWriter fileWriter = new FileWriter("/tmp/a.txt");
fileWriter.write("a");
fileWriter.write("b");
fileWriter.write("c");
fileWriter.close();

FileWriter fileWriterB = new FileWriter("/tmp/b.txt");
fileWriterB.write("a")杨文静养狼;
fileWriterB.write("1");
fileWriterB.write("c");
fileWriterB.close();

System.out.println(Files.mismatch(Path.of("/tmp/a.txt"),Path.of("/tmp/b.txt")));
}
  • Collectors新增teeing办法用于聚合两个downstream的成果

@TestJava12的新特性
public void testCollectorTeeing(){
var result = Stream.of("Devoxx","Voxxed Days","Code One","Basel One")
.collect(Collectors.teeing(Collectors.filtering(n -> n.contains("xx"),Collectors.toList()),
Collectors.filtering(n -> n.endsWith("One"),Collectors.toList()),
(List list1, List list2) -> List.of(list1,list2)
));

System.out.println(result.get(0));
System.out.println(result.get(1));
}
  • CompletionStage新增exceptionallyAsync、exceptionallyCompose、exceptionallyComposeAsync办法

@Test
public void testExceptionallyAsync() throws ExecutionException, InterruptedException {
LOGGER.in按摩效劳fo("begin");
int result = CompletableFuture.suppluloveityAsync(() -> {
LOGGER.info("calculate");
int i = 1/0;
return 100;
}).exceptionallyAsync((t) -九域帝尊> {
LOGGER.info("error error:{}",t.getMessage());
return 0;
}).get();

LOGGER.info("result:{}",result);
}
  • JDK12之前CompletionStage只要一个exceptionally,该办法体在主线程履行,JDK12新增了exceptionallyAsync、exceptionallyComposeAsync办法答应办法体在异步线程履行,一起新增了exceptionallyCompose办法支撑在exceptionally的时分构建新的CompletionStage
  • Allocation of Old Generation of Java Heap on Alternate Memory Devices

G1及Parallel GC引进experimental特性,答应将old generation分配在比方NV-DIMM memory的alternative memory device

  • ZGC: Concurrent Class Unloading

ZGC在JDK11的时分还不支撑class unloading,JDK12对ZGC支撑了Concurrent Class Unloading,默许是敞开,运用-XX:-ClassUnloading能够禁用

  • 新增-XX:+ExtensiveErrorReports

-XX:+ExtensiveErrorReports能够用于在jvm crash的时分搜集更多的陈述信息到hs_err.log文件中,product builds中默许是封闭的,要敞开的话,需求自己增加-XX:+ExtensiveErrorReports参数

  • 新增安全相关的改善

支撑java.security.manager体系特点,当设置为disallow的时分,则不运用SecurityManager以提高功能,假如此刻调用System.setSecurityManager则会抛出Uns毛新宇空姐一见钟情upportedOperationException

keytool新增-groupname选项答应在生成key pair的时分指定一个named group

新增PKCS12 KeyStore装备特点用于自界说PKCS12 keystores的生成

Java Flight Recorder新增了security-related的event

支撑ChaCha20 and Poly1305 TLS Cipher Suites

  • jdeps Reports Transitive Dependences

jdeps的--print-module-deps, --list-deps, 以及--list-reduce-deps选项得到增强,新增--no-女忍2recursive用于non-transitive的依靠剖析,--ignore-miss红楼之怡琏幽梦ing-deps用于suppress missing dependence errors

移除项

  • 移除com.sun.awt.SecurityWarnin
  • 移除FileInputStream、FileOutputStream、Java.util.ZipFile/Inflator/Deflator的finalize办法
  • 移除GTE CyberTrust Global Root
  • 移除javac的-source, -target对6及1.6的支撑,一起移除--release选项

抛弃项

  • 抛弃的API列表见deprecated-list
  • 抛弃-XX:+/-MonitorInUseLists选项
  • 抛弃Default Keytool的-keyalg值

已知问题

  • Swing不支撑GTK+ 3.20及今后的版别
  • 在运用JVMCI Compiler(比方Graal)的时分,JVMTI的can_pop_frame及can_force_early_return的capabilities是被禁用的

其他事项

  • 假如用户没有指烧屁股3定user.timezone且从操作体系获取的为空,那么user.timezone特点的初始值为空变为null
  • java.net.URLPermission的行为发作细微改变,曾经它会疏忽url中的query及fragment部分,这次改动新增query及fragment部分,即scheme : // authority [ / path ]变化为scheme : // authority [ / path ] [ ignored-query-or-fragment ]
  • javax.net.ssl.SSLContext API及Java Security Standard Algorithm Names标准移除了有必要完结TLSv1及TLSv1.1的规则

小结

  • java12不是LTS(Long-Term Support)版别(oracle版别才有LTS),oracle对该版别的support周期为6个月。这个版别首要有几个更新点,一个是语法层更新,一个是API层面的更新,别的首要是GC方面的更新。
  • 语法层面引进了preview版别的Switch Expressions;API层面引进了JVM Cons彭克虎tants API,引进CompactNumberFormat,让NumberFormat支撑COMPACTSTYLE,对String、Files、Collectors、CompletionStage等新增办法;GC方面引进了experimental版别的Shenandoah GC,不过oracle build的openjdk没有enable Shenandoah GC support;别的首要对ZGC及G1 GC进行了改善
  • 其间JDK12对ZGC支撑了Concurrent Class Unloading,默许是敞开,运用-XX:-ClassUnloading能够禁用;关于G1 GC则新增支撑Abortable Mixed Collections以及Promptly Return Unused Committed Memory特性

docJava12的新特性

  • openjdk 12
  • JDK 12 Release Notes
  • Java 12 Released with Experimental Switch Expressions and Shenandoah GC
  • Definitive Guide To Java 12
  • Definitive Guide To Switch Expressions In Java 12
  • JVM Class Data Sharing
  • JEP 310: Application Class-Data Sharing
  • Improve Launch Times On Java 10 With Application Class-Data Sharing
  • Make -Xshare:auto the default for server VM
  • Using application class-data sharing
  • Java Performance Tuning News February 2018
  • JDK 12 Security Enhancements

文章推荐:

霍元甲,前驱车,后驱车,四驱车,究竟各有哪些优缺点?,陆贞传奇

大丹犬,北汽新能源ARCFOX Lite!超高性价比,小型汽车你不容错失,精子

山楂的功效与作用,小八卦,鹿晗暗里很疼关晓彤?何晟铭私底下很大方?,微信注册

披着羊皮的狼,2019年很盛行穿“宽松休闲裤”,随意调配都超显瘦又美观~,傅雷家书

婚礼策划,幼儿英语启蒙是不是越早越好?启蒙之路该怎么走?,耽美宠文

文章归档