0% found this document useful (0 votes)
20 views13 pages

Java 17 Features: Sealed Classes & More

java 17

Uploaded by

Ajay
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views13 pages

Java 17 Features: Sealed Classes & More

java 17

Uploaded by

Ajay
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1. What Are SealedClasses?

o SealedInterfaces

2. Pattern Matchingfor instanceof


3. WhatAre Records?
4. WhatIs Strong Encapsulation?
5. NewGarbage Collectors
o HowIt Works

 Divides memory into twogenerations:


 Java 21 IMprovements
 Other Collectors(Still Available)
6. VectorAPI
o What is Vector API?

 Purpose
 Key Components
 How It Works
7. TextBlocks

1. What Are Sealed Classes?


restrict which classes or interfaces can extend or implement a
given class or interface.

🧩 Syntax

public sealed class Shape permits Circle, Square, Triangle {

// class body}

 sealed: Declares the class as sealed.

 permits: Lists the classes allowed to extend this sealed


class.

Each permitted subclass must be declared as either:

 sealed

 non-sealed

 final
Sealed Interfaces:

You can also seal interfaces to restrict which classes implement


them

 public sealed interface Vehicle permits Car, Bike {}

Subclass Options

Modifier Meaning

final Cannot be extended further.

Can be extended, but must declare its own


sealed
permits clause.

non- Removes sealing — allows unrestricted


sealed extension.

🧠 Why Use Sealed Classes?

 ✅ Exhaustive pattern matching: Useful with switch or


instanceof checks.

 ✅ Better control: Prevents unwanted subclassing.

 ✅ Improved readability: Makes hierarchies explicit.

 ✅ Safer refactoring: You know all subclasses at compile time.

Real-World Backend Use Case: Error Handling

public sealed class ServiceError permits TimeoutError,


ValidationError, DatabaseError {

public abstract String getMessage();

public final class TimeoutError extends ServiceError {

public String getMessage() {

return "Request timed out.";

}
public final class ValidationError extends ServiceError {

public String getMessage() {

return "Invalid input.";

public final class DatabaseError extends ServiceError {

public String getMessage() {

return "Database connection failed.";

This lets you handle errors like:

public void handleError(ServiceError error) {

switch (error) {

case TimeoutError t -> log([Link]());

case ValidationError v -> notifyUser([Link]());

case DatabaseError d -> alertOps([Link]());

2. Pattern Matching for instanceof


🔍 Traditional instanceof (Before Java 16)

if (obj instanceof String) {


String s = (String) obj; // explicit cast
[Link]([Link]());
}
We had to check the type and then cast it manually.

🚀 Pattern Matching instanceof (Java 16+)


if (obj instanceof String s) {
[Link]([Link]()); // no cast needed
}
 The variable s is automatically cast to String if the check
passes.
 Scope of s is limited to the if block.

3. What Are Records?


 Definition

o Records are a special kind of class in Java.


o Their purpose is to simplify the creation of data-holding objects.
 Purpose
o Designed to reduce boilerplate code for classes that primarily
store data.
o Automatically generate methods like equals(),
hashCode(), and toString().

🚫 Limitations
 Records cannot extend other classes (they implicitly
extend [Link]).
 Fields are final and cannot be changed after
construction.
 Not suitable for mutable or behavior-heavy classes.
🛠 Use Cases
 DTOs (Data Transfer Objects)
 Configuration objects
 Lightweight domain models
 Return types for service methods

example of a record in Java that models a Person:


public record Person(String name, int age) {}
🔍 What This Does
This single line of code automatically gives you:
 A final class named Person
 Two private final fields: name and age
 A constructor: Person(String name, int age)
 Getter methods: name() and age()
 equals(), hashCode(), and toString() methods
🧪 Example Usage
public class Main {
public static void main(String[] args) {
Person p = new Person("Aarav", 30);
[Link]([Link]()); // Output: Aarav
[Link]([Link]()); // Output: 30
[Link](p); // Output: Person[name=Aarav,
age=30]
}
}

4. What Is Strong Encapsulation?


Strong encapsulation refers to the default restriction of access to
internal APIs and non-exported packages in Java modules.

exported or opened packages are accessible outside a module.


🧱 Why It Was Introduced

Before Java 9, developers developed on internal JDK classes (like


[Link]) that were never meant for public use.

 Security risks due to access to privileged operations.

 Maintenance issues when internal APIs changed or were removed.

 Compatibility problems during JDK upgrades.

Strong encapsulation aims to:

 Improve security and maintainability of the JDK.

 Encourage use of standard APIs.

 Prevent accidental dependencies on unstable internal code.

📦 How It Works

Java modules define boundaries using [Link].

 Exported packages: Accessible to other modules.

 Unexported packages: Hidden from other modules.

 Opened packages: Accessible via reflection (if explicitly opened).

 Internal APIs: Not exported or opened, hence inaccessible.

Even reflection-based access is blocked unless the package is explicitly


opened.

⚙️Example

Suppose you have a module:

module [Link] {

exports [Link];

 [Link] is accessible to other modules.

 Any other package (e.g., [Link]) is strongly


encapsulated.
Exceptions and Migration

Some internal APIs like [Link] are still accessible via the
[Link] module for compatibility reasons.

To ease migration:

 Java 9 introduced the --illegal-access option:

o permit: Allows access to JDK 8 internal packages.

o warn: Logs warnings.

o deny: Blocks access completely.

This option was removed in Java 17, enforcing strong encapsulation fully.

✅ Benefits

 Robustness: Prevents fragile dependencies.

 Security: Limits access to sensitive operations.

 Cleaner architecture: Encourages modular design.

 Future-proofing: Easier upgrades across Java versions.

5. New Garbage Collectors


Generational ZGC (Z Garbage Collector)

 A low-latency, scalable garbage collector.

 Introduced in Java 11 (non-generational), enhanced in Java 21


with generational support.

🧠 How It Works
Divides memory into two generations:
o Young Generation: Where new objects are created.

o Old Generation: long-lived objects are moved after surviving


several collections.

 Collects young objects more frequently, reducing overhead and


improving performance.

🎯 Benefits
 Faster GC cycles for short-lived objects.

 Lower pause times even with large heaps.

 Better performance for typical Java workloads.

⚙️How to Enable

Use JVM options:

java -XX:+UseZGC -XX:+UseGenerationalZGC -Xmx2G MyApp

📊 Monitoring Tools

 Use JVisualVM or Java Mission Control (JMC).

 Enable GC logging:

-Xlog:gc

2. 🌀 Shenandoah GC (Improved)

Java 21 Improvements
 Enhanced support for large heaps and high-concurrency
applications.

 Better integration with virtual threads.

Other Collectors (Still Available)


Collector Description Use Case

Region-based, balances pause Default in many Java


G1 GC
and throughput versions

Parallel GC High throughput, longer pauses Batch processing

Serial GC Simple, single-threaded Small applications

ZGC (non- Large heaps, real-time


Unified heap, low latency
generational) systems

📌 Summary

 Java 21’s highlight is the Generational ZGC, combining low


latency with smart memory management.

 Shenandoah GC also sees performance boosts.


 These collectors help Java apps run faster, smoother, and more
efficiently—especially in cloud, big data, and real-time
environments.

Context-Specific Deserialization Filters

🔐 What Is Deserialization?

Deserialization is the process of converting binary data back into Java


objects.

If not handled carefully, it can be load malicious or unexpected


classes, leading to security risks.

🧠 What Are Context-Specific Deserialization Filters?

define which classes are allowed or denied during deserialization,


based on the context in which deserialization occurs.

✅ Key Features:

 Fine-grained control over deserialization.

 Filters can be applied per stream, not just globally.

 Helps prevent unauthorized class loading.

 Supports custom logic using predicates or patterns.

How to Use Them

You can set a filter on an ObjectInputStream like this:

🔍 Explanation:

 [Link]() gives the class being deserialized.


 You check if it belongs to a safe package.

 You allow or reject based on your rules.

📦 Use Cases

 Web applications: Prevent attackers from sending harmful


serialized data.

 Microservices: Ensure only expected classes are deserialized


across services.

 Third-party data: Safely handle data from external sources.

6. Vector API
📌 What is Vector API?
 A Java API for performing vectorized computations using SIMD
(Single Instruction, Multiple Data).

 Introduced as an incubator module in JDK 16 ([Link]).

Purpose
 To accelerate performance of numerical and data-parallel
operations.

 Enables Java programs to use CPU vector instructions efficiently.

🧩 Key Components
Component Description

Defines shape and size of


VectorSpecies<T>
vectors

FloatVector, IntVector,
Type-specific vector classes
etc.

Enables conditional lane


VectorMask
operations

VectorShuffle Rearranges vector lanes


How It Works
1. Choose a VectorSpecies (e.g., IntVector.SPECIES_256).

2. Load data into a vector using fromArray.

3. Perform operations like add, mul, etc.

4. Store results back to an array.

Benefits

 High performance: Leverages SIMD for parallel processing.

 Platform independence: Abstracts hardware-specific instructions.

 Safer than native code: No need for JNI or unsafe memory access.

Use Cases

 Image processing

 Signal processing

 Machine learning inference

 Financial modelling

🚧 Limitations

 Still in incubator stage (subject to change).

 Requires modern CPUs with SIMD support.

 Adds complexity—best for performance-critical code.

Setting Up

Requirements

 JDK 17 installed.

 Enable incubator modules when compiling and running:

 javac --add-modules [Link] [Link]

 java --add-modules [Link] YourClass

4. Step-by-Step Example: Adding Two Arrays

Step 1: Import the API

import [Link].*;

Step 2: Define Species


VectorSpecies<Float> SPECIES = FloatVector.SPECIES_256;

Step 3: Create Arrays

float[] a = new float[8];

float[] b = new float[8];

float[] result = new float[8];

Step 4: Fill Arrays

[Link](a, i -> (float) [Link]());

[Link](b, i -> (float) [Link]());

Step 5: Vector Addition

for (int i = 0; i < [Link]; i += [Link]()) {

FloatVector va = [Link](SPECIES, a, i);

FloatVector vb = [Link](SPECIES, b, i);

FloatVector vc = [Link](vb);

[Link](result, i);

7. Text Blocks
📌 Text Blocks in Java 17 — Key Points

1. Syntax: Use triple double quotes """ to define a text block.

2. String text = """

3. Line 1

4. Line 2

5. Line 3

6. """;

7. Purpose: Simplifies multi-line string creation and improves


readability.

8. Whitespace Handling: Java automatically removes common


leading whitespace.

9. Escape Sequences: Supports standard escapes like \n, \t, \".


10. String Type: Text blocks are still regular String objects.

11. Formatting: Use .formatted() to inject values.

12. String name = "Alice";

13. String greeting = """

14. Hello, %s!

15. """.formatted(name);

16. Use Cases: Ideal for HTML, SQL, JSON, XML, and other
structured text.

Common questions

Powered by AI

Sealed classes enhance safe refactoring by making hierarchies explicit during compile time, which means developers are aware of all subclasses that can extend a sealed class. This prevents unexpected subclassing, thus providing a controlled and predictable class hierarchy. Consequently, sealed classes improve modular design and extensibility by restricting which classes or interfaces can extend them .

Records benefit Java by significantly reducing boilerplate code when creating data-holding classes, automatically providing implementations for methods like equals(), hashCode(), and toString(). They are particularly useful for DTOs (Data Transfer Objects) and configuration objects. However, records cannot extend other classes as they implicitly extend java.lang.Record, and their fields are final and immutable, limiting their use in mutable or behavior-heavy classes .

The Generational Z Garbage Collector (ZGC) differs from traditional garbage collectors by dividing memory into two generations: young and old. Young objects are collected more frequently to reduce overhead, while long-lived objects are moved to the old generation after surviving several collections. This approach leads to faster garbage collection cycles for short-lived objects, reduced pauses even with large heaps, and improved performance for typical Java workloads .

The Vector API leverages SIMD (Single Instruction, Multiple Data) to enable Java applications to perform parallel processing at a high performance level. By using SIMD, the API allows operations on multiple data points with a single instruction, enhancing computational efficiency in numerical and data-parallel tasks. However, the API is still in the incubator stage, requiring CPUs with modern SIMD support. This also adds complexity, making it best suited for performance-critical code .

In Java 21, improvements to the Shenandoah Garbage Collector include better support for applications with large heap sizes and increased concurrency by enhancing its pause time reduction and integration with new Java features such as virtual threads. These enhancements enable Shenandoah to handle parallel garbage collection more efficiently, thus improving the responsiveness and scalability of high-concurrency applications .

Context-specific deserialization filters provide security benefits by allowing developers to define finely-grained controls over which classes are allowed or denied during the deserialization process. By applying filters per stream rather than globally, they help prevent unauthorized class loading and protect against vulnerabilities that could exploit deserialization to execute malicious code, especially when dealing with data from third-party or external sources .

Text blocks in Java 17 improve readability by simplifying the formatting of multi-line strings, eliminating the need for manual newline characters and complex quoting. Java automatically handles indentation, allowing developers to better visualize the structure of strings such as JSON or XML directly within the code, making them ideal for structured data representation. Text blocks can also use escape sequences and support string formatting, adding flexibility for inserting dynamic content .

The introduction of modules in Java addresses accidental dependencies by enforcing strong encapsulation via the module system, which allows developers to explicitly declare dependencies, control access across module boundaries, and prevent unintended exposure of internal APIs. This approach resolves compatibility issues typically encountered in large projects by ensuring that only clearly defined modules interact with one another, simplifying maintenance and easing upgrades by eliminating reliance on unstable, internal JDK classes .

Strong encapsulation improves security by restricting access to internal APIs and non-exported packages, which helps prevent accidental dependencies on unstable code and reduces security risks. By discouraging reliance on internal JDK classes, it ensures that applications are dependent on stable, public APIs, improving maintainability. This encapsulation also aids in cleaner architecture by modularizing applications more effectively, easing future upgrades across Java versions .

Pattern matching for 'instanceof' in Java 16+ enhances code readability and reduces error-prone manual type casting by automatically casting a tested variable to the proper type within the scope of the 'if' statement. This eliminates the need for explicit casting and improves the concise expression of type-checking logic, minimizing verbosity and potential casting errors associated with traditional instanceof checks .

You might also like