1

I have the following loop that listens for UDP messages coming in

 public void run(){

 int count = 0;
        boolean loopRecv = true;
        while (loopRecv) {
                count++;
                if (count == 500) {
                    loopRecv = false;
                    System.out.println("break from loop");

                    count = 0;


                }
            }
 }

The problem is that within a few hours, I receive an out of memory exception. Also I am monitoring the memory in Top and it is growing slowly.

I thought that breaking from this loop would remove that allocated stack frames, but this doesn't seem to be the case.

How can i run this loop without receiving the out of memory error?

Atma
  • 29,141
  • 56
  • 198
  • 299

4 Answers4

5

Every 500 iterations of your while loop, you call back into run.

run()
.
. 500 iterations
.
   run()
   .
   .
   . 500 iterations
   .
      run()

Your loopRecv boolean is not doing anything. Though you set loopRecv to false, you immediately make the recursive call, rendering the boolean assignment useless! Hence, the StackOverflowError. Instead, why don't you just find a way to implement your method iteratively instead? Consider breaking to a label. It's not very clear what your function accomplishes.

Amir Afghani
  • 37,814
  • 16
  • 84
  • 124
0

You're recursively calling the method every time count == 500. This slows down the StackOverflowError, but it will still happen.

Remove the call to run() from the inside of the while loop and it shouldn't error anymore.

Robert Mitchell
  • 892
  • 7
  • 9
0

The common StackOverFolow error comes with an infinity recursive loop that has no terminal and calls itself continuously, in your case, your calling run () even after the condition is true , so if you declare a break point to the while loop you won't get the error.

I am interested of asking why you are calling run () after a condition is true? Is it the matter of interesting or you have some purpose?

Azad
  • 5,047
  • 20
  • 38
0

The problem was that I was opening a database connection before the run and not closing it.

Atma
  • 29,141
  • 56
  • 198
  • 299