Blog

Java 17 | What you need to know

Key Takeaways

  • Java 17 introduces notable features like sealed classes, pattern matching for switch expressions, and enhanced pseudo-random number generators.
  • Deprecated features include the Applet API and Security Manager, reflecting the move away from older paradigms.
  • Removed functionalities such as RMI Activation and AOT/JIT Compilers signify a shift towards more stable, widely-used alternatives.
  • The new release process for Java focuses on regular long-term support (LTS) releases every two years.

Preface: What is a JEP?

JEP stands for JDK Enhancement Proposal, essentially suggesting improvements to the Java language. Not every proposal becomes part of the language, but many of the features in Java 17 stem from such proposals.

Curious for more? Here's a deeper dive into What is a JEP in Java?

New Features in Java 17

Java 17 brings several development-friendly enhancements. Here are the key ones that benefit developers:

Sealed Classes (JEP 409)

Sealed interfaces and classes control which other classes can implement or extend them, providing a more maintainable codebase.

public sealed interface Animal permits Cow, Pig {
    void makeNoise();
}

By defining:

public sealed class Habitat permits Ocean, Land {
    ...
}

Sealed classes, initially a preview feature in Java 15, are now fully integrated. They help enforce specific architectural constraints, such as limiting what can implement the Product interface in an e-commerce app.

Pattern Matching for Switch (JEP 406)

Java 17 introduces improvements allowing pattern matching with switch expressions, still under a preview status but with notable perks:

public class Demo {
    public static void main(String[] args){
        System.out.println(printObject("hello"));
        System.out.println(printObject(100));
        System.out.println(printObject(3));
        System.out.println(printObject(null));
    }
    static String printObject(Object obj) {
        return switch (obj) {
            case String s -> "Object is string: " + s;
            case Integer i && i >= 100 -> "Object is a BIG integer: " + i;
            case Integer i -> "Object is an integer: " + i;
            case null -> "Object is null";
            default -> "Object is something else";
        };
    }
}

This update simplifies null handling, allows combined condition logic, and enhances readability with arrow functions.

Pseudo-Random Number Generators (JEP 356)

Efficiently generating random numbers just got easier with new options for pseudo-random number generators (PRNG).

RandomGenerator xoShiro = RandomGeneratorFactory.of("Xoshiro256PlusPlus").create();
RandomGenerator lxm = RandomGeneratorFactory.of("L32X64MixRandom").create();
System.out.println(xoShiro.nextInt(10));
System.out.println(lxm.nextInt(10));

The RandomGeneratorFactory supports streaming APIs:

RandomGeneratorFactory.all()
        .map(factory -> factory.name())
        .sorted()
        .forEach(System.out::println);

This showcases seamless PRNG integration into applications, offering both flexibility and performance.

Foreign Function & Memory API (JEP 412)

Replacing JNI, this API provides a more robust approach to interact with native code and manage memory outside the Java heap. This incubator feature aims for safer and easier native memory access.

MemorySegment memorySegment = MemorySegment.allocateNative(200);

This code snippet demonstrates simple allocation of native memory, enhancing performance and safety over the traditional JNI method.

Context-Specific Deserialization Filters (JEP 415)

With deserialization being a potential security weak spot, these filters enhance safety by restricting class deserialization based on context.

public class Demo {
    public static void main(String[] args) throws Exception{
        byte[] bytes = convertObjectToStream(new HashMap());
        InputStream inputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream s = new ObjectInputStream(inputStream);
        s.setObjectInputFilter(createFilter());
        s.readObject();
    }
    private static ObjectInputFilter createFilter() {
        return filterInfo -> {
            Class<?> clazz = filterInfo.serialClass();
            if (clazz != null) {
                return (HashMap.class.isAssignableFrom(clazz))
                        ? ObjectInputFilter.Status.REJECTED
                        : ObjectInputFilter.Status.ALLOWED;
            }
            return ObjectInputFilter.Status.UNDECIDED;
        };
    }

    private static byte[] convertObjectToStream(Object obj) {
        ByteArrayOutputStream boas = new ByteArrayOutputStream();
        try (ObjectOutputStream ois = new ObjectOutputStream(boas)) {
            ois.writeObject(obj);
            return boas.toByteArray();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        throw new RuntimeException();
    }
}

This method prevents insecure data from being executed inadvertently, adding an enhanced layer of protection.

Deprecated Features in Java 17

Java 17 deprecates several outdated features, providing modern alternatives:

Deprecate Applet API (JEP 398)

Once vital for enhanced browser performance, the Applet API becomes redundant in an era of powerful JavaScript frameworks. Discontinued support by major browsers since 2017 underscores this shift.

Deprecate Security Manager (JEP 411)

The Security Manager's relevance dwindles, particularly with its antiquated focus on applet security policies. New security paradigms make it obsolete.

Removed Features in Java 17

Java 17 also says goodbye to certain lesser-utilized features.

Remove RMI Activation (JEP 407)

This feature, initially supporting object activation across systems, sees its demise in favor of more stable alternatives.

Remove AOT/JIT Compilers (JEP 410)

Limited adoption of these compilers led to their removal. Newer alternatives offer better performance optimization pathways.

A New Release Process...

Java has streamlined its release cycle. Every two years brings a new Long-Term Support (LTS) version, with Java 21 as the next anticipated in September 2023. The frequent six-month feature releases ensure rapid introduction and feedback from the development community.

This cycle elevates the overall quality and relevance of Java's features, keeping pace with community and technological advancements.

Conclusion

This overview highlights significant features and changes in Java 17, important for developers aiming to stay ahead in Java application development.

FAQ

What is the main purpose of sealed classes in Java 17?

Sealed classes allow developers to define a limited set of classes that can extend a particular base class, helping enforce design constraints and simplify architectures.

Why was the Security Manager deprecated in Java 17?

The Security Manager was deprecated due to its declining applicability, particularly with web applets, and newer, more relevant approaches to application security.

How does the new release process affect Java developers?

With more frequent LTS releases and interim feature releases, developers can adopt new Java features quickly and contribute feedback, leading to software that better meets community needs.

Mastering the tech interviewWhat everyone is doing wrong in tech interviews