preface
Take a look at Java11 before you’re out! This is a link to the original personal blog post. Java update is too fast to learn, recently understand some of the Java8 after some features, write down hope to help you.
Why Java11
- Container environment support, GC and other enhancements.
- It has been slimmed down, more lightweight, and the installation package is small.
- JDK11 is a long term support release.
Features introduced
Since it jumps directly from Java8 to Java11, the feature introduction introduces some of the features of Java9 to Java11 together. Those of you who want to learn more about Java8 features can go to my blog and find the “Java8 series”.
Jshell @since 9
Jshell was introduced in Java9, and you can write Java programs directly on the terminal and execute them by pressing Enter. Jshell imports the following packages by default, so the contents of these packages are available in a Jshell environment.
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.*;
Copy the code
1. What is Jshell?
Jshell was introduced in Java 9. It provides an interactive shell for rapid prototyping, debugging, and learning about Java and its apis, all without the need for the public static void main method or compiling code before execution.
2. The use of Jshell
Open the terminal, type jshell to enter the Jshell environment, and then type /help Intro to see the introduction of Jshell.
Lixiaoshuang @ localhost ~ jshell | welcome to use jshell - version 11.0.2 | to roughly understand this version, please type: /help intro
jshell> /helpIntro | | type | = = = = = | | jshell tool can execute Java code, so as to obtain immediate results. | you can enter Java definition (variables, methods, classes, etc.), for example: int = 8 x | or Java expressions, for example: x + x | or Java statements or import. | these small pieces of Java code called "fragments". | | these jshell tool command also allows you to understand and control | you are doing, for example: / list | | the command list, please perform: /help
jshell>
Copy the code
Jshell is really a good tool to use, I will not go into too much here, I will give an example, the rest of you experience. For example, we now want to randomly generate a UUID, as we used to do:
- Create a class.
- Create a main method.
- Then write a logic that generates the UUID and execute.
Now just go to the open terminal and type jshell, then type var uuid = uuid.randomuuid () and press Enter. We’ll see the uUID echo, and we’ll have a UUID. Public static void main(String[] args);
Lixiaoshuang @ localhost ~ jshell | welcome to use jshell - version 11.0.2 | to roughly understand this version, please type: /help intro
jshell> var uuid = UUID.randomUUID();
uuid ==> 9dac239e-c572-494f-b06d-84576212e012
jshell>
Copy the code
3. How do I exit Jshell?
To exit, type /exit in the Jshell environment.
Lixiaoshuang @ localhost ~ lixiaoshuang @ localhost ~ jshell | welcome to use jshell - version 11.0.2 | to roughly understand this version, please type: /help intro
jshell> var uuid = UUID.randomUUID();
uuid ==> 9dac239e-c572-494f-b06d-84576212e012
jshell> /exit| bye lixiaoshuang @ localhost ~ Copy the code
Module @since 9
1. What is modularity?
Modularity is the addition of a higher level of aggregation, the encapsulation of a Package. A Package is a convention for some classpath name, and a module is an encapsulation of one or more packages.
Java9 before: package => class/interface.
After Java9: module => package => class/interface.
So what modules was the JDK dismantled into? Open the terminal and run Java –list-modules to check.
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]Copy the code
2. Why do you do that?
Everyone knows that the JRE has a huge Rt. jar(over 60 MB) and tools.jar has tens of megabytes, which used to be a hundred Megabyte environment to run a Hello World.
- Make Java SE applications easier to deploy with a lighter weight.
- Strong encapsulation capability.
- Improved dependency management between components by introducing modules with greater granularity than jars.
- Improved performance and security.
3. How to define a module?
A module is defined in module-info.java, compiled and packaged to become a module entity. Let’s look at the simplest module definition.
4. Module keywords
-
open
Used to specify open modules. All packages of open modules are public,public can be used by reference directly, and other types can be obtained by reflection.
Open Module module.one {// Importing the log package requires java.logging; }Copy the code
-
opens
The commission is used to specify open packages, where the public type is directly accessible and the other types are available through reflection.
module module.one { opens <package>; } Copy the code
-
exports
Exports specifies which packages under a module can be accessed by other modules.
module module.one { exports <package>; exports <package> to <module1>, <module2>... ; }Copy the code
-
requires
This keyword declares a dependency between the current module and another module.
module module.one { requires <package>; } Copy the code
-
USES and provides… With…
The uses statement uses the name of the service interface, which is found by the current module and loaded with the java.util.ServiceLoader class, which must be in this module, not another module. The implementation classes can be provided by other modules.
Module module.one {// The interface service provided externally, the interface specified below, and the impL providing the service. If there are multiple implementation classes, use commas to separate uses < interface name >; Provides < interface name > with < interface implementation class > < interface implementation class >; }Copy the code
Var keyword @since 10
1. What is var?
Var is a new local type variable inference in Java10. It will infer the type of the variable from the following value, so the var must be initialized.
Ex. :
var a; ❌
var a = 1; ✅
Copy the code
2. Example of using var
-
Var defines local variables
var a = 1; Is equal to int a = 1;Copy the code
-
When the var receiving method returns
var result = this.getResult(); 等于 String result = this.getResult(); Copy the code
-
The var loop defines local variables
for(var i = 0; i < 5; i++) { System.out.println(i); } is equal to thefor (int i = 0; i < 5; i++) { System.out.println(i); } Copy the code
-
Var combines generics
var list1 = new ArrayList<String>(); List<String> = list <String> list1 = new ArrayList<>(); var list2 = new ArrayList<>(); //<> will default to ObjectCopy the code
-
Var is used in Lambda (only available in java11)
Consumer<String> Consumer = (var i) -> System.out.println(i); 等于 Consumer<String> Consumer = (String i) -> System.out.println(i); Copy the code
3. Where can VAR be used?
- Class member variable type.
- Method return value type.
- Lambda can’t use var in Java10, but it can in Java11.
Enhance the API
1. String enhancement @since 11
// Determine if the string is blank"".isBlank(); // true// Remove the leading and trailing Spaces" Hello Java11 ".strip(); // "Hello Java11"// remove trailing Spaces" Hello Java11 ".stripTrailing(); // " Hello Java11"// remove the header space" Hello Java11 ".stripLeading(); // "Hello Java11 "// Copy the string"Java11".repeat(3); // "Java11Java11Java11"// Line count"A\nB\nC".lines().count(); / / 3Copy the code
2. Collection enhancement
Since Java 9, the JDK has added of and copyOf methods for collections (List, Set, Map). 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); Println (list == copy); // Check whether the set type is immutable. //truevar list = new ArrayList<String>(); Var copy = list.copyof (List); Println (list == copy); // Return an immutable set system.out.println (list == copy); //false
Copy the code
Example 2:
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
Copy the code
Example 3:
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
Copy the code
Note: Use of and copyOf create set for immutable, can not add, delete, replace, sorting and other operations, or you will quote Java. Lang. UnsupportedOperationException abnormalities, Using the Set of () can’t duplicate elements, Map. Of () can’t duplicate key, otherwise returns the Java. Lang. IllegalArgumentException..
3.Stream enhancement @since 9
Stream is a Java 8 feature with four new methods added in Java 9:
-
ofNullable(T t)
This method can accept NULL to create an empty stream
Before the Stream of (null); // Error now stream. ofNullable(null);Copy the code
-
takeWhile(Predicate<? super T> predicate)
This method determines from the Predicate interface that if true, a new stream will be generated, and terminates when false, regardless of whether the following elements meet the conditions.
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, 10Copy the code
-
dropWhile(Predicate<? super T> predicate)
This method determines from the Predicate interface that if it is true it will be discarded to generate a new stream, and terminates when it hits false, regardless of whether the following elements meet the criteria.
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,20Copy the code
-
Iterate overloading
Previously using the Iterate method to generate an infinite stream required truncation in conjunction with limit
Stream<Integer> limit= Stream.iterate(1, i -> i + 1).limit(5); limit.forEach(System.out::println); / / 1, 2, 3, 4, 5Copy the code
Now overloaded this method adds a judgment argument
Stream<Integer> iterate = Stream.iterate(1, i -> i <= 5, i -> i + 1); iterate.forEach(System.out::println); / / 1, 2, 3, 4, 5Copy the code
4.Optional enhancement @since 9
-
stream()
Returns an empty stream if null, and converts the Optional value to a stream if not null.
Stream<String> Stream = option.of ("Java 11").stream(); stream.forEach(System.out::println); Stream<Object> Stream = optional.ofnullable (null).stream(); stream.forEach(System.out::println); //Copy the code
-
ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)
The ifPresentOrElse method is used to call action (action.accept(value)) on an Optional value if it contains an Optional value. This is consistent with ifPresent; IfPresentOrElse differs from ifPresent in that it has a second argument, emptyAction — ifPresentOrElse calls emptyAction if Optional does not contain a value, Namely emptyAction. The 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. Copy the code
-
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
Copy the code
5.InputStream enhancement @since 9
String lxs = "java";
try (var inputStream = new ByteArrayInputStream(lxs.getBytes());
var outputStream = new ByteArrayOutputStream()) {
inputStream.transferTo(outputStream);
System.out.println(outputStream); //java
}
Copy the code
HTTP Client API
The API supports both synchronous and asynchronous modes. Here are examples of both modes:
var request = HttpRequest.newBuilder()
.uri(URI.create("https://www.baidu.com/")) .build(); var client = HttpClient.newHttpClient(); / / synchronize HttpResponse < String > response = client. Send (request, HttpResponse. BodyHandlers. OfString ()); System.out.println(response.body()); // Async CompletableFuture<HttpResponse<String>> sendAsync = client.sendAsync(request, HttpResponse.BodyHandlers.ofString()); HttpResponse<String> response1 = sendAsync.get(); System.out.println(response1.body());Copy the code
Run Java files directly
As we all know, to run a.java file, first compile javac into a.class file and then execute it in Java:
Compile javac java11.java // Run Java Java11Copy the code
In Java 11, all you need is a command from Java
java Java11.java
Copy the code
Remove the content
- Com. The sun. The awt. AWTUtilities.
- Sun. Misc. Unsafe. DefineClass using Java. Lang. Invoke. MethodHandles. Lookup. DefineClass to replace.
- Thread.destroy() and thread.stop (Throwable) methods.
- Sun. Nio. Ch. DisableSystemWideOverlappingFileLockCheck properties.
- Sun. Locale. Formatasdefault properties.
- JDK SNMP module.
- Javafx, openJDK was removed from Java10, Oracle Java10 has not removed JavafX, and Java11 removed JavafX.
- Java Mission Control, once removed from the JDK, will need to be downloaded separately.
- Root Certificates: Baltimore Cybertrust Code Signing CA, SECOM, AOL and Swisscom.
- Java EE and CORBA modules deprecated in Java 9 have been removed in Java 11.
Full support for Linux containers (including Docker)
Many applications running in Java virtual machines (including data services such as Apache Spark and Kafka, as well as traditional enterprise applications) can run in Docker containers. The problem with running Java applications in Docker containers is that running JVM applications in Docker containers can cause performance degradation after setting memory size and CPU usage. This is because the Java application is not aware that it is running in a container. With the release of Java 10, this issue has finally been resolved and the JVM can now recognize constraints set by container control groups (CGroups). You can use memory and CPU constraints in containers to manage Java applications directly, including:
- Adhere to the memory limits set in the container
- Set the available CPU in the container
- Set the CPU constraints in the container
This improvement in Java 10 works with Docker for Mac, Docker for Windows, and Docker Enterprise Edition.
conclusion
reference
Segmentfault.com/a/119000001…
Thank you for watching and I hope you’ll pay more attention. Please correct any mistakes.