How do I use new Java 10 methods like List.copyOf(), Set.copyOf(), and Map.copyOf()?

Java 10 introduced the List.copyOf(), Set.copyOf(), and Map.copyOf() methods as convenient ways to create unmodifiable copies of existing collections. These methods are part of the java.util package and provide a simpler way to create immutable collections compared to using older methods like Collections.unmodifiableList().

Here’s how you can use them:


1. List.copyOf()

The List.copyOf() method creates an unmodifiable copy of the provided Collection. The returned list:

  • Is immutable (you cannot add, remove, or modify elements).
  • Rejects null elements (throws a NullPointerException).

Example:

package org.kodejava.util;

import java.util.List;

public class ListCopyExample {
    public static void main(String[] args) {
        // Create a mutable list
        List<String> originalList = List.of("A", "B", "C");

        // Create an unmodifiable copy
        List<String> unmodifiableList = List.copyOf(originalList);

        // Print the copied list
        System.out.println(unmodifiableList);

        // Throws UnsupportedOperationException if modification is attempted
        // unmodifiableList.add("D");

        // Throws NullPointerException if original list has nulls
        // List<String> listWithNull = new ArrayList<>();
        // listWithNull.add(null);
        // List.copyOf(listWithNull);
    }
}

2. Set.copyOf()

The Set.copyOf() method creates an unmodifiable copy of the provided Collection, ensuring that:

  • The returned set contains no duplicate elements.
  • Null elements are not allowed.
  • The original collection can be a List, Set, or any Collection.

Example:

package org.kodejava.util;

import java.util.Set;

public class SetCopyExample {
   public static void main(String[] args) {
      // Create a mutable set
      Set<String> originalSet = Set.of("A", "B", "C");

      // Create an unmodifiable copy
      Set<String> unmodifiableSet = Set.copyOf(originalSet);

      // Print the copied set
      System.out.println(unmodifiableSet);

      // Throws UnsupportedOperationException
      // unmodifiableSet.add("D");
   }
}

3. Map.copyOf()

The Map.copyOf() method creates an unmodifiable copy of the provided map. Similar to List.copyOf() and Set.copyOf():

  • The returned map is immutable.
  • Null keys or values are not allowed.
  • Elements retain the original insertion order (if applicable, e.g., for LinkedHashMap).

Example:

package org.kodejava.util;

import java.util.Map;

public class MapCopyExample {
   public static void main(String[] args) {
      // Create a mutable map
      Map<Integer, String> originalMap = Map.of(1, "One", 2, "Two", 3, "Three");

      // Create an unmodifiable copy
      Map<Integer, String> unmodifiableMap = Map.copyOf(originalMap);

      // Print the copied map
      System.out.println(unmodifiableMap);

      // Throws UnsupportedOperationException
      // unmodifiableMap.put(4, "Four");
   }
}

Notes:

  1. Immutable Behavior:
    • Any attempt to modify the unmodifiable collections (e.g., using add() or put()) throws UnsupportedOperationException.
    • These methods return a new collection, but if the input collection is already immutable and meets the conditions, it may return the original collection (performance optimization).
  2. Handling Nulls:
    • If any input collection contains null elements, these methods will throw a NullPointerException.
  3. Differences from Existing Methods:
    • Unlike Collections.unmodifiableList()/Set()/Map(), these methods create a copy, ensuring that changes to the source collection won’t affect the new collection.
  4. Static Imports:
    • These methods belong to static utility classes (List, Set, and Map) and are invoked directly as static methods.

Summary:

  • Use these methods to get immutable copies of collections.
  • They reject null values by design.
  • Collections become unmodifiable and can’t be changed after creation.

They are great for enhancing immutability and safety of the application!

How to monitor memory with Java 10’s improved GC interface

Java 10 introduced enhancements to the Garbage Collection (GC) interface through the JEP 304: GC Interface, which abstracts garbage-collection implementations to improve integration and monitoring capabilities. While these improvements primarily simplify the addition of new garbage collectors to the JVM, they can also be leveraged to monitor memory usage and GC behavior in real time.

Here’s how to monitor memory using Java 10’s improved GC interface.

Key Concepts

The primary tools for monitoring memory and garbage collection (from Java 10 onward) include:
1. java.lang.management package: Interfaces and classes such as GarbageCollectorMXBean, MemoryMXBean, and MemoryPoolMXBean are still accessible.
2. java.util.logging or external libraries: For logging GC activity.
3. New Unified Logging framework: Can be used to log GC activities in detail starting with Java 9.


Steps to Monitor Memory Using Java 10 GC Interface:

1. Use the GarbageCollectorMXBean

The GarbageCollectorMXBean allows you to track details such as the number of collections, total collection time, and more.

Here’s an example:

package org.kodejava.lang.management;

import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.List;

public class GcMonitoringDemo {
    public static void main(String[] args) {
        // Get all GC beans
        List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans();

        for (GarbageCollectorMXBean gcBean : gcBeans) {
            System.out.println("Garbage Collector: " + gcBean.getName());
            System.out.println("Collection count: " + gcBean.getCollectionCount());
            System.out.println("Collection time (ms): " + gcBean.getCollectionTime());
        }

        // Simulate some memory load
        for (int i = 0; i < 10000; i++) {
            String[] temp = new String[1000];
            temp = null; // Let the memory be collected
        }

        System.out.println("After memory load:");
        for (GarbageCollectorMXBean gcBean : gcBeans) {
            System.out.println("Garbage Collector: " + gcBean.getName());
            System.out.println("Collection count: " + gcBean.getCollectionCount());
            System.out.println("Collection time (ms): " + gcBean.getCollectionTime());
        }
    }
}

Output will include:

  • Garbage collector names based on the JVM (e.g., G1 Young Generation, G1 Old Generation, etc.).
  • Collection count and total collection time.

2. Analyze Memory Usage via the MemoryMXBean

The MemoryMXBean interface helps monitor heap and non-heap memory usage.

package org.kodejava.lang.management;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;

public class MemoryMonitoringDemo {
    public static void main(String[] args) {
        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();

        // Get heap memory usage
        MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
        System.out.println("Heap Memory Usage:");
        System.out.println("  Init: " + heapMemoryUsage.getInit());
        System.out.println("  Used: " + heapMemoryUsage.getUsed());
        System.out.println("  Max: " + heapMemoryUsage.getMax());
        System.out.println("  Committed: " + heapMemoryUsage.getCommitted());

        // Get non-heap memory usage
        MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();
        System.out.println("Non-Heap Memory Usage:");
        System.out.println("  Init: " + nonHeapMemoryUsage.getInit());
        System.out.println("  Used: " + nonHeapMemoryUsage.getUsed());
        System.out.println("  Max: " + nonHeapMemoryUsage.getMax());
        System.out.println("  Committed: " + nonHeapMemoryUsage.getCommitted());
    }
}

3. Monitor GC Using Unified Logging

Starting from Java 9, the new Unified Logging Framework allows you to log GC activities comprehensively. You can enable it with various JVM options.

For example:

java -Xlog:gc* -XX:+UseG1GC -jar YourApplication.jar

Additional useful options include:

  • -Xlog:gc+heap: Logs GC and heap events.
  • -Xlog:gc+age: Logs information about object aging.
  • -Xlog:gc*=info,safepoint: Logs GC and safe-point information.

Output in the log will provide in-depth GC activity for analysis.


4. Advanced Real-Time Monitoring with JFR (Java Flight Recorder)

Java Flight Recorder (JFR) is another tool integrated into the JVM that enables detailed profiling and monitoring, including GC data.

java -XX:StartFlightRecording=filename=recording.jfr,duration=60s -XX:+UnlockCommercialFeatures -jar YourApplication.jar

After this recording, you can analyze recording.jfr in tools such as Java Mission Control (JMC).


5. Third-Party Tools for Active Monitoring

You can also leverage external tools or libraries:

  • VisualVM: Provides a GUI-based approach to monitor GC and memory usage.
  • micrometer.io: A metrics library for monitoring in microservices.
  • Prometheus + Grafana: To build custom dashboards for GC and memory metrics.

Conclusion

  • For basic JVM-based monitoring, use the GarbageCollectorMXBean and MemoryMXBean.
  • For detailed runtime logging of GC behavior, use the Unified Logging Framework.
  • For comprehensive profiling and diagnostics, use tools like JFR or VisualVM.

Java 10’s GC interface improvements make it easier to add and monitor new garbage collector implementations, but the existing Java Management Extensions (JMX) and logging tools are still central to effective memory monitoring.

How to inspect and use the enhanced Optional.orElseThrow() in Java 10

In Java 10, the Optional.orElseThrow() method was enhanced to become the preferred method for retrieving a value from an Optional when the value is present, and throwing an exception otherwise. Let’s explore how this works.


Enhanced Optional.orElseThrow()

Prior to Java 10, the Optional class provided:

  • orElse() – Retrieves the value if present or returns a default value.
  • orElseGet() – Retrieves the value or calculates one using a supplier.
  • orElseThrow(Supplier<? extends X> exceptionSupplier) – Retrieves the value or throws the exception provided by the supplier.

With Java 10, the Optional.orElseThrow() now acts as a shorthand for orElseThrow(NoSuchElementException::new) when you need to retrieve a value, and throw an exception if the value is absent, without providing a custom exception supplier.


Usage

Key Behavior:

  • If the Optional contains a value, orElseThrow() will return the value.
  • If the Optional is empty, it will throw a NoSuchElementException.

Example Code:

package org.kodejava.util;

import java.util.NoSuchElementException;
import java.util.Optional;

public class EnhancedOptionalExample {

    public static void main(String[] args) {
        // An Optional with a value
        Optional<String> optionalWithValue = Optional.of("Hello, Java 10!");

        // Retrieve the value using orElseThrow()
        String value = optionalWithValue.orElseThrow();
        System.out.println("Value: " + value); // Output: Hello, Java 10!

        // An empty Optional
        Optional<String> emptyOptional = Optional.empty();

        try {
            // Attempt to retrieve the value from an empty Optional
            emptyOptional.orElseThrow();
        } catch (NoSuchElementException e) {
            System.err.println("Caught Exception: " + e.getMessage()); // Output: No value present
        }
    }
}

Comparison with Other Optional Methods

Method Behavior
orElse(value) Returns the value if present; otherwise, returns the provided default value.
orElseGet(supplier) Returns the value if present; otherwise, computes a value using the supplier.
orElseThrow(supplier) Returns the value if present; otherwise, throws an exception provided by the supplier.
orElseThrow() (Java 10) Returns the value if present; otherwise, throws a NoSuchElementException (default).

Advantages of Enhanced orElseThrow()

  1. Simplicity: Eliminates the need to write orElseThrow(NoSuchElementException::new) explicitly.
  2. Readability: Makes the code concise and expressive.
  3. Standardized Exception: Default exception (NoSuchElementException) aligns with the semantics of an empty Optional.

Real-World Use Case

A common scenario is when processing data that is expected to be present:

Example:

Optional<String> username = fetchUsernameFromDatabase();

String verifiedUsername = username.orElseThrow();
System.out.println("Verified Username: " + verifiedUsername);

Here, if the username is absent, the application will throw a runtime exception (NoSuchElementException), indicating data inconsistency.


The enhanced Optional.orElseThrow() introduced in Java 10 simplifies handling Optional objects by providing a default exception mechanism without needing a custom supplier.

How to use the Collectors.toUnmodifiableList() and other new Collectors in Java 10

In Java 10, a significant enhancement was introduced to the java.util.stream.Collectors class: new utility methods to create unmodifiable collections such as lists and sets. One notable method is Collectors.toUnmodifiableList(). This method allows you to efficiently create immutable lists during stream processing, adding to the immutability features provided by Java 9 and earlier versions.

Here’s how you can use Collectors.toUnmodifiableList() and other similar methods introduced in Java 10:


1. Using Collectors.toUnmodifiableList()

The Collectors.toUnmodifiableList() collector creates an unmodifiable list from a stream of elements. This means the resulting list cannot be modified (no adding, removing, or updating elements). If you attempt to modify it, a runtime exception (UnsupportedOperationException) will be thrown.

Example:

package org.kodejava.util.stream;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class UnmodifiableList {
    public static void main(String[] args) {
        // Example list using Collectors.toUnmodifiableList
        List<String> unmodifiableList = Stream.of("A", "B", "C")
                .collect(Collectors.toUnmodifiableList());

        System.out.println("Unmodifiable List: " + unmodifiableList);

        // Attempt to modify the list will throw UnsupportedOperationException
        unmodifiableList.add("D"); // This will throw a runtime exception!
    }
}

Output:

Unmodifiable List: [A, B, C]
Exception in thread "main" java.lang.UnsupportedOperationException

2. Other Collectors Introduced in Java 10

Java 10 introduced two other collectors similar to toUnmodifiableList():

  • Collectors.toUnmodifiableSet()
    • Creates an unmodifiable set from a stream of elements.
    • Duplicate elements will be removed since it’s a set.

Example:

package org.kodejava.util.stream;

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class UnmodifiableSet {
    public static void main(String[] args) {
        Set<String> unmodifiableSet = Stream.of("A", "B", "C", "A") // "A" will appear only once
                .collect(Collectors.toUnmodifiableSet());
        System.out.println("Unmodifiable Set: " + unmodifiableSet);

        unmodifiableSet.add("D"); // Throws UnsupportedOperationException
    }
}
  • Collectors.toUnmodifiableMap()
    • Creates an unmodifiable map using key-value pairs from a stream.
    • Requires a way to specify the key and value in the collector.
    • If duplicate keys are produced, it will throw an IllegalStateException.

Example:

package org.kodejava.util.stream;

import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class UnmodifiableMap {
    public static void main(String[] args) {
        Map<Integer, String> unmodifiableMap = Stream.of("A", "B", "C")
                .collect(Collectors.toUnmodifiableMap(
                        String::length,  // Key mapper
                        v -> v           // Value mapper
                ));

        System.out.println("Unmodifiable Map: " + unmodifiableMap);

        // Attempting to modify will throw an UnsupportedOperationException
        unmodifiableMap.put(2, "D"); // Throws UnsupportedOperationException
    }
}

3. Behavior of Unmodifiable Collections

  • These collectors guarantee that:
    • The collection cannot be modified (no add, remove, put, etc.).
    • Any attempt to modify them results in an UnsupportedOperationException.
    • They are safe to use for read-only purposes.
  • If the stream itself contains null values, a NullPointerException will be thrown.

4. Best Uses of toUnmodifiable*() Collectors

  • Ensuring immutability for collections to prevent accidental modifications.
  • Useful in multi-threaded or concurrent applications where immutability eliminates thread-safety issues.
  • Perfect for cases where only read access is required.

5. Comparison with Java 9 List.of()

Java 9 introduced factory methods like List.of(), Set.of(), and Map.of() for creating immutable collections. While those methods are concise, the new collectors offer more flexibility when working with streams.

Java 9 Example:

List<String> immutableList = List.of("A", "B", "C");

Java 10 Stream Example:

List<String> immutableList = Stream.of("A", "B", "C")
                                   .collect(Collectors.toUnmodifiableList());

Summary Table:

Collector Description Introduced in
Collectors.toUnmodifiableList() Creates an unmodifiable List Java 10
Collectors.toUnmodifiableSet() Creates an unmodifiable Set Java 10
Collectors.toUnmodifiableMap() Creates an unmodifiable Map Java 10

Conclusion

The Collectors.toUnmodifiableList() and related methods introduced in Java 10 are powerful tools for creating immutable collections directly from streams. They ensure immutability, improve code safety, and fit well into functional programming paradigms introduced with Java Streams.

How to create cleaner code with type inference in Java 10

Type inference was introduced in Java 10 with the new var keyword, enabling developers to declare local variables without explicitly specifying their type. This feature can help create cleaner, more concise code by reducing boilerplate, though it should be used judiciously to maintain code readability.

Here’s a guide on how to use type inference effectively and write cleaner code in Java 10 and later:


1. Use var for Local Variables

The var keyword allows you to declare local variables without explicitly stating their type. The compiler infers the type based on the expression assigned to the variable. Here’s how it works:

Example:

var message = "Hello, World!"; // Compiler infers this as String
var count = 42;                // Compiler infers this as int
var list = new ArrayList<String>(); // Compiler infers this as ArrayList<String>

System.out.println(message);  // Hello, World!
System.out.println(count);    // 42

Benefits:

  • Eliminates redundancy. For instance:
List<String> list = new ArrayList<>();

becomes:

var list = new ArrayList<String>();

2. Use var in Loops

In for-each loops and traditional for-loops, var can simplify the code:

Example:

var numbers = List.of(1, 2, 3, 4, 5);
for (var num : numbers) {
    System.out.println(num); // Iterates through the numbers
}

Benefits:

  • Avoids unnecessary type declarations while maintaining readability.

3. Use var with Streams and Lambdas

var integrates well with Java Streams and Lambda expressions to reduce verbosity:

Example:

var numbers = List.of(1, 2, 3, 4, 5);
var result = numbers.stream()
                    .filter(n -> n % 2 == 0)
                    .map(n -> n * 2)
                    .toList();

System.out.println(result); // [4, 8]

When working with complex streams, var can make code shorter and easier to follow.


4. Restrictions on var

While var is versatile, there are some limitations and rules:

  • Only for Local Variables: var can only be used for local variables, loop variables, and indexes, not for class fields, method parameters, or return types.
  • Compiler Must Infer Type: You must assign a value to a var. For example, the following won’t work:
var uninitialized; // Error: cannot use 'var' without initializer
  • Anonymous Classes: Avoid overuse with anonymous classes to maintain clarity.

5. Maintain Readability

While var can simplify code, readability should always be a priority. Overusing var can obscure the code’s intent, especially when dealing with complex types:

Example of Overuse:

var map = new HashMap<List<String>, Set<Integer>>(); // Hard to understand

In such cases, it’s better to use explicit types.


6. Good Practices

  • Use var for Obvious Types:
var name = "John Doe"; // Obviously String
  • Avoid var for Ambiguous Types:
// Original:
var data = performOperation(); // What is the return type?
// Better:
List<String> data = performOperation();
  • Avoid Excessive Chaining:

    Using var with complex chains can make debugging harder. Be explicit when needed.


7. Refactoring Example

Here’s how you can refactor code for better clarity using var:

Before Refactoring:

ArrayList<String> names = new ArrayList<>();
HashMap<String, Integer> nameAgeMap = new HashMap<>();

After Refactoring:

var names = new ArrayList<String>();
var nameAgeMap = new HashMap<String, Integer>();

This is concise without sacrificing clarity.


Conclusion

Type inference with var in Java 10 improves code conciseness and readability when used appropriately. To ensure cleaner code:

  • Use var for obvious and readable scenarios.
  • Avoid using var when the inferred type is unclear or ambiguous.
  • Focus on balancing conciseness with the need for maintainable and self-explanatory code.