JavaRush /Java Blog /Random EN /New Java… Again… Meet Java 10

New Java… Again… Meet Java 10

Published in the Random EN group
Previously, developers waited for a new Java for several years, some with horror, and some with hope. Times have changed, and new versions of the JDK will delight us every six months. If it’s not yet clear to you what this will lead to, check out the expert’s opinion , and here we will list the main changes in Java 10, the newest version of our favorite language. New Java... Again... Meet Java 10 - 1In square brackets before the new “feature” the JEP number is indicated, that is, “JDK Enchancement Proposal”. JEP is a proposal to improve OpenJDK and may be approved, delayed, or rejected. That is, in essence, a collection of JEPs is a development strategy for OpenJDK.

Important features of Java 10

[286] Local-Variable Type Inference - A proposal to introduce the var keyword into Java, eliminating the need to explicitly specify the type of a local variable. That is, now you can not specify the type of the initialized variable, but write something like:
var list = new ArrayList<String>();  //перед нами ArrayList<String>
var stream =;          // перед нами Stream<String>
This eliminates the duplication of the ArrayList<String> type definition that we would have had to use before. It's interesting to note that var does not become a keyword, but is a reserved type. That is, you can use var as the name of a variable, method, or package. But you won’t be able to name the class that way (what a loss!). [296] Merging the JDK forest into a single repository . JDK 9 has eight repositories - root, corba, hotspot, jaxp, jaxws, jdk, langtools, nashorn. In Java 10, this entire forest will be combined into a single repository to make it possible to perform atomic commits across repositories of interdependent changesets. [304] The Garbage-Collector Interface is not an interface that can be used by developers to control garbage collection. Instead, we get a clean garbage collector interface in the JVM source code, allowing you to quickly and easily integrate alternative collectors. Those who dreamed of adding their own garbage collector to the JVM will be most pleased with this improvement. [307] Parallel Full GC for the G1 garbage collector . In JDK 9, G1 became the default garbage collector, whereas previously the default garbage collector was Parallel GC, which could collect garbage across multiple threads. Now G1 can do this too; previously it did it in one thread, which sometimes caused difficulties. By the way, developers will be able to configure the number of threads using the - XX:ParallelGCThreads. [310] Application Class-Data Sharing parameter - this development, adopted in Java 10, offers improved loading and tracking, extends the existing Class Sharing (CDS) feature to allow application classes to be located in general archive. Class-Data Sharing or CDS for short works with files with the *class extension. This function allows you to select a certain subset of classes, process them and compress them into a special archive. All this is done to save memory. Often different instances of the JVM load the same classes included in the standard library. And CDS allows all these JVM instances to share a single archive with classes placed in it. This reduces both program loading time and memory usage. In fact, CDS improves JVM startup performance and reduces resource footprint when multiple JVMs are running on the same physical or virtual machine, starting with version 5. But earlier the use of CDS was limited to bootstrap loader only. Now an extended version called Application CDS allows you to load special archives with classes for other loaders. [312] Thread-Local Handshakes is a fairly low-level change within the JVM that will allow callbacks to be executed across threads without running a global VM safety point. This will allow you to costlessly stop individual threads, rather than all at once (or none at all). [313] Remove the Native-Header Generation Tool (javah) . Back in Java 9, language developers began to actively remove unnecessary tools, and JEP 313 continues this good work. The javah tool generates JNI headers if there are native methods in the code. Healthy? Of course, but the native javac compiler, starting with JDK 8, can itself generate JNI headers. So now they decided to get rid of javah. By the way, the Panama project is currently being developed , which, in particular, can replace JNI. [314] Additional Unicode Language-Tag Extensions This change is intended to improve the java.util.Locale class and associated APIs to implement additional Unicode extensions to BCP 47 language tags. In particular, tags for the currency type (cu), day one will now be supported week (fw), region (rg) and time zone (tz) overrides. [316] Heap Allocation on Alternative Memory Devices This innovation will help those who use memory types other than DRAM. Since technologies are constantly changing, the use of non-volatile memory with the same interface and performance characteristics similar to DRAM is an objective reality today. So, JEP 316 allows the JVM to place a heap in other types of memory. [317] Experimental Java-Based JIT Compiler . The Metropolis project was recently announced, which proposes to rewrite most of the JVM in Java. In case you didn't know, the current version is written in C++. Well, if you are already in the know, probably at first such an idea will seem strange to you. Since the JVM is written in Java, wouldn't you need a JVM to run the JVM? Such is the recursion, reminiscent of mirrors opposite each other. However, the reality is a little different: just because the JVM is written in Java, that doesn't mean you have to compile it into bytecodes. You can actually use AOT compilation and then JIT compiles the code as it works to improve performance.

A tool such as javac is commonly used to compile Java code. It converts a Java program into a set of class files with bytecodes. Next, the JVM runs your bytecode and its interpreter converts them into processor instructions. In addition to the interpreter, the JVM also has a built-in compiler, and it can also create instructions for the processor from bytecode. This is the so-called runtime compilation, compilation during startup. Usually the code that is most often used is subjected to such compilation - this improves performance.

The compiler can perform actions in different ways: JIT compilation (just-in-time) - dynamic, right during program execution, or AOT compilation (ahead-of-time) - before execution.

The jaotc AOT compiler was introduced in JDK 9. Currently, the Hotspot JVM contains two JIT compilers, C1 (for speed) and C2 (for optimization).

JEP 317 introduces the Graal research project, a compiler for the JDK. This is a certain basis that will help make Metropolis a reality and enable the JVM to match (or better yet, exceed) the current version written in C++ in performance. [319] Root Certificates are the default set of standard Certification Authority (CA) certificates in the JDK. Critical security components such as TLS will now work by default in OpenJDK builds. This useful addition is likely part of what Oracle is doing to ensure that OpenJDK binaries and Oracle JDK binaries are functionally the same. [322] Time-Based Release Versioning - in Java 10, new features will be added to Feature releases, and bugs will be fixed in Update Releases. Essentially, we have a new way to set JDK version string formats. It fixes a rather strange situation with JDK 9. The first update was JDK 9.0.1, which is quite logical. The second update is JDK 9.0.4, which is illogical. The logic is that within the JDK 9 version numbering scheme, space is left between updates in case of an emergency, unplanned update. Since the update wasn't necessary, why not just call it JDK 9.0.2? And here's what the new Java version format looks like:

New APIs

There are 73 additions to the JDK 10 standard class libraries.
  • java.awt.Toolkit

    int getMenuShortcutKeyMaskEx (): Defines which extended modifier key is the corresponding accelerator key for the shortcut menu.

  • java.awt.geom.Path2D:

    void trimToSize (): Trims the capacity of this instance Path2Dto its current size. An application can use this operation to minimize path storage. The same method has been added to the inner classes Path2D.Doubleand Path2D.Float.


    String toString (Charset): overloaded toString, converts the contents of a buffer into a string by decoding the bytes using the specified encoding.

  • and

    Both of these classes have three new constructors that take an additional argument charset.


    long transferTo (Writer): Reads all characters from this reader and writes the characters to the given writer in the order in which they are read.

  • java.lang.Runtime.Version:

    Four new methods that return an integer value for the new version (JEP 322) of string fields: feature (), interim (), patch ()and update ().

  • java.lang.StackWalker.StackFrame:

  • String getDescriptor():

    returns a handle to the method represented by this stack frame, as defined by the Java Virtual Machine Specification.

  • String getMethodType():

    returns MethodType, representing the parameter types and return type for the method represented by the stack frame.

  • java.lang.invoke.MethodType:

    Class <?> LastParameterType (): возвращает последний тип параметра этого типа метода. Если этот тип не имеет параметров, instead of него возвращается meaning sentinel void.class.


    long getPid () возвращает pid запущенной виртуальной машины Java.


    ThreadInfo [] dumpAllThreads (boolean, boolean, int): возвращает информацию о потоке для всех потоков в реальном времени с трассировкой стека с указанным максимальным количеством элементов и информацией о синхронизации.

  • ThreadInfo [] getThreadInfo (long [], boolean, boolean, int):

    возвращает информацию о потоке для каждого потока, чья идентификация находится во входном массиве, с трассировкой стека указанного максимального количества элементов и информацией о синхронизации.

  • java.lang.reflect.MalformedParameterizedTypeException:

    добавлен новый конструктор, который принимает подробное сообщение в виде строки в качестве параметра.

  • и

    оба этих класса получor новые перегруженные методы расcodeирования и codeирования, которые используют charset в качестве дополнительного параметра.

  • java.nio.channels.Channels:

    Два новых статических перегруженных метода, newReader (ReadByteChannel, Charset) и newWriter (WriteByteChannel, Charset), которые позволяют использовать charset.

  • java.nio.file.FileStore:

    long getBlockSize (): возвращает количество byteов на блок в этом хранorще файлов.

  • java.time.chrono:

    три класса в этом пакете, HijrahEra, MiinguoEra и ThaiBuddhistEra, получor метод String getDisplayName (TextStyle, Locale). Он возвращает текстовое Name, используемое для идентификации эпохи, подходящее для представления пользователю.

  • java.time.format.DateTimeFormatter:

    localizedBy (Locale): возвращает копию этого форматтера с локализованными значениями языка, календаря, региона, десятичного стиля и / or часового пояса, которые заменяют значения в этом формате.

  • java.util:

    DoubleSummaryStatistics, IntSummaryStatistics и LongSummaryStatistics получor новый конструктор, который принимает четыре числовых значения. Он создает непустой экземпляр с указанным счетчиком, минимумом, максимумом и суммой.

  • java.util.List, java.util.Map и java.util.Set:

    каждый из этих интерфейсов обзавёлся новым статическим методом copyOf (Collection). Они возвращают неизменяемые List, Map or Set, содержащие элементы данной коллекции, в своем порядке итерации.

  • java.util.Optional, java.util.OptionalDouble, java.util.OptionalInt, java.util.OptionalLong:

    каждый из этих классов получает новый метод orElseThrow (), который по существу делает то же самое, что и get (), то есть если condition выполняется, meaning возвращается. В противном случае генерируется исключение NoSuchElementException.

  • java.util.Formatter и java.util.Scanner:

    Оба этих класса получor три новых конструктора, которые на вход получают charset в дополнение к другим аргументам.

  • java.util.Properties:

    Здесь появился новый конструктор, который принимает аргумент int. Это создает пустой список свойств без значений по умолчанию и с начальным размером, содержащим указанное количество элементов без необходимости динамического изменения размера. Также появилась новая, перегруженная version метода replace, которая принимает три параметра Object и возвращает логическое meaning.

  • java.SplittableRandom:

    void nextBytes (byte []): заполняет предоставленный пользователем массив byteов с генерируемыми псевдослучайными byteами.

  • java.util.concurrent.FutureTask:

    добавлен метод toString (), который возвращает строку, идентифицирующую FutureTask, а также ее состояние завершения. Состояние (в скобках) содержит одну из строк: «Completed Normally» (нормальное завершение), «Completed Exceptionally» (завершение с исключением), «Cancelled» (отменено) or «Not completed» (не завершено).

  • java.util.concurrent.locks.StampedLock:

    новые методы boolean isLockStamp (long), boolean isOptimisticReadStamp (long), boolean isReadLockStamp (long) и boolean isWriteLockStamp (long).

  • java.jar.JarEntry:

    String getRealName (): возвращает настоящее Name этого JarEntry. Если JarEntry является записью мультирелизного jar-file, настроенного для обработки, тогда Name, возвращаемое этим методом — Name пути версии, которую представляет JarEntry. Иначе JarEntry возвращает то же Name, что и ZipEntry.getName ().

  • java.util.jar.JarFile:

    Stream <JarEntry> versionedStream (): возвращает поток записей в файле с версией jar. Подобно методу getRealName для JarEntry, связан с мультирелизными jar-fileми.

  • java.util.spi.LocaleNameProvider:

    getDisplayUnicodeExtensionKey (String, Locale): возвращает локализованное Name для данного Unicode extension key. getDisplayUnicodeExtensionType (String, String, Locale): возвращает локализованное Name для данного Unicode extension key.


    toUnmodifiableList (), toUnmodifiableSet (), toUnmodifiableMap (Function, Function), toUnmodifiableMap (Function, Function, BinaryOperator) — эти четыре новых метода возвращают коллекторы (Collectors), которые накапливают входные элементы в соответствующую немодифицируемую коллекцию.

  • java.lang.model.SourceVersion:

    теперь это поле RELEASE_10 для представления версии JDK 10.

  • java.lang.model.util.TypeKindVisitor6 и javax.lang.model.util.TypeKindVisitor9:

    что-то не вполне понятное:).

  • R visitNoTypeAsModule (NoType, P):

    посещает псевдо-тип MODULE.


    У этого класса было добавлено два поля: CREDENTIALS_FILTER_PATTERN и SERIAL_FILTER_PATTERN.

  • javax.ButtonModel:

    Представляете, Swing все еще обновляется!

  • ButtonGroup getGroup ():

    возвращает группу, к которой принадлежит кнопка. Обычно используется с radio buttons, которые являются взаимоисключающими в своей группе.

  • javax.plaf.basic.BasicMenuUI:

    Dimension getMinimumSize (JComponent): возвращает минимальный размер указанного компонента, подходящий для внешнего вида.