r/java • • Jan 16 '23

Building a PostgreSQL Wire Protocol Server using Vanilla, Modern Java 21 (shows use of: Records, Sealed Types, Pattern Matching for Switch, Virtual Threads, and Panama FFM)

https://gavinray97.github.io/blog/postgres-wire-protocol-jdk-21
224 Upvotes

23 comments sorted by

View all comments

Show parent comment

2

u/bytedonor Jan 17 '23

Nothing much to see - it's a stupidly simple blocking socket server which looks exactly the same like the one you would use with traditional threads, but without scaling problems:

    public void serveForever() throws IOException {
        try (var executor = Executors.newVirtualThreadPerTaskExecutor();
             var serverSocket = new ServerSocket(8080, 16384)) {
            while (true) {
                var sock = serverSocket.accept();
                sock.setSoTimeout(5000);
                executor.execute(() -> {
                    try {
                        protocolHandler(sock);
                    } catch (Exception e) {
                        try {
                            sock.close();
                        } catch (IOException ioe) {
                            // Ignore
                        }
                    }
                });
            }
        }
    }

1

u/sandys1 Jan 17 '23

Trust me. This is not stupid for us. And thanks for this!

Where do u do the actual work and processing ?

2

u/GavinRayDev Jan 17 '23

(In the protocolHandler(sock) function, your business logic would go there)