How to Use Pattern Matching with instanceof in Java 17

Pattern matching with the instanceof operator was introduced in Java 16 (as a preview feature) and became a standard feature in Java 17. It simplifies the process of type casting when checking an object’s type, making the code shorter and more readable.

Here’s how you can use pattern matching with instanceof in Java 17:

Syntax

With pattern matching, you can directly declare a local variable while checking the type with instanceof. If the condition is true, the variable is automatically cast to the specified type, and you can use it without explicit casting.

if (object instanceof Type variableName) {
   // Use variableName, which is already cast to Type
}

Key Features:

  1. Type Checking and Casting in One Step: No need for an explicit cast.
  2. Shorter Code: Reduces boilerplate.
  3. Available Within Scope: The variable is accessible only within the scope of the if block where the condition is evaluated as true.
  4. Guarded Pattern (Available in Java 20+ – Preview): Introduced later, allowing additional conditions within instanceof.

Example 1: Basic Usage

package org.kodejava.basic;

public class PatternMatchingExample {
   public static void main(String[] args) {
      Object obj = "Hello, Java 17!";

      if (obj instanceof String str) {
         // Type already checked and cast to `String`
         System.out.println("String length: " + str.length());
      } else {
         System.out.println("Not a string.");
      }
   }
}

Explanation:

  • The variable str is declared and automatically cast to String in the same instanceof statement.
  • Within the if block, you can directly use str as it is guaranteed to be a String.

Example 2: Pattern Matching in Loops

package org.kodejava.basic;

import java.util.List;

public class PatternMatchingExample {
   public static void main(String[] args) {
      List<Object> objects = List.of("Java", 42, 3.14, "Pattern Matching");

      for (Object obj : objects) {
         if (obj instanceof String str) {
            System.out.println("Found a String: " + str.toUpperCase());
         } else if (obj instanceof Integer num) {
            System.out.println("Found an Integer: " + (num * 2));
         } else if (obj instanceof Double decimal) {
            System.out.println("Found a Double: " + (decimal + 1));
         } else {
            System.out.println("Unknown type: " + obj);
         }
      }
   }
}

Output:

Found a String: JAVA
Found an Integer: 84
Found a Double: 4.14
Found a String: PATTERN MATCHING

Example 3: Combining && Conditions

You can combine pattern matching with additional conditions:

package org.kodejava.basic;

public class PatternMatchingExample {
   public static void main(String[] args) {
      Object obj = "Hello";

      if (obj instanceof String str && str.length() > 5) {
         System.out.println("String is longer than 5 characters: " + str);
      } else {
         System.out.println("Not a long string (or not a string at all).");
      }
   }
}

Notes:

  1. Scope of Variable:
    The variable introduced inside the instanceof is only accessible inside the block where the condition is true. For example:

    if (obj instanceof String str) {
       System.out.println(str); // str is available here
    }
    // System.out.println(str); // ERROR: str not available here
    
  2. Null Safety:
    If the object being matched is null, the instanceof check will return false, so you don’t have to handle nulls manually.

Benefits:

  • Simplifies code structure.
  • Eliminates the need for verbose casting.
  • Improves readability and reduces errors associated with unnecessary manual typecasting.

Pattern matching with instanceof is now widely used in modern Java. Make sure you’re using JDK 17 or later to take advantage of this feature!

How to use switch expressions in Java 17

In Java 17, switch expressions provide a more concise and streamlined way to handle conditional logic. This feature was introduced in Java 12 as a preview and made a standard feature in Java 14. Java 17, being a Long-Term Support version, includes this feature as well.

Let me guide you through how to use them.


What Are Switch Expressions?

Switch expressions allow you to:

  1. Return values directly from a switch block (as an expression).
  2. Use concise syntax with the arrow -> syntax.
  3. Prevent fall-through by removing the need for explicit break statements.
  4. Handle multiple case labels compactly.

Switch Expression Syntax

Basic Syntax

switch (expression) {
    case value1 -> result1;
    case value2 -> result2;
    default -> defaultResult;
}
  1. Use -> for expression forms.
  2. A default case is mandatory unless all possible values are handled.
  3. The switch expression evaluates to a single value, which can be assigned to a variable.

Examples

1. Assigning a Value with Switch Expression

package org.kodejava.basic;

public class SwitchExpressionExample {
    public static void main(String[] args) {
        String day = "MONDAY";

        int dayNumber = switch (day) {
            case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> 1;
            case "SATURDAY", "SUNDAY" -> 2;
            default -> throw new IllegalArgumentException("Invalid day: " + day);
        };

        System.out.println("Day Group: " + dayNumber);
    }
}
  • Explanation:
    • Multiple case labels like "MONDAY", "TUESDAY" are handled via commas.
    • Default throws an exception if the input doesn’t match any case.

2. Block Syntax with yield

For cases where a more complex computation is needed, you can use a code block and yield to return a value.

package org.kodejava.basic;

public class SwitchExpressionWithYieldExample {
    public static void main(String[] args) {
        String grade = "B";

        String message = switch (grade) {
            case "A" -> "Excellent!";
            case "B" -> {
                int score = 85;
                yield "Good job! Your score is " + score;
            }
            case "C" -> "Passed.";
            default -> {
                yield "Invalid grade.";
            }
        };

        System.out.println(message);
    }
}
  • Explanation:
    • Use {} to enclose a block, and yield to specify the value to return.

3. Enhanced Switch with Enums

Switch expressions work great with enums, promoting type safety and readability.

package org.kodejava.basic;

public class SwitchWithEnums {
    enum Day {
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
    }

    public static void main(String[] args) {
        Day today = Day.FRIDAY;

        String dayType = switch (today) {
            case SATURDAY, SUNDAY -> "Weekend";
            case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";
        };

        System.out.println("Today is a " + dayType);
    }
}
  • Explanation:
    • Using enums eliminates the need for default because all cases are covered.

4. Using Switch in a Method

You can use switch expressions for cleaner and more concise methods.

package org.kodejava.basic;

public class SwitchInMethodExample {
    public static void main(String[] args) {
        System.out.println(getSeason(3)); // Output: Spring
    }

    static String getSeason(int month) {
        return switch (month) {
            case 12, 1, 2 -> "Winter";
            case 3, 4, 5 -> "Spring";
            case 6, 7, 8 -> "Summer";
            case 9, 10, 11 -> "Autumn";
            default -> throw new IllegalArgumentException("Invalid month: " + month);
        };
    }
}
  • Explanation:
    • No break is needed, as the return value is implicit in switch expressions.

Key Features to Remember

  1. No need for break statements.
  2. Use -> for one-liner cases.
  3. Use yield to return values from block-style cases.
  4. Works well with var for type inference.

Switch expressions simplify many patterns while keeping your code readable and concise!

How to leverage Java 10’s Thread-Local Handshakes for performance tuning

Java 10 introduced Thread-Local Handshakes as a powerful feature in the JVM, designed to improve the performance and responsiveness of applications, especially in scenarios involving thread-based operations and garbage collection.

Here’s what you need to know about Thread-Local Handshakes and how to leverage them for performance tuning:


1. What are Thread-Local Handshakes?

Thread-Local Handshakes allow a thread to execute a callback function locally without stopping all threads. This contrasts with traditional global safepoints in Java, where all threads must come to a safe state before any work can be done, such as garbage collection or code deoptimization.

In other words:

  • A handshake is a mechanism to perform operations on a subset of threads (or even individual threads) without stopping the entire JVM.
  • This is useful for operations that don’t require a global JVM safepoint, improving responsiveness and reducing latency.

2. Benefits of Thread-Local Handshakes

  • Avoids Global Safepoints: Operations can target some threads or a single thread, meaning other threads continue their work unaffected.
  • Reduces Latency: No need to pause all threads, improving performance for multithreaded applications.
  • Fine-Grained Control: Perform thread-specific tasks like flushing thread-specific memory buffers, deoptimizing code for just one thread, or collecting specific thread-local objects without interrupting the entire JVM.

3. Use Cases

Here are some scenarios where Thread-Local Handshakes can be beneficial:

  • Garbage Collection
    Garbage collectors rely on safepoints to pause threads while managing memory. Thread-Local Handshakes can isolate such operations to only the threads that need it, reducing pause times and improving application throughput.

  • Code Deoptimization
    This happens during just-in-time (JIT) compilation when compiled code needs to revert to interpreted mode. Utilizing handshakes allows deoptimization to occur on specific threads, minimizing the impact on other threads.

  • Thread-Specific Profiling and Debugging
    A developer or monitoring agent can perform profiling or diagnostic tasks on a single thread without disturbing other threads.

  • Thread-Specific Resource Cleanup
    Thread-local data structures can be cleaned up or flushed for specific threads, optimally managing system resources.


4. How Thread-Local Handshakes Work Internally

Thread-Local Handshakes introduce thread-specific “safepoints.” When a request is initiated:

  1. The JVM signals specific threads to execute a callback function (like releasing resources or processing pending tasks).
  2. Unlike global safepoints, only the targeted thread(s) pause and execute the operation.
  3. Once the operation is complete, the thread resumes execution.

This makes operations more granular and non-blocking at the JVM level.


5. Leveraging Thread-Local Handshakes in Performance Tuning

Although Thread-Local Handshakes are implemented at the JVM level, you can indirectly leverage them for performance tuning in the following ways:

  1. Tuning for Garbage Collection
    If you’re using a garbage collector like G1GC or ZGC, you can reduce garbage collection pauses since these collectors take advantage of handshakes to avoid halting all threads during certain operations.

    • How to Monitor: Use tools like Java Mission Control (JMC), VisualVM, or JVM logging to monitor GC pause times and ensure thread-local synchronization is being effectively utilized.

    Relevant JVM Options:

    • -XX:+UseG1GC (or any GC of choice) to enable advanced garbage collection strategies.
    • Use -Xlog:gc to monitor GC logs and observe pauses.
  2. Reducing Latency in Thread-Sensitive Applications
    If your application uses many threads (e.g., for handling requests or background tasks), Thread-Local Handshakes reduce overall latency by targeting specific threads instead of pausing all threads unnecessarily.

    Best practices:

    • Profile your application for thread contention and safepoints using tools like Async Profiler or JFR (Java Flight Recorder).
    • Optimize thread management through thread pools (using ForkJoinPool, ThreadPoolExecutor, etc.) to prevent thread starvation and maximize throughput.
  3. Tuning Thread-Specific Tasks
    For tasks that manipulate thread-local data or thread-specific settings:

    • Optimize performance by ensuring the work is allocated to specific threads that need operations (e.g., specific callbacks).
    • Reduce contention by designing operations that leverage locality (thread-local memory, caches, etc.).

6. Practical Tips for Developers

While Thread-Local Handshakes are managed by the JVM, the following tips help you align your code and architecture to take full advantage:

  1. Choose Modern JVMs: Use JDK 10 or later for applications where fine-grained thread optimization matters. Newer garbage collectors like ZGC or Shenandoah optimize handshakes even further.

  2. Monitor Safepoints and Utilization:

    • Safepoint statistics can be enabled using -XX:+PrintSafepointStatistics to understand how your threads interact with JVM-managed resources.
    • Use tools like JFR to detect safepoint delays or thread-local handshake activity.
  3. Minimize Global Syncs in Application Code:
    • Avoid global thread synchronization where possible.
    • Use thread-local structures (e.g., ThreadLocal API) for thread-scoped data.
  4. Benchmark Your Application:
    Profile how your code interacts with the JVM and threads. Use tools like JMH (Java Microbenchmark Harness) for thread and synchronization benchmarking.


7. Example: Monitoring Thread Safepoints

java -XX:+PrintSafepointStatistics -XX:PrintSafepointStatisticsCount=1 -XX:+LogVMOutput -XX:LogFile=safepoints.log -jar YourApp.jar

This will output safepoint-related logs, showing where Thread-Local Handshakes may improve performance by reducing pauses.


8. Conclusion

Thread-Local Handshakes represent an evolutionary step in how the JVM manages thread interactions, replacing costly global operations with thread-targeted approaches. While you may not directly invoke or control handshakes, you can optimize your application and JVM configuration to reap their benefits:

  • Select JVM options and garbage collection strategies that leverage handshakes.
  • Profile and diagnose thread safepoints to find opportunities for performance tuning.

These adjustments ensure better efficiency, reduced latency, and improved performance in multithreaded applications.

How do I secure API requests with OAuth2 using Java 11 HttpClient?

Securing API requests with OAuth2 using Java 11’s HttpClient involves obtaining an access token from the OAuth2 provider and including it in the header of your HTTP requests. Here’s a step-by-step guide:

1. Understand OAuth2 Flow

OAuth2 involves several flows (e.g., Authorization Code, Client Credentials, etc.). For simplicity, we’ll focus on the Client Credentials Grant flow where your application (client) authenticates with the OAuth2 provider and retrieves an access token for API calls.

2. Dependencies

You don’t need external dependencies unless you choose to use a library (like Spring Security). Java 11’s HttpClient can directly process token requests.

3. Steps to Secure API Requests

Obtain Access Token

To obtain an access token, make a POST request to the OAuth2 token endpoint with the required parameters:

  • client_id: Your application’s client ID.
  • client_secret: Your application’s secret key.
  • grant_type: For example, client_credentials.

Use the Access Token in API Requests

Once you have the access token, include it in the Authorization header of your requests.

4. Sample Code

Here’s an example of how to secure API requests with OAuth2 using Java 11’s HttpClient:

package org.kodejava.net.http;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class OAuth2HttpClient {

   public static void main(String[] args) throws Exception {
      // OAuth2 Token Endpoint and Client Details
      String tokenEndpoint = "https://your-oauth2-provider.com/token";
      String clientId = "your-client-id";
      String clientSecret = "your-client-secret";
      String scope = "your-api-scope";

      // Step 1: Obtain Access Token
      String accessToken = getAccessToken(tokenEndpoint, clientId, clientSecret, scope);

      // Step 2: Use Access Token for API Request
      String apiEndpoint = "https://api.example.com/secure-resource";
      sendSecureApiRequest(apiEndpoint, accessToken);
   }

   private static String getAccessToken(String tokenEndpoint, String clientId, String clientSecret, String scope) throws Exception {
      // Create request body
      String requestBody = "grant_type=client_credentials" +
                           "&client_id=" + URLEncoder.encode(clientId, StandardCharsets.UTF_8) +
                           "&client_secret=" + URLEncoder.encode(clientSecret, StandardCharsets.UTF_8) +
                           "&scope=" + URLEncoder.encode(scope, StandardCharsets.UTF_8);

      // Create HttpClient and HttpRequest
      HttpClient client = HttpClient.newHttpClient();
      HttpRequest request = HttpRequest.newBuilder()
              .uri(URI.create(tokenEndpoint))
              .header("Content-Type", "application/x-www-form-urlencoded")
              .POST(HttpRequest.BodyPublishers.ofString(requestBody))
              .build();

      // Send request and parse response
      HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
      if (response.statusCode() == 200) {
         // Extract access token from JSON response
         String responseBody = response.body();
         return extractAccessToken(responseBody);
      } else {
         throw new RuntimeException("Failed to get access token. Status: " + response.statusCode() + ", Body: " + response.body());
      }
   }

   private static String extractAccessToken(String responseBody) {
      // Parse JSON response to extract the "access_token" (you can use a library like Jackson or Gson)
      // For simplicity, assume the response contains: {"access_token":"your-token"}
      int startIndex = responseBody.indexOf("\"access_token\":\"") + 16;
      int endIndex = responseBody.indexOf("\"", startIndex);
      return responseBody.substring(startIndex, endIndex);
   }

   private static void sendSecureApiRequest(String apiEndpoint, String accessToken) throws Exception {
      // Create HttpClient and HttpRequest
      HttpClient client = HttpClient.newHttpClient();
      HttpRequest request = HttpRequest.newBuilder()
              .uri(URI.create(apiEndpoint))
              .header("Authorization", "Bearer " + accessToken)
              .GET()
              .build();

      // Send request and print response
      HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
      System.out.println("API Response Status: " + response.statusCode());
      System.out.println("API Response Body: " + response.body());
   }
}

5. Explanation

  1. Obtaining Access Token:
    • A POST request is sent to the token endpoint with appropriate parameters in the body.
    • The response typically returns an access token in JSON format.
  2. Secure API Request:
    • Include the token in the Authorization header as Bearer <token> in subsequent requests to the secured API.
  3. Error Handling:
    • If the token request or API request fails, handle the error gracefully (e.g., retry or log).

6. Security Tip

  • Never hardcode client_id or client_secret in your code. Store them securely (e.g., environment variables or a secrets manager).
  • If you handle sensitive data, ensure your OAuth2 provider supports HTTPS.

How do I log request and response details using Java 11 HttpClient?

If you are using Java 11’s HttpClient and want to log request and response details, you can achieve this by implementing a custom utility. Java 11’s HttpClient provides flexibility to log and inspect both requests and responses using its APIs. Here’s how you can log them:

Full Implementation for Logging Request and Response

Below is an example that demonstrates logging details such as HTTP headers, request body, response status, response headers, and response body.

package org.kodejava.net.http;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class HttpClientLogger {

   public static void main(String[] args) {
      try {
         // Create a sample HTTP GET request
         HttpClient httpClient = HttpClient.newHttpClient();

         HttpRequest request = HttpRequest.newBuilder()
                 .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
                 .GET()
                 .header("Accept", "application/json")
                 .timeout(Duration.ofSeconds(10))
                 .build();

         // Log Request Details
         logRequestDetails(request);

         // Send the request and receive a response
         HttpResponse<String> response = httpClient.send(request,
                 HttpResponse.BodyHandlers.ofString());

         // Log Response Details
         logResponseDetails(response);

      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   private static void logRequestDetails(HttpRequest request) {
      System.out.println("---- HTTP Request Details ----");
      System.out.println("Method: " + request.method());
      System.out.println("URI: " + request.uri());
      System.out.println("Headers: " + request.headers().map());
      request.bodyPublisher().ifPresentOrElse(
              bodyPublisher -> {
                 System.out.println("Request Body: (BodyPublisher details not directly accessible, consider passing it explicitly)");
              },
              () -> System.out.println("Request Body: No body")
      );
      System.out.println("-------------------------------");
   }

   private static void logResponseDetails(HttpResponse<String> response) {
      System.out.println("---- HTTP Response Details ----");
      System.out.println("Status Code: " + response.statusCode());
      System.out.println("Headers: " + response.headers().map());
      System.out.println("Body: " + response.body());
      System.out.println("--------------------------------");
   }
}

Explanation of the Code

  1. Setting up HttpClient:
    • We create a HttpClient instance using HttpClient.newHttpClient().
  2. Building the HttpRequest:
    • Use the HttpRequest.Builder to construct the request. This includes setting the URI, method, headers, and a timeout.
  3. Logging HTTP Request Details:
    • Log details of the request by accessing:
      • HTTP Method: HttpRequest::method
      • URI: HttpRequest::uri
      • Headers: HttpRequest::headers
      • The request body can be logged if you manually supply it during the request creation since BodyPublisher doesn’t provide a content preview.
  4. Sending the Request:
    • Use HttpClient::send to perform the HTTP operation, and specify HttpResponse.BodyHandlers.ofString() to read the response as a string.
  5. Logging HTTP Response Details:
    • Log response information:
      • Status Code: HttpResponse::statusCode
      • Headers: HttpResponse::headers
      • Body: HttpResponse::body

Notes

  1. POST/PUT Requests with a Body:
    • If you are sending POST or PUT requests that include a body (e.g., JSON or a form), you should explicitly log the body content when building the request. Example:
      HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
            .POST(HttpRequest.BodyPublishers.ofString("{\"key\":\"value\"}"))
            .header("Content-Type", "application/json")
            .build();
      

      To log the request body, simply store it in a separate variable and print it in logRequestDetails.

  2. Production Logging:

    • Avoid directly printing details to the console in production.
    • Use proper logging libraries like SLF4J with an implementation (e.g., Logback or Log4j) to write logs at different levels like DEBUG, INFO, ERROR, etc.
  3. Sensitive Data:
    • Avoid logging sensitive details like authentication headers or personal data (e.g., Authorization tokens, passwords).

This approach provides a reusable template for logging HTTP requests and responses while using the Java 11+ HttpClient.