Context in Java

Here’s the translation of the Go code to Java, along with explanations in Markdown format suitable for Hugo:

In the previous example, we looked at setting up a simple HTTP server. HTTP servers are useful for demonstrating the usage of cancellation and timeout mechanisms in Java. While Java doesn’t have a direct equivalent to Go’s context.Context, we can achieve similar functionality using java.util.concurrent classes.

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class ContextExample {

    static class HelloHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            System.out.println("server: hello handler started");

            try {
                // Simulate some work
                boolean completed = Executors.newSingleThreadExecutor().submit(() -> {
                    try {
                        Thread.sleep(10000); // Sleep for 10 seconds
                        return true;
                    } catch (InterruptedException e) {
                        return false;
                    }
                }).get(5, TimeUnit.SECONDS); // Wait for 5 seconds max

                if (completed) {
                    String response = "hello\n";
                    exchange.sendResponseHeaders(200, response.length());
                    PrintWriter out = new PrintWriter(exchange.getResponseBody());
                    out.println(response);
                    out.close();
                } else {
                    throw new InterruptedException("Operation timed out");
                }
            } catch (Exception e) {
                System.out.println("server: " + e.getMessage());
                String error = "Internal Server Error";
                exchange.sendResponseHeaders(500, error.length());
                PrintWriter out = new PrintWriter(exchange.getResponseBody());
                out.println(error);
                out.close();
            } finally {
                System.out.println("server: hello handler ended");
            }
        }
    }

    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(8090), 0);
        server.createContext("/hello", new HelloHandler());
        server.setExecutor(null);
        server.start();

        System.out.println("Server started on port 8090");
    }
}

In this Java example, we’ve created an HTTP server that demonstrates a concept similar to Go’s context cancellation. Here’s a breakdown of what’s happening:

  1. We create an HTTP server listening on port 8090.

  2. We define a HelloHandler class that implements the HttpHandler interface. This is where we handle requests to the “/hello” endpoint.

  3. In the handle method, we simulate some work that takes 10 seconds to complete. However, we use Executors.newSingleThreadExecutor().submit() and Future.get() with a timeout of 5 seconds to implement a cancellation mechanism.

  4. If the work completes within 5 seconds, we send a “hello” response. If it doesn’t, we throw an InterruptedException.

  5. We use try-catch blocks to handle exceptions and send appropriate error responses.

  6. In the main method, we set up the server and start it.

To run the server:

$ javac ContextExample.java
$ java ContextExample

The server will start and listen on port 8090.

To test the server, you can use curl in another terminal:

$ curl http://localhost:8090/hello

If you run this command, you’ll see that the request times out after 5 seconds, demonstrating the cancellation mechanism.

This example shows how to implement a simple cancellation mechanism in Java, which is conceptually similar to Go’s context package. While the implementation details differ, the core concept of managing request lifecycles and cancellations remains the same.

查看推荐产品