• 周四. 12月 1st, 2022

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Learn about the new features of Java 9 – 16 quickly to help you get out of the inner volume

[db:作者]

1月 6, 2022

Click on the above “ Zhu Xiaosi’s blog ”, choice “ Set to star ”

The background to reply ” book “, obtain

The background to reply “k8s”, Can claim k8s Information

JAVA The update in recent years is too much …… fast ,JAVA 8 It hasn’t been long ,16 All have been released . since JAVA 8 Released Lambda and Stream after ,JAVA It’s like beating chicken blood , A half year release , The donkeys in the production team are not so diligent .

So we can’t keep up now JAVA Rhythm of release , Our company is still in JAVA 8, Even some old systems are still in use JAVA 7, It’s not easy to upgrade .

But although I can’t use the latest version for the time being JAVA, But it’s important to understand the main features of each new release , Otherwise, it will be upgraded one day , That’s not enough .

This article will take you to understand JAVA 9 – 16 The main new features of , Finish school early and finish work early !

JAVA 9(2017 year 9 month )

Private interfaces can be added to interfaces

JAVA 8 Support for default methods has been added to the interface , stay JAVA 9 There is another upgrade to this function in , Now you can define private methods in the interface , Then call the private method of the interface in the default method .

thus , You can reuse code in private methods , You can keep the code secret

public interface TestInterface {
    default void wrapMethod(){
        innerMethod();
    }
    private void innerMethod(){
        System.out.println("");
    }
}

Anonymous inner classes also support diamonds (diamond) Operator

JAVA 5 Generics are introduced (generic), here we are JAVA 7 Start supporting diamonds (diamond) Operator :<>, You can automatically infer the type of a generic :

List<Integer> numbers = new ArrayList<>();

But this automatic inference type diamond operator doesn’t support anonymous inner classes , stay JAVA 9 Anonymous inner classes are also supported in :

List<Integer> numbers = new ArrayList<>() {
    ...
}

Enhanced try-with-resources

JAVA 7 Added in try-with-resources Support for , Resources can be automatically shut down :

try (BufferedReader bufferReader = new BufferedReader(...)) {
    return bufferReader.readLine();
}

But when you need to declare multiple resource variables , The code looks a little disgusting , Need to be in try Write the creation process of multiple variables in :

try (BufferedReader bufferReader0 = new BufferedReader(...);
    BufferedReader bufferReader1 = new BufferedReader(...)) {
    return bufferReader0.readLine();
}

JAVA 9 This feature has been enhanced in , You can reference try Variables outside the code block :

BufferedReader bufferReader0 = new BufferedReader(...);
BufferedReader bufferReader1 = new BufferedReader(...);
try (bufferReader0; bufferReader1) {
    System.out.println(br1.readLine() + br2.readLine());
}

JAVA 10(2018 year 3 month )

Automatic type inference of local variables (var)

JAVA 10 It brings a very interesting grammar – var, It can automatically infer the type of local variables , No more typing , You don’t have to rely on it lombok Of var Annotations enhance

var message = "Hello, Java 10";

But this is just grammar candy , After compiling, variables still have types , When using it, consider the issue of maintainability , Otherwise, if you write too much, it will be JavaScript Style

JAVA 11(2018 year 9 month )

Lambda Automatic type inference in (var)

JAVA 11 Chinese vs Lambda Grammar also supports var This automatic type inference variable , adopt var Variables can also add additional annotations :

List<String> languages = Arrays.asList("Java", "Groovy");
String language = sampleList.stream()
  .map((@Nonnull var x) -> x.toUpperCase())
  .collect(Collectors.joining(", "));
assertThat(language).isEqualTo("Java, Groovy");

javac + java Order a shuttle

I used to compile a java When you file , It needs to be done first javac Compiled into class, And then use java perform , Now you can have a shuttle :

$ java HelloWorld.java
Hello Java 11!

Java Flight Recorder land OpenJDK

Java Flight Recorder It’s a useful debugging and diagnosis tool , But before it was Oracle JDK in , Also follow JDK 11 Open source ,OpenJDK You can also use this function , It’s delicious !

JAVA 12(2019 year 3 month )

More concise switch grammar

Prior to JAVA In the version ,switch The grammar is rather wordy , If multiple values follow one logic, you need to write multiple case

DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek();
String typeOfDay = "";
switch (dayOfWeek) {
    case MONDAY:
    case TUESDAY:
    case WEDNESDAY:
    case THURSDAY:
    case FRIDAY:
        typeOfDay = "Working Day";
        break;
    case SATURDAY:
    case SUNDAY:
        typeOfDay = "Day Off";
}

here we are JAVA 12, This thing becomes very simple , In a few lines , and ! It also supports return values :

typeOfDay = switch (dayOfWeek) {
    case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Working Day";
    case SATURDAY, SUNDAY -> "Day Off";
};

instanceof + The type of forced transfer is in place in one step

Before dealing with dynamic types, when it comes to forced conversion , It needs to be done first instanceof Judge , And then it’s forced to this type of processing :

Object obj = "Hello Java 12!";
if (obj instanceof String) {
    String s = (String) obj;
    int length = s.length();
}

Now? instanceof Support for direct type conversion , There’s no need to do another forced turn :

Object obj = "Hello Java 12!";
if (obj instanceof String str) {
    int length = str.length();
}

JAVA 13(2019 year 9 month )

switch Grammar reinforces

JAVA 12 Although it has been enhanced swtich grammar , But not in -> And then write complex logic ,JAVA 12 brought swtich A more perfect experience , It’s like lambda equally , You can write logic , And then back again :

typeOfDay = switch (dayOfWeek) {
    case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> {
        // do sth...
        yield "Working Day";
    }
    case SATURDAY, SUNDAY -> "Day Off";
};

Text block (Text Block) Support for

Are you still bothered by the long string messages with newline characters , Line breaks, a bunch of line breaks , If you don’t change your line, it’s hard to see :

String json = "{\"id\":\"1697301681936888\",\"nickname\":\" unreality \",\"homepage\":\"https://juejin.cn/user/1697301681936888\"}";

JAVA 13 China has solved this disgusting problem for you , Added text block support , Now we can happily spell strings with new lines , It’s like using a template :

String json = """
                {
                    "id":"1697301681936888",
                    "nickname":" unreality ",
                    "homepage":"https://juejin.cn/user/1697301681936888"
                }
                """;

JAVA 14(2020 year 3 month )

Newly added record type , Take out the complicated POJO class

Usually we create a POJO class , You need to define a list of properties , Constructors ,getter/setter, More trouble .JAVA 14 It brings us a convenient way to create classes – record

public record UserDTO(String id,String nickname,String homepage) { };
public static void main( String[] args ){
    UserDTO user = new UserDTO("1697301681936888"," unreality ","https://juejin.cn/user/1697301681936888");
    System.out.println(user.id);
    System.out.println(user.nickname);
    System.out.println(user.id);
}

IDEA This function has been supported for a long time , When creating a class, you can directly select :

But this is just a grammar candy , After compiling, it’s still a Class, And ordinary Class Not much difference

More intuitive NullPointerException Tips

NullPointerException Count as JAVA It’s the most common exception in , But it’s really unfriendly , When you come across some longer chain expressions , There’s no way to tell which object is empty .

For example, in the following example , What is the innerMap It’s empty , still effected It’s empty ?

Map<String,Map<String,Boolean>> wrapMap = new HashMap<>();
wrapMap.put("innerMap",new HashMap<>());
boolean effected = wrapMap.get("innerMap").get("effected");
// StackTrace:
Exception in thread "main" java.lang.NullPointerException
    at org.example.App.main(App.java:50)

JAVA 14 also get here we are JAVAER Our pain points , To optimize the NullPointerException A hint of , Let you not be confused , You can locate it at a glance “ empty ” Where is the !

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Boolean.booleanValue()" because the return value of "java.util.Map.get(Object)" is null
    at org.example.App.main(App.java:50)

current StackTrace It’s very intuitive , Just tell you effected The variable is empty , No more confusion !

Secure off heap memory read / write interface , Stop playing Unsafe I’ve done it

In the previous version ,JAVA If you want to manipulate out of heap memory (DirectBuffer), Still have to Unsafe Various copy/get/offset. Now a set of secure out of heap memory access interfaces has been added directly , Easy access to off heap memory , No more Unsafe I’ve done it .

//  Distribute  200B  Out of heap memory
MemorySegment memorySegment = MemorySegment.allocateNative(200);
//  use  ByteBuffer  Distribute , And then it's packaged as  MemorySegment
MemorySegment memorySegment = MemorySegment.ofByteBuffer(ByteBuffer.allocateDirect(200));
// MMAP  Of course
MemorySegment memorySegment = MemorySegment.mapFromPath(
  Path.of("/tmp/memory.txt"), 200, FileChannel.MapMode.READ_WRITE);
//  Get out of heap memory address
MemoryAddress address = MemorySegment.allocateNative(100).baseAddress();
//  Combined boxing , Off heap distribution , Out of heap assignment
long value = 10;
MemoryAddress memoryAddress = MemorySegment.allocateNative(8).baseAddress();
//  Get handle
VarHandle varHandle = MemoryHandles.varHandle(long.class, ByteOrder.nativeOrder());
varHandle.set(memoryAddress, value);
//  Release is so simple , Think  DirectByteBuffer  Release …… How strange
memorySegment.close();

Don’t understand Unsafe Students who operate the mode of out of heap memory , You can refer to another article of mine 《JDK For performance Unsafe class , Can you use ?》

Newly added jpackage Packaging tools , Packing binaries directly , No more JRE 了

Previously, if you wanted to build an executable program , We also need to use three tools , take JRE Pack together , Or let the client’s computer install one JRE To run our JAVA Program .

Now? JAVA Directly built in jpackage Packaging tools , Help you pack binary packages with one click , Finally, there’s no need to toss about

JAVA 15(2020 year 9 month )

ZGC and Shenandoah Two garbage collectors are officially launched

stay JAVA 15 in ,ZGC and Shenandoah It’s no longer an experimental function , Officially landed ( however G1 It’s still the default ). If you upgrade to JAVA 15 Later versions , Just give it a try , Better performance , Less delay

closed (Sealed ) class

JAVA At present, we can only choose to allow inheritance and not to allow inheritance (final modification ), Now there’s a new closure (Sealed ) Class , You can specify certain classes to inherit :

public sealed interface Service permits Car, Truck {
    int getMaxServiceIntervalInMonths();
    default int getMaxDistanceBetweenServicesInKilometers() {
        return 100000;
    }
}

JAVA 16(2021 year 3 month )

JAVA 16 It doesn’t change much where the user can see it , Basic it is 14/15 The experimental content of , here we are 16 Official release , I won’t repeat it here .

summary

The new features described above , Some of the features are experimental in historical versions , But according to JAVA At present, this donkey has the same update frequency , It’s very likely that the next version will be the stable version . Learn early and enjoy early , Late school is taken away ……

source | https://juejin.cn/post/6964543834747322405

Want to know more ? sweep Trace the QR code below and follow me

The background to reply ” technology “, Join the technology group

The background to reply “k8s”, Can claim k8s Information

【 Highlights 】

  • ClickHouse What is it ? Why is it so cool !

  • original ElasticSearch That’s understandable

  • interviewer :InnoDB One of them B+ How many rows of data can a tree hold ?

  • The way of Architecture : Separate business logic from technical details

  • Starbucks doesn’t use two-phase commit

  • interviewer :Redis The new version begins to introduce multithreading , Tell me what you think ?

  • Himalaya self research gateway architecture evolution process

  • Collection : A comprehensive summary of storage knowledge

  • Microblog tens of millions of scale, high performance and high concurrency network architecture design

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注