Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7161619
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T13:35:51+00:00 2026-05-28T13:35:51+00:00

I’ve got a simple socket server (it is for HL7 communication). When it runs

  • 0

I’ve got a simple socket server (it is for HL7 communication). When it runs longer in production, socket threads hang and consume a lot of CPU time.

This is the relevant code (shortened) for the listener thread:

public void run() {
    try {
        serverSocket = new ServerSocket(port, backlog, bindAddress);
        serverSocket.setSoTimeout(timeout); // 1000 ms
        do {
            Socket socket = null;
            try {
                socket = serverSocket.accept();
            } catch (SocketTimeoutException to) {
                socket = null;
            } catch (InterruptedIOException io) {
                socket = null;
            } catch (IOException e) {
                logger.fatal("IO exception while socket accept", e);
                socket = null;
            }

            try {
                if (socket != null)
                    processConnection(socket);
            } catch (RuntimeException e) {
                logger.fatal("caught RuntimeException trying to terminate listener thread", e);
            }
        } while (running);
    } catch (IOException e) {
        logger.fatal("error binding server socket - listener thread stopped", e);
    }
}

This code starts a new thread for processing an incoming connection:

protected void processConnection(Socket socket) {
    Hl7RequestHandler requestHandler = createRequestHandler();
    requestHandler.setSocket(socket);
    requestHandler.start();
}

This is the code for the request handler thread (keepAlive is set to true):

public void run() {
    try {
        setName("Hl7RequestHandler-" + socket.getPort());
        processRequest();
    } catch (IOException e) {
        logger.fatal("IO exception during socket communication", e);
    }
}

public void processRequest() 
throws IOException {
    socket.setSoTimeout(socketTimeout); // 1000 ms

    InputStream inputStream = socket.getInputStream();
    OutputStream outputStream = socket.getOutputStream();

    BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream, encoding));
    Writer outputWriter = new OutputStreamWriter(outputStream, encoding);

    int timeouts = 0;
    boolean failure = false;
    do {
        StringBuilder message = new StringBuilder();
        try {
            char c;
            do {
                c = (char)inputReader.read();
                if ((c == CARRIAGE_RETURN || c == START_OF_MESSAGE) &&
                    message.length() == 0)
                else if (c != END_OF_MESSAGE && ((short)c) != -1)
                    // ein Byte "Nutzlast"
                    message.append(c);
            } while (c != END_OF_MESSAGE && ((short)c) != -1);
        } catch (SocketTimeoutException te) {
            timeouts++;
            if(!keepAlive && timeouts >= 3 ) {
                socket.close();
                return;
            }
        }

        String messageStr = message.toString();
        if (messageStr.length() == 0)
            continue;

        failure = !processMessage(messageStr, outputWriter);
        outputWriter.flush();
        outputStream.flush();

        // nächste Runde?
        if (!keepAlive || failure)
            socket.close();
    } while (keepAlive && !failure);
}

When I test this locally, it works well.

But in production, there are multiple request handler threads that “hang”. “Keep Alive” is ment to hold open the connection waiting for more messages. (To avoid opening up new connections all the time.) I assume inputReader.read() returns -1 after the timeout of 1s, which results in calling the method just again. Why does this eat up all the CPU time?

Have you got any advice?

Thanks in advance,
Matthias

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T13:35:51+00:00Added an answer on May 28, 2026 at 1:35 pm

    One thing I can see straight off is this :

             char c;
            do {
                c = (char)inputReader.read();
                if ((c == CARRIAGE_RETURN || c == START_OF_MESSAGE) &&
                    message.length() == 0)
                else if (c != END_OF_MESSAGE && ((short)c) != -1)
                    // ein Byte "Nutzlast"
                    message.append(c);
            } while (c != END_OF_MESSAGE && ((short)c) != -1);
    

    is the cast of the inputReader.read() to char. BufferedReader.read() returns an int, a signed value. You cast it to char that is an unsigned value, discarding the negative sign if there is one, a narrowing conversion. Then converting to short is not bringing back the negative sign if there was one.
    Try rewriting as :

             char c;
             int val;
            do {
                val = inputReader.read();
                // do this if you want, you don't have to
                c = (char) val;
                if ((c == CARRIAGE_RETURN || c == START_OF_MESSAGE) &&
                    message.length() == 0)
                else if (c != END_OF_MESSAGE && ((short)c) != -1)
                    // ein Byte "Nutzlast"
                    message.append(c);
            } while (c != END_OF_MESSAGE && val != -1);
    

    I’ve taken another look at your loop and I’m confused.

            char c;
            do {
                c = (char)inputReader.read();
                if ((c == CARRIAGE_RETURN || c == START_OF_MESSAGE) &&
                    message.length() == 0)
                else if (c != END_OF_MESSAGE && ((short)c) != -1)
                    // ein Byte "Nutzlast"
                    message.append(c);
            } while (c != END_OF_MESSAGE && ((short)c) != -1);
    

    The logic of your if statements are confusing (to me at least).
    You have no statements for the first if clause, not even an empty statement.
    You have to have either {} or a ; Does your code compile?

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I've got a string that has curly quotes in it. I'd like to replace
Seemingly simple, but I cannot find anything relevant on the web. What is the
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
i got an object with contents of html markup in it, for example: string
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I'm making a simple page using Google Maps API 3. My first. One marker
I want to count how many characters a certain string has in PHP, but
That's pretty much it. I'm using Nokogiri to scrape a web page what has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.