usage of Nano-Timestamp while at linebased reading from socket

18 hours ago 3
ARTICLE AD BOX

I have a piece of software, which implements a native socket server and offers via port 5555 linebased sentences (e.g. NMEA data).

package org.example; import java.io.*; import java.net.*; public class NMEASocketServer { static String nmeaSentence = "$WIMWV,357.0,R,5.2,M,A*1A\r\n$WIMWV,123.0,T,5.2,M,A*1A\r\n"; static void main(String[] args) { try (ServerSocket serverSocket = new ServerSocket(5555)) { System.out.println("Waiting..."); Socket clientSocket = serverSocket.accept(); System.out.println("Client connected: " + clientSocket.getInetAddress()); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); while (true) { out.write(nmeaSentence); out.flush(); System.out.print("Sending NMEA sentence: " + nmeaSentence); Thread.sleep(500); } } catch (Exception e) { System.out.println("Socket-Error: " + e.getMessage()); e.printStackTrace(); } } }

Then I have a client, which connects to this server (running on the same machine) and consumes linebased data. The client prints out the data incl. the current timestamp in nanos.

package org.example; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; import java.time.Instant; import java.time.temporal.ChronoUnit; public class Main { private static String getNanoTime() { return String.valueOf(Instant.now().truncatedTo(ChronoUnit.NANOS)); } static void main() throws IOException { Socket socket = new Socket("localhost", 5555); socket.setTcpNoDelay(true); InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is); StringBuilder sb = new StringBuilder(); int ch; while ((ch = isr.read()) != -1) { if (ch == '\n') { System.out.println(getNanoTime() + " " + sb.toString()); sb = new StringBuilder(); } else if (ch != '\r') { sb.append((char) ch); } } } }

The output is, e.g.:

2026-04-16T18:09:55.375949100Z $WIMWV,357.0,R,5.2,M,A*1A 2026-04-16T18:09:55.376947700Z $WIMWV,123.0,T,5.2,M,A*1A 2026-04-16T18:09:55.877866900Z $WIMWV,357.0,R,5.2,M,A*1A 2026-04-16T18:09:55.877866900Z $WIMWV,123.0,T,5.2,M,A*1A 2026-04-16T18:09:56.378914500Z $WIMWV,357.0,R,5.2,M,A*1A 2026-04-16T18:09:56.379800300Z $WIMWV,123.0,T,5.2,M,A*1A 2026-04-16T18:09:56.880072500Z $WIMWV,357.0,R,5.2,M,A*1A 2026-04-16T18:09:56.880072500Z $WIMWV,123.0,T,5.2,M,A*1A

So, the nano-timestamps of the two sentences sent together from the server side, is identical (e.g. output lines 3&4 or 7&8). Sometimes there are several microseconds in between (e.g. lines 1&2 or 5&6). Can somebody explain, if this behaviour is realistic? Is it possible to read so fast from a socket, build the String and print it on System.out, that these two timestamps are identical?

Read Entire Article