Switch Expressions comes with Java 12

Switch Expressions comes with Java 12

Java 12, the latest six-monthly release of Java, has been released with support for Switch Expressions and the inclusion of the Shenandoah low-pause garbage collector. 

There are eight main improvements to the new release, starting with switch expressions. This is still a preview feature, and it extends the switch statement so that it can be used as either a statement or an expression. Whichever form is used, you can use either a traditional or a simplified scoping and control flow behavior.

Oracle says that in addition to simplifying everyday coding, the addition prepares the way for the use of pattern matching in the switch statement. Pattern matching is available as another preview language feature.   Currently, the default flow of control of switch blocks is fall through, so requiring a break statement to avoid the rest of the Case statements in a block being tested and potentially executed. The new switch expressions introduce a new form of switch label, written “case L ->” to signify that only the code to the right of the label is to be executed if the label is matched. For example:

switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);
    case TUESDAY                -> System.out.println(7);
    case THURSDAY, SATURDAY     -> System.out.println(8);
    case WEDNESDAY              -> System.out.println(9);

The next improvements to the new release are to the current garbage collector. From now on, the garbage collector will  automatically return Java heap memory to the operating system when idle rather than waiting until a full garbage collection to return memory to the operating system, and it will also respect pause times better.

Until now, the garbage collector sometimes started an amount of work that would take longer than the pause target, meaning the task overran. Under the improved version, if this is happening, the garbage collector lowers its targets.  Still on garbage collection, Shenandoah has been added in an experimental version. Shenandoah is Java’s new low-pause-time garbage collector algorithm. It reduces GC pause times by doing evacuation work concurrently with the running Java threads. Pause times with Shenandoah are independent of heap size, meaning you will have the same consistent pause times whether your heap is 200 MB or 200 GB.

Another improvement is the addition of a basic suite of microbenchmarks to the JDK source code, as well as making it easy for developers to run existing microbenchmarks and create new ones. There’s also a new JVM Constants API that can be used to model nominal descriptions of key class-file and run-time artifacts.

The OpenJDK open source release is available now, along with the commercial license version. JDK 12 will receive a minimum of two updates before being followed by Oracle JDK 13, which is due out in September 2019.

More Information