Post

Java Http

Recently, I was bite by a httpServer issue that the connection hangs at below os.write step. A quick google search tells me that it is probably the client does not close connection properly, so we need to set a timeout for socket connection.

1
2
3
4
            OutputStream os = exchange.getResponseBody();
            os.write(resp.body().getBytes());
            os.close();

I took this chance to read a little bit of openjdk code. The relevant code is here. There is no request or response socket timeout by default. However, if request or response timeout is set, http server will schedule a cron job to check connections periodically and close old connections if needed.

Also, it is interesting to learn how httpserver labels connections. When the server has received the complete request, it switches the connection state from State.REQUET to State.RESPONSE. See code. And once the response has been completely sent back to the client, the state is changed to State.IDLE. There is a dedicated Timer job to close idle connections.

So for our problem, we get stuck at sending response body to client, so we should add a response timeout by add setting sun.net.httpserver.maxRspTime.

Reactive

There are multiple different styles of async programming from early nodejs’s callback style, future chains in Java/C++, to async/await coroutines in python, C#, C++, Rust. Golang has builtin goroutines.

Here reactive programming is yet another pattern. It is a publisher/subscriber pattern on stream. I do not believe the future of it, as in my opinion, it is too functional-programming. It has a single paradigm that forces you to write a chain. On the other hand, async/await is much more flexible. But for learning purpose, it deserves a try.

Basic

https://projectreactor.io/docs/core/release/reference/

Libs

  • reactor-netty

    I cloned the repo to accommodate some intellij changes.

This post is licensed under CC BY 4.0 by the author.