2018/10/13

Java SE 11 not mentioned in JEP

このエントリーをはてなブックマークに追加

Java SE 11 was release on 25th Sep.

Features of Java SE are proposed in JEP (JDK enhancement proposal), and Java SE 11 includes 17 JEPs.

However, there are many small updates not mentioned in JEP. So, I summarized these small updates, especially java.base module.

I excepted security features, because I don't have enough knowledge about security.

 

Removed API

Java is the language that give weight to compatibility, however Java compatibility policy has been changed since Java SE 9.

In fact, there are many APIs removed in Java SE 11.

Module

The biggest incompatibility of Java SE 11 is to remove modules about Java EE. This was proposed in JEP 320.

These modules were deprecated in Java SE 9, but we can still use them in Java SE 9 and 10.

However, the modules were removed finally in Java SE 11!

The removed modules are following:

  • java.se.ee
  • java.activation (JAF)
  • java.corba
  • java.transaction (JTA)
  • java.xml.bind (JAXB)
  • java.xml.ws (JAX-WS)
  • java.xml.ws.annotation (JAX-WS)

You can use JAF, JTA, JAXB and JAX-WS of Java EE (Jakarta EE). These modules are also registered in Maven central reposity. I wrote the article how to use JAXB and JAF in Maven project.

No alternative about CORBA, but I think no one uses CORBA any more.

In addition, JavaFX modules in Oracle JDK were removed (OpenJDK doesn't include JavaFX modules.)

  • javafx.base
  • javafx.graphics
  • javafx.controls
  • javafx.fxml
  • javafx.media
  • javafx.web
  • javafx.swing

JavaFX is developed by OpenJFX project in OpenJDK. JavaFX 11 is also released before Java SE 11.

New JavaFX Site was opened at the same time as JavaFX 11 release. You can download JavaFX 11 and refere Javadoc of JavaFX 11 at the site.

Class

There were many changes about security API. Following class was removed:

  • java.security.Policy

Method

forRemovel atribute of @Deprecated annotation was introduced in Java SE 9. Type of forRemoval is boolean, and true means that target API will be removed.

In Java SE 11, following methods that forRemoval value were true were removed:

  • java.lang.Runtime.runFinalizersOnExit(boolean)
  • java.lang.SecurityManager.checkAwtEventQueueAccess()
  • java.lang.SecurityManager.checkMemberAccess(java.lang.Class, int)
  • java.lang.SecurityManager.checkSystemClipboardAccess()
  • java.lang.SecurityManager.checkTopLevelWindow(java.lang.Object)
  • java.lang.System.runFinalizersOnExit(boolean)
  • java.lang.Thread.destroy()
  • java.lang.Thread.stop(java.lang.Throwable)

All of removed methods were that forRemoval value were true in Java SE 9.

APIs proposed for Removal

Follwoing APIs were proposed for removal in Java SE 11.

Class

  • java.util.jar.Pack200

Interface

  • java.util.jar.Pack200.Packer
  • java.util.jar.Pack200.Unpacker

Pack200 class was proposed by JEP 336.

All of deprecated API are listed in Deprecated in Javadoc.

 

Added APIs

java.io package

ByteArrayOutputStream class

  • void writeBytes(byte[] b)

This method is equivalent to write(b, 0, b.lenght).

FileReader class

Two constructors are introduced.

  • FileReader(java.io.File file, java.nio.charset.Charset charset)
  • FileReader(java.lang.String fileName, java.nio.charset.Charset charset)

Finally, we can specify charset to create FileReader object!

FileWriter class

Four constructers with charset are also introduced as FileReader.

  • FileWriter(java.io.File file, java.nio.charset.Charset charset)
  • FileWriter(java.io.File file, java.nio.charset.Charset charset, boolean append)
  • FileWriter(java.lang.String fileName, java.nio.charset.Charset charset)
  • FileWriter(java.lang.String fileName, java.nio.charset.Charset charset, boolean append)

InputStream class

  • static InputStream nullInputStream()
  • byte[] readNBytes(int len)

nullInputStream method is a factory method to create InputStream object that reads no bytes.

readNBytes method was introduced in Java SE 9. In Java SE 11, overload method is also introduced.

You need to specify byte array for readNBytes in Java SE 9, but no need byte array argument in Java SE 11. You only specigy lenght of read bytes.

However, I think the implementation is not so efficient at the present. Therefore, if reading data repeatedly in a loop, you should use a buffer byte array instead of readNBytes in Java SE 11. If reading all data at once, readAllbytes method is suitable.

OutputStream class

  • static OutputStream nullOutputStream()

nullOutputStream method is a factory method to create OutputStream object that writes no bytes as InputStream.

Reader class

  • static Reader nullReader()

Writer class

  • static Writer nullWriter()

java.lang package

CharSequence interface

  • static int compare(java.lang.CharSequence cs1, java.lang.CharSequence cs2)

compare method is a static method to compare two arguments.

I think it is a simple delegation method, but the implementation of compare methods compares two arguments character one by one.

Character class

  • static String toString(int codePoint)

toString method to create String object from char argument is existed, but no int argument until Java SE 11. It means we can use a codepoint of Unicode to create String object.

Character.UnicodeBlock class

Java SE 11 enable to use Unicode 10. With this update, 18 constans of Unicode block are added.

Character.UnicodeScript enum

With introducing Unicode 10, 10 script name of Unicode are added.

Class class

  • Class<?> getNestHost()

getNestHost method returns host class object of nested class. When class is non-nest, array, or primitive, it returns self class object.

  • Class<?>[] getNestMembers()

getNestMembers returns nested members.

  • boolean isNestmateOf(Class<?> c)

Comparing to the host class of argument Class object. When argument is array or primitive type, it returns false.

These three methods were porposed by JEP 181 Nest-Based Access Control.

String class

  • boolean isBlank()

isBlank return true when string is empty or only white space.

  • Stream<String> lines()

lines method divides string by line break, and makes Stream object.

  • String repeat(int count)

repeat method makes a concatenated string repeatedly by count argument value. For example, "a".repeat(3) returs "aaa".

  • String strip()
  • String stripLeading()
  • String stripTailing()

These three methods remove all white spaces of leading and trailing.

strip method removes leading and trailing white spaces, stripLeading method removes only leading, and stripTailing method removes only tailiing.

strip and stripLeading methods are similar to trim method. But, trim method removes only Latin-1 white space.

To remove non-Latin-1 white space such as U+3000, you should use strip/stripLeading/stripTailing methods.

StringBuffer class

StringBuilder class

These two classes now implement Comparable interface. Therefore, we can use compareTo method of these classes.

java.lang.invoke package

A class was added to java.lang.invoke package.

  • ConstantBootstraps class

boostrap of this class name means bootstrap method for InvokeDynamic bytecode. InvokeDynamic define how to process dynamically, and bootstrap is used for this purpose. InvokeDynamic is used for dynamic type JVM language such as JRuby and Lambda expression.

Java SE 11 introduced new bytecode, that is CONSTANT_Dynamic. CONSTANT_Dynamic is used for constant initialization, on the other hand InvokeDynamic is for method invoking.

CONSTANT_Dynamic also uses bootstrap method for defining constant initialization.

ConstantBootstraps is a utility class for bootstrap of CONSTANT_Dynamic.

By the way, javac of Java SE 11 doesn't use CONSTANT_Dynamic. In the future, javac will make class file including CONSTANT_Dynamic.

java.lang.ref package

Reference class

  • Object clone()

The reason clone method is overridden is to indicate Reference class can't clone. Therefore, the clone method always throws CloneNotSupportedException.

But, I think root cause is that clone method is defined in Object class. Although the root cause is clear, the cause can't be fixed anymore. So, clone method in Reference class is work-around.

java.nio package

ByteBuffer class

  • int mismatch(ByteBuffer that)

CharBuffer class

  • int mismatch(CharBuffer that)

DoubleBuffer class

  • int mismatch(DoubleBuffer that)

FloatBuffer class

  • int mismatch(FloatBuffer that)

IntBuffer class

  • int mismatch(IntBuffer that)

LongBuffer class

  • int mismatch(LongBuffer that)

ShortBuffer class

  • int mismatch(ShortBuffer that)

mismatch method compares this buffer and argument buffer, and returns the relative index that two buffers are diifferent. If the buffers are equal, it returns -1.

The relative means that mismatch method scans from the position to the limit of buffers.

Even if the first absolute mismatch index is before the position, mismatch method doesn't check it.

java.nio.chanels package

SelectionKey class

  • int interestOpsAnd(int ops)
  • int interestOpsOr(int ops)

SelectionKey class is used for non-blocking socket communication, and defines some constans of operations.

These constants are expressed a bit, and can do bit operations such as AND or OR. For example, OP_READ is 0b0001, and OP_WRITE is 0b0100.

We can get/set the present operation value by interestOps method.

Above two methods are combination methods of interestOps and AND or OR operation.

key.interestOpsAnd(ops) is equivalent to key.interestOps(key.interestOps() & ops). At the same way, key.interestOpsOr(ops) is same as key.interestOps(key.interestOps() | ops).

Selector class

Selector class is also used for non-blocking communitation. Now, we can describe the non-blocking process by lambda expression.

  • int select(java.util.function.Consumer<SelectionKey> action)
  • int select(java.util.function.Consumer<SelectionKey> action, long timeout)
  • int selectNow(java.util.function.Consumer<SelectionKey> action)

Until Java SE 11, we get SelectionKey object by selectedKeys method, and handle it according to the operation of SelectionKey object.

Now, we can describe like following:

    selector.select(key -> {
        try {
            if (key.isAcceptable()) {
                // OP_ACCEPT case
                ServerSocketChannel serverSocket = (ServerSocketChannel) key.channel();
                // change to Non-Blocking mode
                serverSocket.configureBlocking(false);
                // register to Selector
                serverSocket.register(selector, SelectionKey.OP_READ);
            } else if (key.isReadable()) {
                // OP_READ case
                SocketChannel socket = (SocketChannel) key.channel();
                // read contents...
            }
        } catch (IOException ex) {
            // exception handling
        }
    });

I don't like exception handling in lambda expression, but description is much easier than boefore.

java.nio.file package

Path interface

static Path of(java.lang.String first, java.lang.String... more)

static Path of(java.net.URI uri)

Two factory methods were added to Path interface.

The former factory method is equivalent to FileSystems.getDefault().getPath(first, more). It means the former factory method deal with phisical file system.

The latter factory method returns Path object of default phisical file system if schema of URI is "file". If not, it checks whether schema of URI is possible to deal with or not. If possible, the factory method calls getPath(uri) method of FileSystemProvider class.

Files class

  • static String readString(java.nio.file.Path path)
  • static String readString(java.nio.file.Path path, java.nio.charset.Charset cs)
  • static Path writeString(java.nio.file.Path path, java.lang.CharSequence csq, java.nio.file.OpenOption... options)
  • static Path writeString(java.nio.file.Path path, java.lang.CharSequence csq, java.nio.charset.Charset cs, java.nio.file.OpenOption... options)

Files class defines readAllLines method to read the contents at one time, but type of return value is List<String>. On the other hand, readString methods returns a String object of file contes including line break code.

In the same way, writeString writes a CharSequence object to path at one time.

java.util package

Collection interface

  • <T> T[] toArray(IntFunction<T[]> generator)

Collection intterface added an overload of toArray method. Argument of new toArray method is a generator function to allocate the returned array.

Optional class

OptionalDouble class

OptionalInt class

OptionalLong class

  • boolean isEmpty()

isEmpty method is reverse of isPresent method.

java.tuil.concurrent package

TimeUnit enum

long convert(java.time.Duration duration)

convert method converts duration to time unit. For example, TimeUnit.MILLISECONDS.convert(Duration.ofMinutes(1L)) returns 60000.

java.util.function package

Predicate interface

  • <T> Predicate<T> not(Predicate<? super T> target)

not method creates Predicate object that indicates negative condition of target.

java.util.regex package

Pattern class

  • Predicate<String> asMatchPredicate()

asPredicate method was introduced in Java SE 8. The asPredicate method creates Predicate object to use for an argument of fiter method, mid-operation of Stream pipeline.

However, Predicate object created by asPredicate is equivalent to s -> s.matcher().find(). It means partial check.

asMatchPredicate method also creates Predicate object, but the object checks whole string. It is equivalent to s -> s.matcher().matches().

    Pattern pattern = Pattern.compile("bc");
    List<String> list = List.of("abc", "bc", "bcd");

    list.stream()
        .filter(pattern.asPredicate())
        .forEach(System.out::println);

    list.stream()
        .filter(pattern.asMatchPredicate())
        .forEach(System.out::println);

The former result of above code is "abc", "bc", and "bcd", but the latter result is only "bc".

java.util.zip package

Deflater class

  • int deflate(java.nio.ByteBuffer output)
  • int deflate(java.nio.ByteBuffer output, int flush)
  • void setDictionary(java.nio.ByteBuffer dictionary)
  • void setInput(java.nio.ByteBuffer input)

Deflater class is used for ZLIB compress.

New four methods are all overloads. Argument of exsited methods are byte array, however one of new methods are ByteBuffer.

Inflater class

  • int inflate(java.nio.ByteBuffer output)
  • void setDictionary(java.nio.ByteBuffer dictionary)
  • void setInput(java.nio.
  • ByteBuffer input)

Inflater class is used for uncompressing ZLIB compressed contents.

As same as Deflater class, new methods enable to use ByteBuffer for argument.

0 件のコメント: