Pregunta

I have the following infinite loop which listens for incoming messages:

public static void listenForMessages(){
          while (true) {

                dsocket.receive(receivepacket);
                byte[] rcvMsg = receivepacket.getData();



                MessageCreator tmc = new MessageCreator();
                TrafficMessage message = tmc.constructMessageFromBinary(rcvMsg);

                System.out.println("message: "+message);


        }
 }

This calls a method that reads the byte array into a string and populates a message object.

public Message constructMessageFromBinary(byte[] rcvMsg)
            throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(rcvMsg);
        DataInputStream dis = new DataInputStream(bais);
        StringBuffer inputLine = new StringBuffer();
        String tmp; 

        while ((tmp = dis.readLine()) != null) {
            inputLine.append(tmp);

        }

    dis.close();

        Message message = new Message();
        message.setDescriptions(tmp);

        return message;

    }

This simple process slowly leaks memory over a few hours and I receive an out of memory exception.

Is there anything wrong with this logic?

¿Fue útil?

Solución

The problem was that I left a database connection open. I wanted to leave it open to pass data with out having to worry about stopping and starting connections. I now open and close connections each time and all is good.

Otros consejos

The best bet here would be to move all possible object instantiations outside the loops. For example, in the first code snippet, every iteration creates a

MessageCreator tmc.

On your second snippet, each call to the method creates a

StringBuffer inputLine.

This instantiation process may be eating away your memory slowly.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top