Check to see Java11, or you're out of!

Foreword

Check to see Java11, or you're out of! This is the personal blog of the original link. Java update too fast, but to learn all the recent understand some Java8 after some of its features, write it down and I hope to help.

Why Java11

  • Enhanced container fields of environmental support, GC and so on.
  • Was thin, more lightweight, small installation package.
  • JDK11 is a long-term support version.

Features introduced

Since directly across from Java8 to Java11, put it features introduced with introduction of some characteristics Java9-Java11. To learn Java8 characteristics friends can go to my blog looking for "Java8 series."

Jshell @since 9

Jshell in Java9 was brought up in, you can write Java programs directly in the terminal, enter to perform. Jshell default import some of the following packages, so Jshell environment These packages can all be used.

import java.lang.*;
import java.io.*;
import java.math.*;
import java.net.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.prefs.*;
import java.util.regex.*;
import java.util.stream.*;
复制代码
1. What is Jshell?

Jshell was introduced in Java 9 in. It provides an interactive shell, used for rapid prototyping, debugging, learning Java and Java API, all without public static void main method does not need to compile code before execution.

2.Jshell use

Open a terminal, type jshell enter jshell environment, and then enter / help intro can view the introduction of Jshell.

 lixiaoshuang@localhost  ~  jshell
|  欢迎使用 JShell -- 版本 11.0.2
|  要大致了解该版本, 请键入: /help intro

jshell> /help intro
|
|                                   intro
|                                   =====
|
|  使用 jshell 工具可以执行 Java 代码,从而立即获取结果。
|  您可以输入 Java 定义(变量、方法、类等等),例如:int x = 8
|  或 Java 表达式,例如:x + x
|  或 Java 语句或导入。
|  这些小块的 Java 代码称为“片段”。
|
|  这些 jshell 工具命令还可以让您了解和
|  控制您正在执行的操作,例如:/list
|
|  有关命令的列表,请执行:/help

jshell>
复制代码

Jshell really is a useful little tool, do not make too much description, I'll give you an example, and the rest we all experience. For example, we now want to generate a random UUID, previously required to do so:

  • Creating a class.
  • Create a main method.
  • Then write a UUID generated logic execution.

Now only need to enter the open end type jshell, then enter directly var uuid = UUID.randomUUID()Enter. We can see the uuid of echo, so we get a uuid. It does not require public static void main (String [] args);

 lixiaoshuang@localhost  ~  jshell
|  欢迎使用 JShell -- 版本 11.0.2
|  要大致了解该版本, 请键入: /help intro

jshell> var uuid = UUID.randomUUID();
 uuid ==> 9dac239e-c572-494f-b06d-84576212e012
jshell>
复制代码
3. how to exit Jshell?

Type in Jshell environment, /exityou can exit.

 lixiaoshuang@localhost  ~ 
 lixiaoshuang@localhost  ~  jshell
|  欢迎使用 JShell -- 版本 11.0.2
|  要大致了解该版本, 请键入: /help intro

jshell> var uuid = UUID.randomUUID();
uuid ==> 9dac239e-c572-494f-b06d-84576212e012

jshell> /exit
|  再见
 lixiaoshuang@localhost  ~ 
复制代码

Modular (Module) @since 9

1. What is modular?

A higher level is to increase the modularity of the polymerization, the Package is a package. Package is a path name convention classes, and the module is composed of one or more Package package.

java9以前 :package => class/interface。

java9以后 :module => package => class/interface。

So what modules for JDK split it? Open a terminal execute java --list-modulesview.

lixiaoshuang@localhost  ~ java --list-modules
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
复制代码
2. Why did you do?

We all know that there is a JRE super large rt.jar (60 Duo M), tools.jar there are tens of megabytes, previously run a hello world also needs hundreds of megabytes of environment.

  • Let lightweight Java SE program easier to deploy.
  • Powerful packaging capabilities.
  • Improved dependency management between components, introducing a particle size greater than jar Module.
  • Improved performance and security.
3. how definition module?

Module is defined by module-info.java, compiled after packaging, has become a solid block. Let's look at the simplest module definition.

4. key module
  • open

    To specify the open module, the module is open all packages are disclosed, the public can be used directly references, other types can be obtained by reflection.

    open module module.one {
        //导入日志包
       requires java.logging;
    
    }
    复制代码
  • opens

    opens to specify open the package, wherein the public type is directly accessible, other types can be obtained by reflection.

    module module.one {
    
        opens <package>;
    }
    复制代码
  • exports

    Which exports a specified package modules may be accessed by other modules.

    module module.one {
        
        exports <package>;
        
        exports <package> to <module1>, <module2>...;
    }
    复制代码
  • requires

    This keyword declares the current dependency module to another module.

    module module.one {
    
        requires <package>;
    
    }
    复制代码
  • uses、provides…with…

    uses statement uses the name service interface, the current module will find it, use java.util.ServiceLoader class to load, must be in this module, can not be other modules in its implementation class may be provided by other modules.

    module module.one {
    
        //对外提供的接口服务 ,下面指定的接口以及提供服务的impl,如果有多个实现类,用用逗号隔开
        uses <接口名>;
    
        provides <接口名> with <接口实现类>,<接口实现类>;
    
    }
    复制代码

var keyword @since 10

What 1.var that?

var Java10 is variable in the new local type inference. It will be inferred according to the latter type of the variable values, it must be initialized var.

Example:

var a;       ❌
var a = 1;   ✅
复制代码
2.var use examples
  • define local variables var

    var a = 1; 
    等于
    int a = 1;
    复制代码
  • When receiving method returns var

    var result = this.getResult();
    等于
    String result = this.getResult();
    复制代码
  • var local variables defined in the cycle

    for (var i = 0; i < 5; i++) {
       System.out.println(i);
    }
    等于
    for (int i = 0; i < 5; i++) {
       System.out.println(i);
    }
    复制代码
  • var binding Generic

    var list1 = new ArrayList<String>();  //在<>中指定了list类型为String
    等于
    List<String> list1 = new ArrayList<>();
    
    var list2 = new ArrayList<>();        //<>里默认会是Object
    复制代码
  • var using the Lambda (java11 can use)

    Consumer<String> Consumer = (var i) -> System.out.println(i);
    等于
    Consumer<String> Consumer = (String i) -> System.out.println(i);
    复制代码
3.var can no longer be used?
  • Class member variable type.
  • The method return type.
  • Java10 can not be used in Lambda var, Java11 may be used.

Enhanced api

1. String reinforcing @since 11
// 判断字符串是否为空白
" ".isBlank();                     // true

// 去除首尾空格
" Hello Java11 ".strip();          // "Hello Java11"

// 去除尾部空格 
" Hello Java11 ".stripTrailing();  // " Hello Java11"

// 去除首部空格 
" Hello Java11 ".stripLeading();   // "Hello Java11 "

// 复制字符串
"Java11".repeat(3);                // "Java11Java11Java11"

// 行数统计
"A\nB\nC".lines().count();         // 3
复制代码
2. Enhanced collection

Java 9 from the beginning, jdk inside it as a collection (List, Set, Map) and an increase of copyOf method. They are used to create immutable collections.

  • of() @since 9
  • copyOf() @since 10

Example 1:

        var list = List.of("Java", "Python", "C"); //不可变集合
        var copy = List.copyOf(list);         //copyOf判断是否是不可变集合类型,如果是直接返回
        System.out.println(list == copy);    // true

        var list = new ArrayList<String>();  // 这里返回正常的集合
        var copy = List.copyOf(list);        // 这里返回一个不可变集合
        System.out.println(list == copy);    // false
复制代码

Example Two:

        var set = Set.of("Java", "Python", "C");
        var copy = Set.copyOf(set);
        System.out.println(set == copy);     // true

        var set1 = new HashSet<String>();
        var copy1 = List.copyOf(set1);
        System.out.println(set1 == copy1);   // false
复制代码

Example Three:

        var map = Map.of("Java", 1, "Python", 2, "C", 3);
        var copy = Map.copyOf(map);
        System.out.println(map == copy);     // true

        var map1 = new HashMap<String, Integer>();
        var copy1 = Map.copyOf(map1);
        System.out.println(map1 == copy1);   // false
复制代码

注意:使用 of 和 copyOf 创建的集合为不可变集合,不能进行添加、删除、替换、排序等操作,不然会报java.lang.UnsupportedOperationException异常,使用Set.of()不能出现重复元素、Map.of()不能出现重复key,否则回报java.lang.IllegalArgumentException。

3.Stream enhance @since 9

Stream is a property of 8 Java, the Java 9 in its new four methods:

  • ofNullable(T t)

    This method can receive a null to create an empty stream

    以前
    Stream.of(null);  //报错
    现在
    Stream.ofNullable(null);
    复制代码
  • takeWhile(Predicate<? super T> predicate)

    This method determines if Predicate interface to true 取出to generate a new stream, as long as the false terminated encountered, regardless of whether the element meets the conditions behind.

            Stream<Integer> integerStream = Stream.of(6, 10, 11, 15, 20);
            Stream<Integer> takeWhile = integerStream.takeWhile(t -> t % 2 == 0);
            takeWhile.forEach(System.out::println);   // 6,10
    复制代码
  • dropWhile(Predicate<? super T> predicate)

    This method determines if Predicate interface to true 丢弃to generate a new stream, as long as the false terminated encountered, regardless of whether the element meets the conditions behind.

            Stream<Integer> integerStream = Stream.of(6, 10, 11, 15, 20);
            Stream<Integer> takeWhile = integerStream.dropWhile(t -> t % 2 == 0);
            takeWhile.forEach(System.out::println);  //11,15,20
    复制代码
  • iterate overloaded

    Iterate previously generated using the method with an infinite stream needs to be cut off limit

            Stream<Integer> limit = Stream.iterate(1, i -> i + 1).limit(5);
            limit.forEach(System.out::println);   //1,2,3,4,5
    复制代码

    After this reload now determine the parameters of a method of increasing the

            Stream<Integer> iterate = Stream.iterate(1, i -> i <= 5, i -> i + 1);
            iterate.forEach(System.out::println);  //1,2,3,4,5
    复制代码
4.Optional enhance @since 9
  • stream()

    If the stream is empty return an empty, if not empty value Optional turn into one stream.

            //返回Optional值的流
            Stream<String> stream = Optional.of("Java 11").stream();
            stream.forEach(System.out::println);    // Java 11
            
            //返回空流
            Stream<Object> stream = Optional.ofNullable(null).stream();
            stream.forEach(System.out::println);    // 
    复制代码
  • ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)

    This method is a combination of personal feeling isPresent () enhanced Else, use ifPresentOrElse approach is that if a Optional contains the value, the value of its action contained in the calling function, namely action.accept (value), which is consistent with ifPresent; and ifPresent difference method is that, ifPresentOrElse there is a second argument emptyAction - Optional If that does not contain a value, then ifPresentOrElse will call emptyAction, namely emptyAction.run ().

            Optional<Integer> optional = Optional.of(1);
            optional.ifPresentOrElse( x -> System.out.println("Value: " + x),() ->
                    System.out.println("Not Present."));    //Value: 1
            
            optional = Optional.empty();
            optional.ifPresentOrElse( x -> System.out.println("Value: " + x),() ->
                    System.out.println("Not Present."));    //Not Present.
    复制代码
  • or(Supplier<? extends Optional<? extends T>> supplier)

        Optional<String> optional1 = Optional.of("Java");
        Supplier<Optional<String>> supplierString = () -> Optional.of("Not Present");
        optional1 = optional1.or( supplierString);
        optional1.ifPresent( x -> System.out.println("Value: " + x));  //Value: Java

        optional1 = Optional.empty();
        optional1 = optional1.or( supplierString);
        optional1.ifPresent( x -> System.out.println("Value: " + x)); //Value: Not Present
复制代码
5.InputStream enhance @since 9
        String lxs = "java";
        try (var inputStream = new ByteArrayInputStream(lxs.getBytes());
             var outputStream = new ByteArrayOutputStream()) {
            inputStream.transferTo(outputStream);
            System.out.println(outputStream);    //java
        }
复制代码

HTTP Client API

Api supports synchronous and asynchronous changed in two ways, the following are examples of two ways:

        var request = HttpRequest.newBuilder()
                .uri(URI.create("https://www.baidu.com/"))
                .build();
        var client = HttpClient.newHttpClient();
        // 同步
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());

        // 异步
        CompletableFuture<HttpResponse<String>> sendAsync = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
        //这里会阻塞
        HttpResponse<String> response1 = sendAsync.get();
        System.out.println(response1.body());
复制代码

Directly run java file

We all know that before you want to run a .java file, first javac compiled into .class files, and then execute the java:

//编译
javac Java11.java
//运行
java Java11
复制代码

In java11, only you need a java command can handle

java Java11.java
复制代码

Remove content

  • com.sun.awt.AWTUtilities。
  • sun.misc.Unsafe.defineClass 使用java.lang.invoke.MethodHandles.Lookup.defineClass来替代。
  • Thread.destroy () and Thread.stop (Throwable) method.
  • sun.nio.ch.disableSystemWideOverlappingFileLockCheck 属性。
  • sun.locale.formatasdefault 属性。
  • jdk snmp module.
  • javafx, openjdk from java10 version is removed, oracle java10 has not yet been removed javafx, and java11 javafx version will be removed.
  • Java Mission Control, then remove from the JDK, so you need to download separately.
  • Root Certificates :Baltimore Cybertrust Code Signing CA,SECOM ,AOL and Swisscom。
  • Tag in the waste java9 java11 in CORBA and Java EE module removed off.

Full support for Linux containers (including docker)

Many applications run in a Java virtual machine (including Apache Spark and Kafka and other data services as well as traditional enterprise applications) can run Docker containers. But running a Java application Docker containers there has been a problem that runs in a container JVM program after setting the memory size and CPU usage, can lead to decreased performance of the application. This is because the Java application does not realize that it is running in the container. With the release of Java 10, this problem is finally solved, JVM now recognizes the constraints set by the container control groups (cgroups). Memory and CPU constraints may be used in a container directly managing Java applications, including:

  • Comply memory limit set in container
  • The available CPU in the container
  • CPU constraint is provided in the container

Java 10的这个改进在Docker for Mac、Docker for Windows以及Docker Enterprise Edition等环境均有效。

to sum up

Java Version Features .png

Recommended clusters

java technology exchange group created, and interested friends can scan code added Oh!

reference

segmentfault.com/a/119000001…

Thank you for watching, hope a lot of attention Oh. If wrong, please correct me.

Guess you like

Origin juejin.im/post/5dc0e1caf265da4d47042543