GCP Serverless Function in Java with 15Mb RAM

 The blog is more about experimenting with Java Native build to achieve less RAM use.

Usually, when using Java as a runtime for Google Cloud functions (https://cloud.google.com/functions/docs/concepts/java-runtime) the average RAM footprint is about 140 MB for a simple REST API Jax-RS based endpoint with JSON (text) static response. For example, the same example in Golang (one HTTP GET method) with JSON response is around 30 MB RAM.

To try to achieve less RAM footprint with Java (e.g. to use 128 MB GCP tier), let us try to use:

  1. - Java Socket as very simple HTTP server
  2. - GraalVM Native build
  3. - Docker
  4. - Google Cloud Run to use custom Docker image as an app

Java code

Source codehttps://github.com/ahndmal/http-simple-sock-native

We create ServerSocket and accept connections on port 8080:


try (ServerSocket serverSocket = new ServerSocket(8080)) {
                System.out.println(">>> Server started on port 8080");

 while(true) {
    Socket accept = serverSocket.accept();

    System.out.println("> client connected");

    InputStream inputStream = accept.getInputStream();
    OutputStream outputStream = accept.getOutputStream();
   ...
}

We create IO streams to get requests and write data to the output (browser) as a static HTTP GET response.
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream));

writer.write("HTTP/1.1 200 OK\n");
writer.write("Content-Type: text/html\r\n\n");
writer.write("""
   <!doctype html><html>
   <head><title>Java</title></head>
   <body>
   <h2>Java Server</h2>
   <div>Test</div>
   </body>
   </html>""");

We can just use any HTML file and read its contents for a response instead of this hardcoded text.

Comments

Popular posts from this blog

How to update Contents in Confluence via REST API