The code which made me sleepless last night.

I wrote a small piece of code which basi­cal­ly lis­tens to JMS queue and receives mes­sages. The fol­low­ing 3 code snips shows what I want­ed to do.
The snip on left is the improved and refac­tored code and the one on the right is the bad code.

In this fol­low­ing snip I tried to cre­ate a queue and receive mes­sages in it.

[ Click to enlarge the image ]

The mis­take I did here, as can be seen in the right hand side is, I cre­ate the queue and also receive mes­sages in it, both in the same method.

In the fol­low­ing snip, I am call­ing the method to receive mes­sags in the queue but what I over­looked is that I am also cre­at­ing the queue in it. This is the where the dis­as­ter is lurk­ing.

[ Click to enlarge the image ]

So even if I close ses­sion and con­nec­tion in the fol­low­ing snip, it just clos­es the last con­nec­tion.

[ Click to enlarge the image ]

Where­as I have cre­at­ed hell lot of con­nec­tions in snip‑2, ( Notice the while loop, which was churn­ing umpteen num­ber of queue con­nec­tions )
I am only clos­ing the last con­nec­tion in snip‑3 which leaves thou­sands of con­nec­tions opened in mem­o­ry. This trig­gered garbage col­lec­tion which took about 12 – 13% of CPU con­sis­tent­ly even if noth­ing was pro­cess­ing in the sys­tem.

This demon­strates the side effects of try­ing to do too many things in a sin­gle method. Also it is very impor­tant to han­dle con­nec­tions, whether datab­se / JMS / sock­ets very very care­ful­ly. This made me sleep­less for a night.



Leave a Reply

%d bloggers like this: