Context in Mercury

Here’s the translated code and explanation in Java, formatted for Hugo:

Our first example demonstrates how to use Context in a Java HTTP server. In Java, we don’t have an exact equivalent of Go’s context.Context, but we can achieve similar functionality using other mechanisms.

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

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

public class ContextExample {

    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(8090), 0);
        server.createContext("/hello", new HelloHandler());
        server.setExecutor(Executors.newCachedThreadPool());
        server.start();
        System.out.println("Server started on port 8090");
    }

    static class HelloHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            System.out.println("server: hello handler started");
            try {
                String response = "hello\n";
                exchange.sendResponseHeaders(200, response.length());
                OutputStream os = exchange.getResponseBody();
                os.write(response.getBytes());
                os.close();
            } finally {
                System.out.println("server: hello handler ended");
            }
        }
    }
}

In this Java example, we’re using the com.sun.net.httpserver package to create a simple HTTP server. While Java doesn’t have a direct equivalent to Go’s context.Context, we can achieve similar functionality using other mechanisms.

The HelloHandler class implements the HttpHandler interface, which is similar to the handler function in the Go example. The handle method is called for each incoming request to the “/hello” endpoint.

To simulate work being done by the server, you could add a delay using Thread.sleep(). However, unlike Go’s example where we can easily cancel the operation using the context, in Java we would need to implement our own cancellation mechanism, possibly using Future or CompletableFuture.

To run the server:

$ javac ContextExample.java
$ java ContextExample
Server started on port 8090

You can then make a request to the server:

$ curl localhost:8090/hello
hello

In the server logs, you would see:

server: hello handler started
server: hello handler ended

Note that this Java example doesn’t implement the cancellation functionality shown in the Go example. To achieve that in Java, you would need to use more complex concurrency utilities like ExecutorService with Futures, or reactive programming libraries like RxJava or Project Reactor.