New features of Java10

  java10

Java language feature series

Order

This article focuses on the new features of Java10

Property list

Relevant interpretation:Java10 series (ii) Local-Variable Type Inference

Relevant interpretation:Java10 is coming, let’s take a look at the new JIT compiler it has released together.

Relevant interpretation:OpenJDK 10 Now Includes Root CA Certificates

Relevant interpretation:Java10 series (i) Time-Based Release Versioning

Detailed interpretation

The features listed above are in many aspects. Besides, there are also some api updates and discards. SeeWhat’s New in JDK 10 – New Features and EnhancementsHere are a few examples.

Optional.orElseThrow()

/Library/Java/JavaVirtualMachines/jdk-10.jdk/Contents/Home/lib/src.zip! /java.base/java/util/Optional.java

  • Source code
    /**
     * If a value is present, returns the value, otherwise throws
     * {@code NoSuchElementException}.
     *
     * @return the non-{@code null} value described by this {@code Optional}
     * @throws NoSuchElementException if no value is present
     * @since 10
     */
    public T orElseThrow() {
        if (value == null) {
            throw new NoSuchElementException("No value present");
        }
        return value;
    }
  • Example
    @Test
    public void testOrElseThrow(){
        var data = List.of("a","b","c");
        Optional<String> optional = data.stream()
                .filter(s -> s.startsWith("z"))
                .findAny();
        String res = optional.orElseThrow();
        System.out.println(res);
    }

OrElseThrow has been added to correspond to get.

Output

java.util.NoSuchElementException: No value present

    at java.base/java.util.Optional.orElseThrow(Optional.java:371)
    at com.example.FeatureTest.testOrElseThrow(FeatureTest.java:19)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

APIs for Creating Unmodifiable Collections

The interface parameters of the of factory method added by java9 are elements. java10 adds List.copyOf, Set.copyOf, and Map.copyOf to create ImmutableCollections from existing collections

  • Copy of source code
    /**
     * Returns an <a href="#unmodifiable">unmodifiable List</a> containing the elements of
     * the given Collection, in its iteration order. The given Collection must not be null,
     * and it must not contain any null elements. If the given Collection is subsequently
     * modified, the returned List will not reflect such modifications.
     *
     * @implNote
     * If the given Collection is an <a href="#unmodifiable">unmodifiable List</a>,
     * calling copyOf will generally not create a copy.
     *
     * @param <E> the {@code List}'s element type
     * @param coll a {@code Collection} from which elements are drawn, must be non-null
     * @return a {@code List} containing the elements of the given {@code Collection}
     * @throws NullPointerException if coll is null, or if it contains any nulls
     * @since 10
     */
    @SuppressWarnings("unchecked")
    static <E> List<E> copyOf(Collection<? extends E> coll) {
        if (coll instanceof ImmutableCollections.AbstractImmutableList) {
            return (List<E>)coll;
        } else {
            return (List<E>)List.of(coll.toArray());
        }
    }
  • Example
    @Test(expected = UnsupportedOperationException.class)
    public void testCollectionCopyOf(){
        List<String> list = IntStream.rangeClosed(1,10)
                .mapToObj(i -> "num"+i)
                .collect(Collectors.toList());
        List<String> newList = List.copyOf(list);
        newList.add("not allowed");
    }

Collectors have added tounmodified ablelist, tounmodified ableset, and toUnmodifiableMap methods.

    @Test(expected = UnsupportedOperationException.class)
    public void testCollectionCopyOf(){
        List<String> list = IntStream.rangeClosed(1,10)
                .mapToObj(i -> "num"+i)
                .collect(Collectors.toUnmodifiableList());
        list.add("not allowed");
    }

Summary

The most important new feature of java10 belongs to Local-Variable Type Inference at the syntax level, while it belongs to jvm307: Parallel Full GC for G1as well as317: Experimental Java-Based JIT CompilerBoth of them are quite heavy and deserve further study.

doc